SPB Git

Repository Public

auth.ts 7.7 KB 80 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/routes/auth.ts9 * Module           : routes10 * 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 { z } from '@mls/contracts';43import type { Ctx } from '../app.ts';44import { consumeHandoff, cookieName, createHandoff, createSetupLink, loginOptions, loginVerify, logout, registrationOptions, registrationVerify } from '../auth.ts';45import { emergencyState, activePolicy } from '../core/policy.ts';46import { audit } from '../audit.ts';47import { bad } from '../core/errors.ts';4849export function registerAuthRoutes(ctx: Ctx) {50  const { db, cfg, route } = ctx;51  const setCookie = (reply: any, s: { cookie: string; csrf: string }) => { reply.setCookie(cookieName(cfg), s.cookie, { httpOnly: true, secure: cfg.prod, sameSite: 'strict', path: '/', maxAge: cfg.sessionTtlHours * 3600 }); return { ok: true }; };52  route({ method: 'POST', path: '/auth/login/options', summary: 'Défi de connexion par clé d’accès', tag: 'auth', auth: 'public' }, async (req) => loginOptions(db, req.origin));53  route({ method: 'POST', path: '/auth/login/verify', summary: 'Vérifie la clé d’accès et ouvre une session', tag: 'auth', auth: 'public', body: z.object({ state: z.string().max(100), response: z.any() }).strict() }, async (req, reply) => setCookie(reply, await loginVerify(db, cfg, req.origin, req.data.state, req.data.response)));54  route({ method: 'POST', path: '/auth/register/options', summary: 'Défi d’enregistrement (lien d’activation ou session)', tag: 'auth', auth: 'public', body: z.object({ setupToken: z.string().max(100).optional() }).strict() }, async (req) => {55    if (!req.data.setupToken && !req.session) throw bad('setup_required');56    return registrationOptions(db, cfg, req.origin, req.data.setupToken ? { setupToken: req.data.setupToken } : { session: req.session });57  });58  route({ method: 'POST', path: '/auth/register/verify', summary: 'Enregistre la clé d’accès', tag: 'auth', auth: 'public', body: z.object({ state: z.string().max(100), response: z.any(), label: z.string().max(60).default('') }).strict() }, async (req, reply) => setCookie(reply, await registrationVerify(db, cfg, req.origin, req.data.state, req.data.response, req.data.label)));59  route({ method: 'POST', path: '/auth/logout', summary: 'Ferme la session', tag: 'auth', auth: 'user', body: z.object({ everywhere: z.boolean().default(false) }).strict() }, async (req, reply) => { await logout(db, req.cookies[cookieName(cfg)], req.data.everywhere, req.session!.user.id); reply.clearCookie(cookieName(cfg), { path: '/' }); return { ok: true }; });60  route({ method: 'POST', path: '/auth/handoff', summary: 'Ticket à usage unique (60 s) vers l’autre domaine privé', tag: 'auth', auth: 'user', body: z.object({ target: z.enum(['social', 'navigator']) }).strict() }, async (req) => ({ url: await createHandoff(db, cfg, req.session!, req.data.target === 'social' ? cfg.socialOrigin : cfg.navigatorOrigin) }));61  route({ method: 'POST', path: '/auth/handoff/consume', summary: 'Échange le ticket contre une session', tag: 'auth', auth: 'public', body: z.object({ ticket: z.string().min(20).max(100) }).strict() }, async (req, reply) => setCookie(reply, await consumeHandoff(db, cfg, req.origin, req.data.ticket)));62  route({ method: 'GET', path: '/v1/me', summary: 'Utilisateur, jeton CSRF, état global', tag: 'auth', auth: 'user' }, async (req) => {63    const pol = await activePolicy(db);64    const brands = await ctx.visibleBrandIds(req);65    return { user: req.session!.user, csrf: req.session!.csrf, emergency: await emergencyState(db), policyVersion: pol._version, origins: { social: cfg.socialOrigin, navigator: cfg.navigatorOrigin }, brandScope: brands === 'all' ? 'all' : brands, env: cfg.env,66      brandRoles: Object.fromEntries((await db.query('SELECT brand_id, role_id FROM brand_members WHERE user_id=$1', [req.session!.user.id])).rows.map((r) => [r.brand_id, r.role_id])),67      passkeysHere: (await db.one('SELECT count(*)::int AS n FROM passkeys WHERE user_id=$1 AND rp_id=$2', [req.session!.user.id, new URL(req.origin).hostname]))!.n };68  });69  route({ method: 'GET', path: '/v1/users', summary: 'Utilisateurs', tag: 'admin', auth: 'user', role: 'admin' }, async () => ({ users: (await db.query('SELECT u.id, u.handle, u.display_name, u.role_id AS role, u.status, u.created_at, (SELECT count(*)::int FROM passkeys p WHERE p.user_id=u.id) AS passkeys FROM users u ORDER BY u.created_at')).rows }));70  route({ method: 'POST', path: '/v1/users', summary: 'Crée un utilisateur et son lien d’activation', tag: 'admin', auth: 'user', role: 'owner', body: z.object({ handle: z.string().regex(/^[a-z0-9._-]{2,40}$/), displayName: z.string().min(1).max(80), role: z.enum(['owner', 'admin', 'approver', 'editor', 'viewer']) }).strict() }, async (req) => {71    const u = await db.tx(async (tx) => { const r = (await tx.query('INSERT INTO users(handle, display_name, role_id) VALUES ($1,$2,$3) RETURNING id', [req.data.handle, req.data.displayName, req.data.role])).rows[0]; await audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'user.create', targetKind: 'user', targetId: r.id, result: 'ok', detail: { role: req.data.role } }); return r; });72    return { id: u.id, setupLink: await createSetupLink(db, cfg, u.id, cfg.socialOrigin) };73  });74  route({ method: 'POST', path: '/v1/users/:id/setup-link', summary: 'Nouveau lien d’activation (30 min)', tag: 'admin', auth: 'user', role: 'owner', body: z.object({ target: z.enum(['social', 'navigator']).default('social') }).strict() }, async (req) => ({ setupLink: await createSetupLink(db, cfg, (req.params as any).id, req.data.target === 'social' ? cfg.socialOrigin : cfg.navigatorOrigin) }));75  route({ method: 'POST', path: '/v1/users/:id/disable', summary: 'Désactive un utilisateur et ferme ses sessions', tag: 'admin', auth: 'user', role: 'owner', body: z.object({}).strict() }, async (req) => {76    const id = (req.params as any).id; if (id === req.session!.user.id) throw bad('cannot_disable_self');77    await db.tx(async (tx) => { await tx.query("UPDATE users SET status='disabled' WHERE id=$1", [id]); await tx.query('DELETE FROM auth_sessions WHERE user_id=$1', [id]); await audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'user.disable', targetKind: 'user', targetId: id, result: 'ok' }); });78  });79}80
Files main
Menu

Theme