Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : tests/helpers.ts9 * Module : tests10 * 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 { randomBytes, randomUUID } from 'node:crypto';43import { mkdtempSync, rmSync } from 'node:fs';44import { tmpdir } from 'node:os';45import { join } from 'node:path';46import { fileURLToPath } from 'node:url';47import pg from 'pg';48import type { FastifyInstance } from 'fastify';49import { loadConfig, type Config } from '../services/control-api/src/config.ts';50import { Db, migrate } from '../services/control-api/src/db.ts';51import { buildApp, type Ctx } from '../services/control-api/src/app.ts';52import { seed } from '../services/control-api/src/seed.ts';53import { h } from '../services/control-api/src/auth.ts';5455export const ROOT = fileURLToPath(new URL('..', import.meta.url));56export type TestUser = { id: string; cookie: string; csrf: string; role: string };57export type Env = { db: Db; cfg: Config; app: FastifyInstance; ctx: Ctx; notified: any[]; dbName: string; dir: string; close: () => Promise<void>;58 user: (role: string, handle?: string) => Promise<TestUser>;59 call: (u: TestUser | null, method: string, url: string, body?: unknown, opts?: { headers?: Record<string, string>; host?: string; remote?: string }) => Promise<{ status: number; json: any; headers: Record<string, any>; raw: Buffer }> };60const ADMIN_URL = process.env.MLS_TEST_ADMIN_URL ?? 'postgres://127.0.0.1/postgres';6162export async function makeEnv(over: Record<string, string> = {}): Promise<Env> {63 const dbName = `mls_test_${randomBytes(5).toString('hex')}`; const dir = mkdtempSync(join(tmpdir(), 'mls-test-'));64 const admin = new pg.Client({ connectionString: ADMIN_URL }); await admin.connect(); await admin.query(`CREATE DATABASE ${dbName}`); await admin.end();65 const cfg = loadConfig({ DATABASE_URL: ADMIN_URL.replace(/\/[^/]*$/, `/${dbName}`), MLS_DATA_DIR: join(dir, 'data'), MLS_CONFIG_DIR: join(dir, 'cfg'), MLS_SOCIAL_ORIGIN: 'http://social.test', MLS_NAVIGATOR_ORIGIN: 'http://navigator.test', MLS_FIXTURE_ORIGIN: 'http://127.0.0.1:8883', MLS_ENV: 'test', MLS_ANTHROPIC_KEY_FILE: join(dir, 'none.key'), MLS_MLX_KEY_FILE: join(dir, 'none2.key'), ...over });66 const db = new Db(cfg.databaseUrl, 6);67 await migrate(db, join(ROOT, 'database/migrations')); await seed(db, cfg);68 const notified: any[] = [];69 const { app, ctx } = await buildApp(db, cfg, { notifyGateway: (e) => notified.push(e) }); await app.ready();70 const env: Env = { db, cfg, app, ctx, notified, dbName, dir,71 async user(role, handle) { const id = randomUUID(); const cookie = randomBytes(24).toString('base64url'); const csrf = randomBytes(12).toString('base64url');72 await db.query('INSERT INTO users(id, handle, display_name, role_id) VALUES ($1,$2,$3,$4)', [id, handle ?? `${role}-${id.slice(0, 6)}`, `Test ${role}`, role]);73 for (const host of cfg.origins.map((o) => new URL(o).host)) await db.query("INSERT INTO auth_sessions(token_hash, user_id, host, csrf, expires_at) VALUES ($1,$2,$3,$4,now()+interval '1 hour')", [h(cookie + host), id, host, csrf]);74 return { id, cookie, csrf, role }; },75 async call(u, method, url, body, opts = {}) { const host = opts.host ?? new URL(cfg.socialOrigin).host;76 const headers: Record<string, string> = { host, ...(u ? { cookie: `mls=${u.cookie}${host}`, 'x-csrf': u.csrf } : {}), ...(body !== undefined && !Buffer.isBuffer(body) ? { 'content-type': 'application/json' } : {}), ...(opts.headers ?? {}) };77 for (const k of Object.keys(headers)) if (headers[k] === '') delete headers[k];78 const r = await app.inject({ method: method as any, url, headers, payload: body === undefined ? undefined : Buffer.isBuffer(body) ? body : JSON.stringify(body), remoteAddress: opts.remote ?? '127.0.0.1' });79 let json: any = null; try { json = r.json(); } catch { /* not json */ }80 return { status: r.statusCode, json, headers: r.headers as any, raw: r.rawPayload }; },81 async close() { await app.close(); await db.end(); const a = new pg.Client({ connectionString: ADMIN_URL }); await a.connect(); await a.query(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`); await a.end(); rmSync(dir, { recursive: true, force: true }); } };82 return env;83}84export const brandId = async (env: Env, slug: string) => (await env.db.one('SELECT id FROM brands WHERE slug=$1', [slug]))!.id as string;85/** A confirmed fixture page for a brand. */86export async function fixturePage(env: Env, admin: TestUser, slug: string, ext = 'page-1001', name = 'Atelier Démo') {87 const b = await brandId(env, slug);88 const p = await env.call(admin, 'POST', '/v1/pages', { brandId: b, platform: 'fixture', displayName: name, url: `${env.cfg.fixtureOrigin}/pages/${ext}`, composerUrl: `${env.cfg.fixtureOrigin}/pages/${ext}/composer`, externalPageId: ext });89 if (p.status !== 200) throw new Error(`page: ${JSON.stringify(p.json)}`);90 const c = await env.call(admin, 'POST', `/v1/pages/${p.json.id}/confirm`, { typedName: name, attest: true }); if (c.status !== 200) throw new Error('confirm');91 return { brandId: b, pageId: p.json.id as string };92}93/** Draft → review → approved by a different user. Returns ids and the approved hash. */94export async function approvedContent(env: Env, editor: TestUser, approver: TestUser, brand: string, pageId: string, body = 'Nouvelle version disponible aujourd’hui.') {95 const c = await env.call(editor, 'POST', '/v1/content', { brandId: brand, pageId, title: 'Annonce', payload: { lang: 'fr', body } }); if (c.status !== 200) throw new Error(`content: ${JSON.stringify(c.json)}`);96 await env.call(editor, 'POST', `/v1/content/${c.json.id}/submit`, {});97 const a = await env.call(approver, 'POST', `/v1/content/${c.json.id}/approve`, { versionId: c.json.version.id, contentHash: c.json.version.content_hash, pageId, decision: 'approve' });98 if (a.status !== 200) throw new Error(`approve: ${JSON.stringify(a.json)}`);99 return { contentId: c.json.id as string, versionId: c.json.version.id as string, hash: c.json.version.content_hash as string };100}101export const inMinutes = (n: number) => new Date(Date.now() + n * 60_000).toISOString();102/** Registers a worker + READY confirmed session scoped to the given pages, without a browser. */103export async function readySession(env: Env, owner: TestUser, pageIds: string[], name = 'w1') {104 const w = await env.call(owner, 'POST', '/v1/workers', { name }); const token = w.json.token as string;105 const s = await env.call(owner, 'POST', '/v1/navigator/sessions', { label: 'S', workerId: w.json.id });106 const hb = (sessions: any[] = []) => env.call(null, 'POST', '/v1/workers/heartbeat', { sessions, info: { version: 't', headed: false } }, { headers: { authorization: `Bearer ${token}` } });107 await env.call(owner, 'POST', `/v1/navigator/sessions/${s.json.id}/takeover`, {}, { host: 'navigator.test' });108 await env.call(owner, 'POST', `/v1/navigator/sessions/${s.json.id}/confirm`, { pageIds, attest: true }, { host: 'navigator.test' });109 await env.call(owner, 'POST', `/v1/navigator/sessions/${s.json.id}/release`, {}, { host: 'navigator.test' });110 const w2 = (path: string, body: unknown = {}) => env.call(null, 'POST', path, body, { headers: { authorization: `Bearer ${token}` } });111 return { workerId: w.json.id as string, token, sessionId: s.json.id as string, hb, worker: w2 };112}113