SPB Git

Repository Public

sessions.ts 13.3 KB 182 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : services/control-api/src/core/sessions.ts9 * Module           : core10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { canTransitionSession, type SessionState } from '@mls/contracts';43import type { Tx } from '../db.ts';44import { audit, type Actor } from '../audit.ts';45import { conflict, forbidden, notFound } from './errors.ts';46import { activePolicy, emergencyState } from './policy.ts';4748export type SessionRow = { id: string; profile_id: string; state: SessionState; wanted: 'running' | 'stopped'; start_url: string | null; scope_page_ids: string[]; confirmed_at: string | null; confirmed_by: string | null; state_reason: string; worker_id: string; opaque_ref: string; label: string };49const SELECT = `SELECT s.*, p.worker_id, p.opaque_ref, p.label FROM navigator_sessions s JOIN navigator_profiles p ON p.id = s.profile_id`;50export async function lockSession(tx: Tx, id: string): Promise<SessionRow> {51  const r = (await tx.query(`${SELECT} WHERE s.id=$1 FOR UPDATE OF s`, [id])).rows[0];52  if (!r) throw notFound('session');53  return r;54}55/** Single place where a session changes state. Every transition is validated and journaled. */56export async function transition(tx: Tx, s: SessionRow, to: SessionState, reason: string, actor: Actor, correlationId?: string): Promise<SessionRow> {57  if (s.state === to) return s;58  if (!canTransitionSession(s.state, to)) {59    await audit(tx, { correlationId, actor, action: 'session.transition', targetKind: 'session', targetId: s.id, result: 'refused', detail: { from: s.state, to, reason } });60    throw conflict('invalid_transition', `Transition ${s.state} → ${to} interdite`);61  }62  // Losing the login (or revoking) voids the administrator's confirmation: it must be given again.63  const dropConfirm = to === 'LOGIN_REQUIRED' || to === 'EXPIRED' || to === 'REVOKED' || to === 'FAILED';64  await tx.query(`UPDATE navigator_sessions SET state=$2, state_reason=$3, state_at=now()${dropConfirm ? ", confirmed_at=NULL, confirmed_by=NULL, scope_page_ids='{}'" : ''}${to === 'REVOKED' ? ", revoked_at=now(), wanted='stopped'" : ''} WHERE id=$1`, [s.id, to, reason]);65  await audit(tx, { correlationId, actor, action: 'session.transition', targetKind: 'session', targetId: s.id, result: 'ok', detail: { from: s.state, to, reason } });66  return { ...s, state: to, state_reason: reason, ...(dropConfirm ? { confirmed_at: null, confirmed_by: null, scope_page_ids: [] } : {}) };67}6869export type Lease = { session_id: string; holder_kind: 'human' | 'agent'; holder_id: string; fencing_token: number; expires_at: string };70export async function currentLease(tx: Tx, sessionId: string): Promise<Lease | undefined> {71  return (await tx.query('SELECT * FROM worker_leases WHERE session_id=$1 AND expires_at > now()', [sessionId])).rows[0];72}73/** Exclusive lease with a strictly increasing fencing token. A human always pre-empts an agent; an agent never pre-empts anyone. */74export async function acquireLease(tx: Tx, s: SessionRow, holder: { kind: 'human' | 'agent'; id: string }, ttlSeconds: number): Promise<Lease> {75  const cur = (await tx.query('SELECT * FROM worker_leases WHERE session_id=$1 FOR UPDATE', [s.id])).rows[0] as Lease | undefined;76  const live = cur && new Date(cur.expires_at).getTime() > Date.now();77  if (live && cur.holder_kind === holder.kind && cur.holder_id === holder.id) {78    return (await tx.query(`UPDATE worker_leases SET heartbeat_at=now(), expires_at=now()+make_interval(secs=>$2) WHERE session_id=$1 RETURNING *`, [s.id, ttlSeconds])).rows[0];79  }80  if (live && holder.kind === 'agent') throw conflict('lease_held', 'La session est contrôlée par un autre détenteur.');81  if (live && cur.holder_kind === 'human' && cur.holder_id !== holder.id) throw conflict('lease_held_by_human', 'Un autre administrateur contrôle cette session.');82  return (await tx.query(`INSERT INTO worker_leases(session_id, holder_kind, holder_id, fencing_token, expires_at) VALUES ($1,$2,$3,nextval('fencing_seq'),now()+make_interval(secs=>$4))83    ON CONFLICT (session_id) DO UPDATE SET holder_kind=excluded.holder_kind, holder_id=excluded.holder_id, fencing_token=excluded.fencing_token, acquired_at=now(), heartbeat_at=now(), expires_at=excluded.expires_at RETURNING *`,84    [s.id, holder.kind, holder.id, ttlSeconds])).rows[0];85}86export async function heartbeatLease(tx: Tx, sessionId: string, token: number, ttlSeconds: number): Promise<boolean> {87  return ((await tx.query(`UPDATE worker_leases SET heartbeat_at=now(), expires_at=now()+make_interval(secs=>$3) WHERE session_id=$1 AND fencing_token=$2 AND expires_at > now()`, [sessionId, token, ttlSeconds])).rowCount ?? 0) === 1;88}89export async function dropLease(tx: Tx, sessionId: string, token?: number) {90  await tx.query('DELETE FROM worker_leases WHERE session_id=$1 AND ($2::bigint IS NULL OR fencing_token=$2)', [sessionId, token ?? null]);91}92const restingState = (s: SessionRow): SessionState => (s.confirmed_at ? 'READY' : 'LOGIN_REQUIRED');9394export async function takeover(tx: Tx, sessionId: string, user: Actor, correlationId: string) {95  if ((await emergencyState(tx)).emergency_stop) throw forbidden('emergency_stop', "Arrêt d'urgence engagé.");96  let s = await lockSession(tx, sessionId);97  if (s.state === 'REVOKED') throw conflict('revoked', 'Session révoquée.');98  const pol = await activePolicy(tx);99  const lease = await acquireLease(tx, s, { kind: 'human', id: user.id }, pol.navigator.idleLeaseSeconds);100  if (s.wanted !== 'running') await tx.query("UPDATE navigator_sessions SET wanted='running' WHERE id=$1", [s.id]);101  s = await transition(tx, s, 'MANUAL_CONTROL', 'prise de contrôle humaine', user, correlationId);102  await audit(tx, { correlationId, actor: user, action: 'session.takeover', targetKind: 'session', targetId: s.id, result: 'ok', detail: { fencing: lease.fencing_token } });103  return { session: s, lease };104}105export async function release(tx: Tx, sessionId: string, user: Actor, correlationId: string) {106  let s = await lockSession(tx, sessionId);107  const lease = await currentLease(tx, s.id);108  if (lease && (lease.holder_kind !== 'human' || lease.holder_id !== user.id)) throw forbidden('not_lease_holder', 'Vous ne détenez pas le contrôle.');109  await dropLease(tx, s.id);110  if (s.state === 'MANUAL_CONTROL') s = await transition(tx, s, restingState(s), 'contrôle libéré', user, correlationId);111  return s;112}113/** The administrator, still in manual control, attests the login is done and names the pages the session may be used for. */114export async function confirm(tx: Tx, sessionId: string, user: Actor, pageIds: string[], correlationId: string) {115  const s = await lockSession(tx, sessionId);116  const lease = await currentLease(tx, s.id);117  if (s.state !== 'MANUAL_CONTROL' || !lease || lease.holder_kind !== 'human' || lease.holder_id !== user.id) throw conflict('manual_control_required', 'Confirmez la session pendant que vous la contrôlez.');118  const ok = (await tx.query("SELECT id FROM pages WHERE id = ANY($1::uuid[]) AND status='confirmed'", [pageIds])).rows.map((r) => r.id);119  if (ok.length !== new Set(pageIds).size) throw conflict('page_not_confirmed', 'Chaque page du périmètre doit être confirmée.');120  await tx.query('UPDATE navigator_sessions SET scope_page_ids=$2, confirmed_by=$3, confirmed_at=now() WHERE id=$1', [s.id, ok, user.id]);121  await audit(tx, { correlationId, actor: user, action: 'session.confirm', targetKind: 'session', targetId: s.id, result: 'ok', detail: { pageIds: ok } });122}123export async function setPaused(tx: Tx, sessionId: string, paused: boolean, closeBrowser: boolean, user: Actor, correlationId: string) {124  let s = await lockSession(tx, sessionId);125  if (s.state === 'REVOKED') throw conflict('revoked', 'Session révoquée : créez une nouvelle session.');126  if (paused) {127    await dropLease(tx, s.id);128    s = await transition(tx, s, 'PAUSED', closeBrowser ? 'navigateur fermé' : 'suspendue', user, correlationId);129    if (closeBrowser) await tx.query("UPDATE navigator_sessions SET wanted='stopped' WHERE id=$1", [s.id]);130  } else {131    if ((await emergencyState(tx)).emergency_stop) throw forbidden('emergency_stop', "Arrêt d'urgence engagé.");132    await tx.query("UPDATE navigator_sessions SET wanted='running' WHERE id=$1", [s.id]);133    if (s.state === 'PAUSED') s = await transition(tx, s, restingState(s), 'reprise', user, correlationId);134  }135  return s;136}137export async function revoke(tx: Tx, sessionId: string, user: Actor, correlationId: string) {138  let s = await lockSession(tx, sessionId);139  await dropLease(tx, s.id);140  s = await transition(tx, s, 'REVOKED', 'révoquée', user, correlationId);141  await tx.query("UPDATE navigator_profiles SET status='wiped' WHERE id=$1", [s.profile_id]);142  // Jobs that were waiting on this session cannot proceed automatically.143  await tx.query("UPDATE publication_jobs SET state='QUEUED', locked_by=NULL, locked_until=NULL, fencing_token=NULL, state_reason='session révoquée' WHERE state='PREPARING' AND locked_by=$1 AND NOT EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=publication_jobs.id AND a.phase='submitting')", [s.worker_id]);144  return s;145}146/** Applies what a worker observed (URL class only — never content) to the state machine. */147export async function applyObservation(tx: Tx, s: SessionRow, observed: 'running' | 'stopped' | 'login_required' | 'security_challenge' | 'ok', actor: Actor, urlHost?: string): Promise<SessionRow> {148  if (urlHost !== undefined) await tx.query('UPDATE navigator_sessions SET last_url_host=$2 WHERE id=$1', [s.id, urlHost.slice(0, 200)]);149  if (s.state === 'REVOKED' || s.state === 'PAUSED' || s.state === 'FAILED') return s;150  const human = s.state === 'MANUAL_CONTROL';151  switch (observed) {152    case 'security_challenge':153      // An agent must stop at once. A human already in control keeps it (they are the ones solving it).154      if (!human && s.state !== 'SECURITY_CHALLENGE') { await dropLeaseIfAgent(tx, s.id); return transition(tx, s, 'SECURITY_CHALLENGE', 'vérification de sécurité détectée', actor); }155      return s;156    case 'login_required':157      if (s.state === 'READY' || s.state === 'BUSY') { await dropLeaseIfAgent(tx, s.id); return transition(tx, s, 'EXPIRED', 'connexion requise par le site', actor); }158      if (s.state === 'UNINITIALIZED') return transition(tx, s, 'LOGIN_REQUIRED', 'navigateur prêt, connexion manuelle requise', actor);159      return s;160    case 'running': case 'ok':161      if (s.state === 'UNINITIALIZED') return transition(tx, s, 'LOGIN_REQUIRED', 'navigateur prêt, connexion manuelle requise', actor);162      return s;163    case 'stopped': return s;164  }165}166async function dropLeaseIfAgent(tx: Tx, sessionId: string) { await tx.query("DELETE FROM worker_leases WHERE session_id=$1 AND holder_kind='agent'", [sessionId]); }167168export async function engageEmergencyStop(tx: Tx, engage: boolean, reason: string, user: Actor, correlationId: string) {169  await tx.query('UPDATE system_state SET emergency_stop=$1, reason=$2, changed_by=$3, changed_at=now()', [engage, reason, user.id]);170  let paused = 0;171  if (engage) {172    await tx.query('DELETE FROM worker_leases');173    const rows = (await tx.query(`${SELECT} WHERE s.state NOT IN ('REVOKED','PAUSED') FOR UPDATE OF s`)).rows as SessionRow[];174    for (const s of rows) { await transition(tx, s, 'PAUSED', "arrêt d'urgence", user, correlationId); paused++; }175    await tx.query("UPDATE navigator_sessions SET wanted='stopped' WHERE state <> 'REVOKED'");176    // Prepared-but-unsubmitted work goes back to the queue; anything mid-submission becomes UNKNOWN_OUTCOME via the sweeper.177    await tx.query("UPDATE publication_jobs SET state='QUEUED', locked_by=NULL, locked_until=NULL, fencing_token=NULL, state_reason='arrêt d''urgence' WHERE state='PREPARING' AND NOT EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=publication_jobs.id AND a.phase='submitting')");178  }179  await audit(tx, { correlationId, actor: user, action: engage ? 'emergency.engage' : 'emergency.release', targetKind: 'system', result: 'ok', detail: { reason, paused } });180  return { paused };181}182
Files main
Menu

Theme