From e9164b323cd8d7cbcd0c2f8243c50cb992deae06 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Thu, 22 Oct 2026 13:40:25 +0200 Subject: [PATCH] =?UTF-8?q?feat(auth):=20connexion=20Google=20et=20Apple,?= =?UTF-8?q?=20sessions=20li=C3=A9es=20aux=20comptes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Google (PKCE) et Apple (response_mode=form_post, secret client JWT ES256 signé avec node:crypto), sans nouvelle dépendance ; - id_token vérifié pour les deux : signature RS256 via les JWKS, émetteur, audience, expiration, nonce, email vérifié ; - state à usage unique lié au navigateur par un cookie SameSite=None limité à /auth (le retour d'Apple est un POST cross-site) ; - sessions liées à users.id ; un compte suspendu ne peut ni se connecter ni utiliser une session existante ; - ALLOWED_EMAILS supprimée, ADMIN_EMAILS désigne les admins, variables APPLE_* toutes ou aucune. --- src/auth.js | 283 ++++++++++++++++++++++++-------- src/config.js | 19 ++- src/http.js | 4 +- test/auth.test.js | 360 +++++++++++++++++++++++++++++++++++++++++ test/core.test.js | 23 ++- test/helpers/oidc.js | 29 ++++ test/helpers/server.js | 50 ++++++ 7 files changed, 693 insertions(+), 75 deletions(-) create mode 100644 test/auth.test.js create mode 100644 test/helpers/oidc.js create mode 100644 test/helpers/server.js diff --git a/src/auth.js b/src/auth.js index 13f2c10..5cea3b6 100644 --- a/src/auth.js +++ b/src/auth.js @@ -1,26 +1,64 @@ -// Auth Google (OIDC, code flow + PKCE) avec whitelist d'emails. Sessions en base. -import { createHash } from 'node:crypto'; +// Connexion Google et Apple (OIDC, code flow), sessions en base liées à users.id. +// Pas de mot de passe : l'inscription est automatique à la première connexion réussie. +import { createHash, createPrivateKey, createPublicKey, sign, verify, timingSafeEqual } from 'node:crypto'; import { now } from './db.js'; import { randomId } from './crypto.js'; import { parseCookies, setCookie, redirect, HttpError } from './http.js'; +import { loginIdentity } from './users.js'; const SESSION_COOKIE = 'sid'; +const BIND_COOKIE = 'oauth_b'; const SESSION_TTL = 30 * 24 * 3600; const STATE_TTL = 600; -const GOOGLE_AUTH = 'https://accounts.google.com/o/oauth2/v2/auth'; -const GOOGLE_TOKEN = 'https://oauth2.googleapis.com/token'; +const JWKS_TTL = 3600; +const APPLE_AUD = 'https://appleid.apple.com'; +export const PROVIDERS = { + google: { + label: 'Google', + authUrl: 'https://accounts.google.com/o/oauth2/v2/auth', + tokenUrl: 'https://oauth2.googleapis.com/token', + jwksUrl: 'https://www.googleapis.com/oauth2/v3/certs', + issuers: ['https://accounts.google.com', 'accounts.google.com'], + scope: 'openid email profile', + extra: { prompt: 'select_account' }, + pkce: true, + }, + apple: { + label: 'Apple', + authUrl: 'https://appleid.apple.com/auth/authorize', + tokenUrl: 'https://appleid.apple.com/auth/token', + jwksUrl: 'https://appleid.apple.com/auth/keys', + issuers: [APPLE_AUD], + scope: 'name email', + extra: { response_mode: 'form_post' }, // obligatoire dès que le scope demande le nom ou l'email + pkce: false, + }, +}; + +// ---------- Sessions ---------- + +/** Session valide d'un compte actif. Un compte suspendu n'a plus de session utilisable (elles sont supprimées). */ export async function getSession(db, req) { const sid = parseCookies(req)[SESSION_COOKIE]; if (!sid) return null; - const s = await db.prepare('SELECT * FROM sessions WHERE id = ? AND expires_at > ?').get(sid, now()); - return s || null; + const s = await db.prepare(`SELECT s.id, s.user_id, u.email, u.name, u.provider, u.status, u.is_admin + FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.id = ? AND s.expires_at > ?`).get(sid, now()); + if (!s) return null; + if (s.status !== 'active') { + await db.prepare('DELETE FROM sessions WHERE user_id = ?').run(s.user_id); + return null; + } + return { + id: s.id, userId: Number(s.user_id), email: s.email, + user: { id: Number(s.user_id), email: s.email, name: s.name, provider: s.provider, status: s.status, isAdmin: !!s.is_admin }, + }; } -export async function createSession(db, res, email) { +export async function createSession(db, res, userId) { const id = randomId(); - await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)') - .run(id, email, now(), now() + SESSION_TTL); + await db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)') + .run(id, userId, now(), now() + SESSION_TTL); setCookie(res, SESSION_COOKIE, id, { maxAge: SESSION_TTL }); } @@ -30,77 +68,194 @@ export async function destroySession(db, req, res) { setCookie(res, SESSION_COOKIE, '', { maxAge: 0 }); } +/** Suspension : toutes les sessions du compte tombent tout de suite. */ +export async function destroyUserSessions(db, userId) { + await db.prepare('DELETE FROM sessions WHERE user_id = ?').run(userId); +} + export async function purgeExpired(db) { await db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now()); await db.prepare('DELETE FROM oauth_states WHERE created_at < ?').run(now() - STATE_TTL); } -export async function startGoogleLogin(db, cfg, res) { - const state = randomId(24); - const nonce = randomId(24); - const verifier = randomId(48); - const challenge = createHash('sha256').update(verifier).digest('base64url'); - await db.prepare('INSERT INTO oauth_states(state, verifier, nonce, created_at) VALUES(?, ?, ?, ?)') - .run(state, verifier, nonce, now()); - const q = new URLSearchParams({ - client_id: cfg.google.clientId, - redirect_uri: `${cfg.appUrl}/auth/google/callback`, - response_type: 'code', - scope: 'openid email', - state, nonce, - code_challenge: challenge, - code_challenge_method: 'S256', - prompt: 'select_account', - }); - redirect(res, `${GOOGLE_AUTH}?${q}`); -} +// ---------- JWT ---------- -// Vérifie les claims de l'id_token. Il est reçu directement de Google en TLS (code flow), -// la validation TLS remplace la vérification de signature (OIDC Core §3.1.3.7). -export function checkIdTokenClaims(claims, { clientId, nonce, allowedEmails, at = now() }) { - if (!['https://accounts.google.com', 'accounts.google.com'].includes(claims.iss)) throw new HttpError(401, 'Émetteur invalide'); - if (claims.aud !== clientId) throw new HttpError(401, 'Audience invalide'); - if (!claims.exp || claims.exp < at) throw new HttpError(401, 'Token expiré'); - if (claims.nonce !== nonce) throw new HttpError(401, 'Nonce invalide'); - if (!claims.email_verified) throw new HttpError(403, 'Email Google non vérifié'); - const email = String(claims.email || '').toLowerCase(); - if (!allowedEmails.includes(email)) throw new HttpError(403, 'Compte non autorisé'); - return email; -} +const b64json = (part) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8')); +const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url'); export function decodeJwtPayload(jwt) { const part = String(jwt).split('.')[1]; if (!part) throw new HttpError(401, 'id_token invalide'); - return JSON.parse(Buffer.from(part, 'base64url').toString('utf8')); + try { return b64json(part); } catch { throw new HttpError(401, 'id_token invalide'); } } -export async function finishGoogleLogin(db, cfg, url, res) { - const code = url.searchParams.get('code'); - const state = url.searchParams.get('state'); +/** + * Secret client Apple : un JWT signé en ES256 avec la clé privée du compte développeur + * (APPLE_KEY_ID / APPLE_TEAM_ID / APPLE_CLIENT_ID). Signature brute r||s (ieee-p1363), comme l'exige JWS. + */ +export function appleClientSecret(apple, { at = now(), ttl = 300 } = {}) { + const head = b64({ alg: 'ES256', kid: apple.keyId, typ: 'JWT' }); + const body = b64({ iss: apple.teamId, iat: at, exp: at + ttl, aud: APPLE_AUD, sub: apple.clientId }); + const sig = sign('sha256', Buffer.from(`${head}.${body}`), { key: createPrivateKey(apple.privateKey), dsaEncoding: 'ieee-p1363' }); + return `${head}.${body}.${sig.toString('base64url')}`; +} + +const fetcher = (app) => app.fetch || fetch; + +async function loadJwks(app, url) { + const r = await fetcher(app)(url, { signal: AbortSignal.timeout(10_000) }); + if (!r.ok) throw new HttpError(502, `Clés publiques indisponibles (${r.status})`); + const keys = (await r.json()).keys; + if (!Array.isArray(keys)) throw new HttpError(502, 'Clés publiques invalides'); + return keys; +} + +// Clés du fournisseur en cache ; une clé inconnue (rotation) déclenche une seule relecture, pas plus d'une par minute +async function findJwk(app, url, kid) { + const cache = (app.jwksCache ??= new Map()); + let entry = cache.get(url); + const find = (e) => e?.keys.find((k) => k.kid === kid && k.kty === 'RSA'); + if (!entry || now() - entry.at > JWKS_TTL) { + entry = { keys: await loadJwks(app, url), at: now() }; + cache.set(url, entry); + } else if (!find(entry) && now() - entry.at > 60) { + entry = { keys: await loadJwks(app, url), at: now() }; + cache.set(url, entry); + } + return find(entry); +} + +/** Vérifie la signature RS256 d'un id_token avec les JWKS du fournisseur, et renvoie ses claims (pas encore validés). */ +export async function verifyIdTokenSignature(app, jwt, jwksUrl) { + const parts = String(jwt || '').split('.'); + if (parts.length !== 3) throw new HttpError(401, 'id_token invalide'); + let header; + try { header = b64json(parts[0]); } catch { throw new HttpError(401, 'id_token invalide'); } + if (header.alg !== 'RS256') throw new HttpError(401, 'Algorithme de signature refusé'); + const jwk = await findJwk(app, jwksUrl, header.kid); + if (!jwk) throw new HttpError(401, 'Clé de signature inconnue'); + let ok = false; + try { + ok = verify('RSA-SHA256', Buffer.from(`${parts[0]}.${parts[1]}`), createPublicKey({ key: jwk, format: 'jwk' }), Buffer.from(parts[2], 'base64url')); + } catch { ok = false; } + if (!ok) throw new HttpError(401, 'Signature de l\'id_token invalide'); + return decodeJwtPayload(jwt); +} + +/** + * Valide les claims d'un id_token déjà authentifié (signature vérifiée) : émetteur, audience, expiration, + * nonce, identifiant (sub) et email vérifié. Renvoie l'identité à inscrire / connecter. + */ +export function checkIdTokenClaims(claims, { issuers, clientId, nonce, at = now() }) { + if (!issuers.includes(claims.iss)) throw new HttpError(401, 'Émetteur invalide'); + const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud]; + if (!aud.includes(clientId)) throw new HttpError(401, 'Audience invalide'); + if (!claims.exp || claims.exp < at) throw new HttpError(401, 'Token expiré'); + if (!claims.nonce || claims.nonce !== nonce) throw new HttpError(401, 'Nonce invalide'); + if (!claims.sub) throw new HttpError(401, 'Identifiant fournisseur manquant'); + // Apple renvoie parfois "true" en chaîne + if (claims.email_verified !== true && claims.email_verified !== 'true') throw new HttpError(403, 'Email non vérifié par le fournisseur'); + const email = String(claims.email || '').trim().toLowerCase(); + if (!email) throw new HttpError(401, 'Email manquant'); + return { sub: String(claims.sub), email, name: claims.name || null }; +} + +// ---------- Flux OAuth ---------- + +const hashBind = (v) => createHash('sha256').update(String(v)).digest('hex'); + +function providerOf(cfg, name) { + const p = PROVIDERS[name]; + if (!p || (name === 'apple' && !cfg.apple)) throw new HttpError(404, 'Fournisseur de connexion indisponible'); + return p; +} + +const clientIdOf = (cfg, name) => (name === 'apple' ? cfg.apple.clientId : cfg.google.clientId); +const redirectUri = (cfg, name) => `${cfg.appUrl}/auth/${name}/callback`; + +/** + * Démarre la connexion : state + nonce (+ PKCE pour Google) en base, et un cookie qui lie le flux à CE navigateur. + * Le retour d'Apple est un POST cross-site (form_post) : ni le cookie de session ni un cookie SameSite=Lax ne + * suivent. Le cookie de liaison est donc SameSite=None, Secure, HttpOnly, limité à /auth et à 10 minutes. + */ +export async function startLogin(app, name, res) { + const { db, cfg } = app; + const p = providerOf(cfg, name); + const state = randomId(24); + const nonce = randomId(24); + const verifier = randomId(48); + const bind = randomId(24); + await db.prepare('INSERT INTO oauth_states(state, provider, verifier, nonce, binding, created_at) VALUES(?, ?, ?, ?, ?, ?)') + .run(state, name, verifier, nonce, hashBind(bind), now()); + setCookie(res, BIND_COOKIE, bind, { maxAge: STATE_TTL, sameSite: 'None', path: '/auth' }); + const q = new URLSearchParams({ + client_id: clientIdOf(cfg, name), + redirect_uri: redirectUri(cfg, name), + response_type: 'code', + scope: p.scope, + state, nonce, + ...p.extra, + }); + if (p.pkce) { + q.set('code_challenge', createHash('sha256').update(verifier).digest('base64url')); + q.set('code_challenge_method', 'S256'); + } + redirect(res, `${p.authUrl}?${q}`); +} + +// Apple n'envoie le nom que lors de la toute première autorisation, dans le champ `user` du formulaire +function appleName(raw) { + try { + const n = JSON.parse(raw)?.name; + return [n?.firstName, n?.lastName].filter((x) => typeof x === 'string').join(' ').trim() || null; + } catch { return null; } +} + +/** + * Termine la connexion. `params` = paramètres de retour (query pour Google, corps du POST pour Apple). + * Contrôles : state connu, à usage unique, non expiré, du bon fournisseur et lié au navigateur (cookie) ; + * signature RS256 de l'id_token vérifiée avec les JWKS du fournisseur ; iss / aud / exp / nonce validés. + */ +export async function finishLogin(app, name, params, req, res) { + const { db, cfg } = app; + const p = providerOf(cfg, name); + const get = (k) => (typeof params.get === 'function' ? params.get(k) : params[k]); + const state = get('state'); + const row = state + ? await db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(String(state), now() - STATE_TTL) + : null; + if (state) await db.prepare('DELETE FROM oauth_states WHERE state = ?').run(String(state)); // usage unique + setCookie(res, BIND_COOKIE, '', { maxAge: 0, sameSite: 'None', path: '/auth' }); + + if (get('error')) throw new HttpError(401, get('error') === 'user_cancelled_authorize' ? 'Connexion annulée' : `Connexion refusée (${String(get('error')).slice(0, 60)})`); + const code = get('code'); if (!code || !state) throw new HttpError(400, 'Paramètres OAuth manquants'); + if (!row || row.provider !== name) throw new HttpError(400, 'State OAuth invalide ou expiré'); + const bind = parseCookies(req)[BIND_COOKIE]; + const a = Buffer.from(hashBind(bind || '')); + const b = Buffer.from(String(row.binding)); + if (!bind || a.length !== b.length || !timingSafeEqual(a, b)) throw new HttpError(400, 'Connexion démarrée depuis un autre navigateur'); - const row = await db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(state, now() - STATE_TTL); - await db.prepare('DELETE FROM oauth_states WHERE state = ?').run(state); - if (!row) throw new HttpError(400, 'State OAuth invalide ou expiré'); - - const r = await fetch(GOOGLE_TOKEN, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - code, - client_id: cfg.google.clientId, - client_secret: cfg.google.clientSecret, - redirect_uri: `${cfg.appUrl}/auth/google/callback`, - grant_type: 'authorization_code', - code_verifier: row.verifier, - }), + const body = new URLSearchParams({ + code: String(code), + client_id: clientIdOf(cfg, name), + client_secret: name === 'apple' ? appleClientSecret(cfg.apple) : cfg.google.clientSecret, + redirect_uri: redirectUri(cfg, name), + grant_type: 'authorization_code', }); - if (!r.ok) throw new HttpError(401, `Échange du code Google refusé (${r.status})`); + if (p.pkce) body.set('code_verifier', row.verifier); + const r = await fetcher(app)(p.tokenUrl, { + method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, signal: AbortSignal.timeout(10_000), + }); + if (!r.ok) throw new HttpError(401, `Échange du code ${p.label} refusé (${r.status})`); const tokens = await r.json(); - const email = checkIdTokenClaims(decodeJwtPayload(tokens.id_token), { - clientId: cfg.google.clientId, nonce: row.nonce, allowedEmails: cfg.allowedEmails, - }); - await createSession(db, res, email); + + const claims = await verifyIdTokenSignature(app, tokens.id_token, p.jwksUrl); + const id = checkIdTokenClaims(claims, { issuers: p.issuers, clientId: clientIdOf(cfg, name), nonce: row.nonce }); + if (name === 'apple') id.name = appleName(get('user')) || id.name; + + const user = await loginIdentity(db, cfg, { provider: name, sub: id.sub, email: id.email, name: id.name }); + await createSession(db, res, user.id); redirect(res, '/'); } diff --git a/src/config.js b/src/config.js index 327e4d0..f9025bd 100644 --- a/src/config.js +++ b/src/config.js @@ -9,6 +9,21 @@ function required(name) { return v; } +// Connexion Apple : les quatre variables ensemble, ou aucune (le bouton Apple est alors masqué) +function appleConfig() { + const keys = ['APPLE_TEAM_ID', 'APPLE_KEY_ID', 'APPLE_CLIENT_ID', 'APPLE_PRIVATE_KEY']; + const set = keys.filter((k) => env[k]); + if (!set.length) return null; + if (set.length < keys.length) { + throw new Error(`Connexion Apple : variables incomplètes (manque ${keys.filter((k) => !env[k]).join(', ')})`); + } + return { + teamId: env.APPLE_TEAM_ID, keyId: env.APPLE_KEY_ID, clientId: env.APPLE_CLIENT_ID, + // Le PEM tient sur une ligne dans un .env : les séquences \n littérales redeviennent des retours à la ligne + privateKey: env.APPLE_PRIVATE_KEY.replace(/\\n/g, '\n'), + }; +} + export function loadConfig() { const secretKey = required('SECRET_KEY'); if (!/^[0-9a-f]{64}$/i.test(secretKey)) { @@ -22,7 +37,9 @@ export function loadConfig() { clientId: required('GOOGLE_CLIENT_ID'), clientSecret: required('GOOGLE_CLIENT_SECRET'), }, - allowedEmails: required('ALLOWED_EMAILS').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean), + apple: appleConfig(), + // Administrateurs : ces adresses seulement (la première est aussi propriétaire des données migrées) + adminEmails: (env.ADMIN_EMAILS || '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean), secretKey: Buffer.from(secretKey, 'hex'), db: dbConfigFromEnv(env), dataDir: resolve(env.DATA_DIR || './data'), diff --git a/src/http.js b/src/http.js index 0ef74f5..38048f7 100644 --- a/src/http.js +++ b/src/http.js @@ -32,8 +32,8 @@ export function parseCookies(req) { return out; } -export function setCookie(res, name, value, { maxAge, httpOnly = true } = {}) { - const parts = [`${name}=${encodeURIComponent(value)}`, 'Path=/', 'SameSite=Lax', 'Secure']; +export function setCookie(res, name, value, { maxAge, httpOnly = true, sameSite = 'Lax', path = '/' } = {}) { + const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`, 'Secure']; if (httpOnly) parts.push('HttpOnly'); if (maxAge !== undefined) parts.push(`Max-Age=${maxAge}`); const prev = res.getHeader('Set-Cookie'); diff --git a/test/auth.test.js b/test/auth.test.js new file mode 100644 index 0000000..90e82f5 --- /dev/null +++ b/test/auth.test.js @@ -0,0 +1,360 @@ +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { createPublicKey, verify } from 'node:crypto'; +import { now } from '../src/db.js'; +import { loadConfig } from '../src/config.js'; +import { PROVIDERS, appleClientSecret } from '../src/auth.js'; +import { startApp, APP_URL } from './helpers/server.js'; +import { makeProvider } from './helpers/oidc.js'; +import { addUser } from './helpers/users.js'; + +// Flux Google et Apple avec des fournisseurs simulés : aucun appel réseau, tout passe par app.fetch. +const prov = makeProvider(); +const PEM_HEAD = '-----BEGIN ' + 'PRIVATE KEY-----', PEM_FOOT = '-----END ' + 'PRIVATE KEY-----'; // faux contenu de .p8 +let s, base, issue, calls; + +before(async () => { + s = await startApp({ cfg: { apple: prov.apple, adminEmails: ['admin@x.fr'] } }); + base = s.base; + s.app.fetch = async (url, opts = {}) => { + calls.push({ url, body: opts.body ? Object.fromEntries(new URLSearchParams(opts.body)) : null }); + if (url === PROVIDERS.google.jwksUrl || url === PROVIDERS.apple.jwksUrl) return { ok: true, status: 200, json: async () => ({ keys: [prov.jwk] }) }; + if (url === PROVIDERS.google.tokenUrl || url === PROVIDERS.apple.tokenUrl) { + return issue ? { ok: true, status: 200, json: async () => ({ id_token: issue(url) }) } : { ok: false, status: 400, json: async () => ({}) }; + } + return { ok: false, status: 404, json: async () => ({}) }; + }; +}); +after(() => s.close()); + +const GOOGLE_CLAIMS = (nonce, o = {}) => ({ + iss: 'https://accounts.google.com', aud: 'gid', sub: 'g-100', exp: now() + 600, iat: now(), + nonce, email: 'Ada@Example.com', email_verified: true, name: 'Ada L.', ...o, +}); +const APPLE_CLAIMS = (nonce, o = {}) => ({ + iss: 'https://appleid.apple.com', aud: prov.apple.clientId, sub: '001234.abcd.5678', exp: now() + 600, iat: now(), + nonce, email: 'bob@privaterelay.appleid.com', email_verified: 'true', ...o, +}); + +const cookieOf = (r, name) => r.headers.getSetCookie().find((c) => c.startsWith(`${name}=`)); + +/** Démarre une connexion : state, nonce et cookie de liaison du « navigateur ». */ +async function start(provider) { + calls = []; + const r = await fetch(`${base}/auth/${provider}`, { redirect: 'manual' }); + assert.equal(r.status, 303); + const loc = new URL(r.headers.get('location')); + const set = cookieOf(r, 'oauth_b'); + return { loc, set, state: loc.searchParams.get('state'), nonce: loc.searchParams.get('nonce'), bind: set?.split(';')[0] }; +} + +const google = ({ state, bind, code = 'code-1' }) => fetch(`${base}/auth/google/callback?${new URLSearchParams({ code, state })}`, + { redirect: 'manual', headers: bind ? { cookie: bind } : {} }); +// Retour d'Apple : POST cross-site (form_post), l'origine est celle d'Apple +const apple = ({ state, bind, code = 'code-1', user, error }) => fetch(`${base}/auth/apple/callback`, { + method: 'POST', redirect: 'manual', + headers: { 'content-type': 'application/x-www-form-urlencoded', origin: 'https://appleid.apple.com', ...(bind ? { cookie: bind } : {}) }, + body: new URLSearchParams({ ...(code ? { code } : {}), state, ...(user ? { user } : {}), ...(error ? { error } : {}) }).toString(), +}); + +const failure = (r) => decodeURIComponent(new URL(r.headers.get('location'), base).searchParams.get('e') || ''); +const sessions = async () => (await s.db.prepare('SELECT COUNT(*) n FROM sessions').get()).n; +const userByEmail = (email) => s.db.prepare('SELECT * FROM users WHERE email = ?').get(email); + +test('Google : inscription automatique à la première connexion, session, PKCE et secret client', async () => { + const st = await start('google'); + assert.equal(st.loc.host, 'accounts.google.com'); + assert.equal(st.loc.searchParams.get('code_challenge_method'), 'S256'); + assert.equal(st.loc.searchParams.get('scope'), 'openid email profile'); + assert.match(st.set, /SameSite=None/); + assert.match(st.set, /Secure/); + assert.match(st.set, /HttpOnly/); + assert.match(st.set, /Path=\/auth/); + + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce)); + const before = await sessions(); + const r = await google(st); + assert.equal(r.status, 303); + assert.equal(r.headers.get('location'), '/'); + const sid = cookieOf(r, 'sid'); + assert.ok(sid, 'cookie de session'); + assert.equal(await sessions(), before + 1); + + const exchange = calls.find((c) => c.url === PROVIDERS.google.tokenUrl).body; + assert.equal(exchange.client_secret, 'gsecret'); + assert.ok(exchange.code_verifier, 'PKCE'); + assert.equal(exchange.redirect_uri, `${APP_URL}/auth/google/callback`); + + const u = await userByEmail('ada@example.com'); + assert.equal(u.provider, 'google'); + assert.equal(u.provider_sub, 'g-100'); + assert.equal(u.name, 'Ada L.'); + assert.equal(u.status, 'active'); + assert.equal(u.is_admin, 0); + assert.equal(u.plan, 'free'); + assert.ok(u.last_login_at); + assert.equal(u.claude_link_json, null); + + const home = await s.client(sid.split(';')[0]).get('/'); + assert.equal(home.status, 200, 'la session ouvre le tableau de bord'); +}); + +test('Google : seconde connexion = même compte, pas de doublon', async () => { + const st = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { email: 'ada@example.com' })); + const r = await google(st); + assert.equal(r.headers.get('location'), '/'); + assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM users WHERE email = 'ada@example.com'").get()).n, 1); +}); + +test('Google : id_token invalide refusé (signature, alg, kid, émetteur, audience, expiration, nonce, email)', async () => { + const cases = { + 'signature forgée (clé du faussaire)': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { sub: 'evil' }), { key: prov.forgerKey }), /Signature/], + 'alg none': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { alg: 'none' }), /Algorithme/], + 'alg HS256 (confusion de clé)': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { alg: 'HS256' }), /Algorithme/], + 'kid inconnu': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { kid: 'autre' }), /Clé de signature/], + 'émetteur': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { iss: 'https://evil.example' })), /Émetteur/], + 'audience': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { aud: 'autre-client' })), /Audience/], + 'expiré': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { exp: now() - 10 })), /expiré/], + 'nonce': [() => prov.idToken(GOOGLE_CLAIMS('autre-nonce')), /Nonce/], + 'email non vérifié': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { email_verified: false })), /vérifié/], + 'sans sub': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { sub: undefined })), /Identifiant/], + 'jeton mal formé': [() => 'pas.un.jwt', /invalide/], + }; + const known = (await s.db.prepare('SELECT COUNT(*) n FROM users').get()).n; + for (const [name, [make, re]] of Object.entries(cases)) { + const st = await start('google'); + issue = () => make(st.nonce); + const sessionsBefore = await sessions(); + const r = await google(st); + assert.equal(r.status, 303, name); + assert.match(failure(r), re, name); + assert.equal(cookieOf(r, 'sid'), undefined, `${name} : aucune session`); + assert.equal(await sessions(), sessionsBefore, name); + } + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM users').get()).n, known, 'aucun compte créé par un jeton invalide'); + assert.equal(await userByEmail('evil@x.fr'), undefined); +}); + +test('state, nonce et liaison au navigateur : inconnus, rejoués, expirés ou d\'un autre navigateur → refusés', async () => { + issue = null; + // state inconnu + let r = await google({ state: 'forge', bind: 'oauth_b=x' }); + assert.match(failure(r), /State OAuth invalide/); + // paramètres manquants + r = await fetch(`${base}/auth/google/callback`, { redirect: 'manual' }); + assert.match(failure(r), /manquants/); + + // cookie absent (le flux n'a pas été démarré dans ce navigateur : login CSRF) + let st = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-csrf', email: 'csrf@x.fr' })); + r = await google({ state: st.state, bind: null }); + assert.match(failure(r), /autre navigateur/); + assert.equal(await userByEmail('csrf@x.fr'), undefined); + + // mauvais cookie + st = await start('google'); + r = await google({ state: st.state, bind: 'oauth_b=pas-le-bon' }); + assert.match(failure(r), /autre navigateur/); + + // state à usage unique + st = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce)); + assert.equal((await google(st)).headers.get('location'), '/'); + r = await google(st); + assert.match(failure(r), /State OAuth invalide/, 'rejeu refusé'); + + // state expiré + st = await start('google'); + await s.db.prepare('UPDATE oauth_states SET created_at = ? WHERE state = ?').run(now() - 3600, st.state); + r = await google(st); + assert.match(failure(r), /State OAuth invalide/); + + // state Google présenté sur le callback Apple + st = await start('google'); + r = await apple({ state: st.state, bind: st.bind }); + assert.match(failure(r), /State OAuth invalide/); + // le fournisseur refuse (code invalide) : échec propre, rien n'est créé + st = await start('google'); + issue = null; + r = await google(st); + assert.match(failure(r), /refusé/); +}); + +test('Apple : redirection form_post avec state + nonce, cookie de liaison SameSite=None', async () => { + const st = await start('apple'); + assert.equal(st.loc.origin + st.loc.pathname, PROVIDERS.apple.authUrl); + assert.equal(st.loc.searchParams.get('response_mode'), 'form_post'); + assert.equal(st.loc.searchParams.get('response_type'), 'code'); + assert.equal(st.loc.searchParams.get('scope'), 'name email'); + assert.equal(st.loc.searchParams.get('client_id'), prov.apple.clientId); + assert.equal(st.loc.searchParams.get('redirect_uri'), `${APP_URL}/auth/apple/callback`); + assert.ok(st.state && st.nonce); + assert.match(st.set, /SameSite=None/); + assert.match(st.set, /Secure/); +}); + +test('Apple : POST cross-site accepté (state + nonce + cookie), nom reçu à la première connexion, secret client ES256 valide', async () => { + const st = await start('apple'); + issue = () => prov.idToken(APPLE_CLAIMS(st.nonce)); + const r = await apple({ ...st, user: JSON.stringify({ name: { firstName: 'Bob', lastName: 'Martin' }, email: 'bob@privaterelay.appleid.com' }) }); + assert.equal(r.status, 303); + assert.equal(r.headers.get('location'), '/'); + assert.ok(cookieOf(r, 'sid')); + const u = await userByEmail('bob@privaterelay.appleid.com'); + assert.equal(u.provider, 'apple'); + assert.equal(u.provider_sub, '001234.abcd.5678'); + assert.equal(u.name, 'Bob Martin'); + + // Le secret client envoyé à Apple est un JWT ES256 signé avec la clé privée du compte développeur + const secret = calls.find((c) => c.url === PROVIDERS.apple.tokenUrl).body.client_secret; + const [h, p, sig] = secret.split('.'); + const head = JSON.parse(Buffer.from(h, 'base64url')); + const claims = JSON.parse(Buffer.from(p, 'base64url')); + assert.deepEqual({ alg: head.alg, kid: head.kid }, { alg: 'ES256', kid: prov.apple.keyId }); + assert.equal(claims.iss, prov.apple.teamId); + assert.equal(claims.sub, prov.apple.clientId); + assert.equal(claims.aud, 'https://appleid.apple.com'); + assert.ok(claims.exp > claims.iat && claims.exp - claims.iat <= 600); + assert.equal(Buffer.from(sig, 'base64url').length, 64, 'signature brute r||s'); + assert.ok(verify('sha256', Buffer.from(`${h}.${p}`), { key: prov.apple.publicKey, dsaEncoding: 'ieee-p1363' }, Buffer.from(sig, 'base64url'))); + assert.equal(calls.find((c) => c.url === PROVIDERS.apple.tokenUrl).body.client_id, prov.apple.clientId); +}); + +test('Apple : id_token forgé, mauvais nonce / audience / émetteur, POST sans cookie → refusés', async () => { + const cases = { + 'signature forgée': [(n) => prov.idToken(APPLE_CLAIMS(n, { sub: 'evil' }), { key: prov.forgerKey }), /Signature/], + 'nonce': [() => prov.idToken(APPLE_CLAIMS('autre')), /Nonce/], + 'audience': [(n) => prov.idToken(APPLE_CLAIMS(n, { aud: 'dev.autre.app' })), /Audience/], + 'émetteur': [(n) => prov.idToken(APPLE_CLAIMS(n, { iss: 'https://accounts.google.com' })), /Émetteur/], + 'expiré': [(n) => prov.idToken(APPLE_CLAIMS(n, { exp: now() - 1 })), /expiré/], + 'email non vérifié': [(n) => prov.idToken(APPLE_CLAIMS(n, { email_verified: 'false' })), /vérifié/], + }; + for (const [name, [make, re]] of Object.entries(cases)) { + const st = await start('apple'); + issue = () => make(st.nonce); + const r = await apple(st); + assert.match(failure(r), re, name); + assert.equal(cookieOf(r, 'sid'), undefined, name); + } + // Login CSRF : un POST d'un site tiers avec un state connu mais sans le cookie de ce navigateur + const st = await start('apple'); + issue = () => prov.idToken(APPLE_CLAIMS(st.nonce, { sub: 'attacker', email: 'attacker@x.fr' })); + const r = await apple({ state: st.state, bind: null }); + assert.match(failure(r), /autre navigateur/); + assert.equal(await userByEmail('attacker@x.fr'), undefined); + // refus de l'utilisateur côté Apple + const st2 = await start('apple'); + assert.match(failure(await apple({ state: st2.state, bind: st2.bind, code: null, error: 'user_cancelled_authorize' })), /annulée/); +}); + +test('page de connexion : bouton Apple seulement si Apple est configuré', async () => { + let r = await s.anon.get('/login'); + let page = await r.text(); + assert.match(page, /Se connecter avec Google/); + assert.match(page, /Se connecter avec Apple/); + + const bare = await startApp(); + try { + page = await (await bare.anon.get('/login')).text(); + assert.match(page, /Se connecter avec Google/); + assert.doesNotMatch(page, /Apple/); + assert.equal((await bare.anon.get('/auth/apple')).status, 404, 'route Apple inexistante sans configuration'); + assert.equal((await bare.anon.post('/auth/apple/callback', {}, { origin: null })).status, 303, 'le retour Apple échoue proprement'); + } finally { await bare.close(); } +}); + +test('configuration : variables Apple toutes présentes ou toutes absentes, ADMIN_EMAILS, plus de ALLOWED_EMAILS', () => { + const keep = { ...process.env }; + try { + Object.assign(process.env, { + SECRET_KEY: '00'.repeat(32), APP_URL: 'https://x.test/', GOOGLE_CLIENT_ID: 'a', GOOGLE_CLIENT_SECRET: 'b', + DB_HOST: 'h', DB_USER: 'u', DB_NAME: 'n', ADMIN_EMAILS: ' Tony@X.fr, b@x.fr ,', + }); + for (const k of ['APPLE_TEAM_ID', 'APPLE_KEY_ID', 'APPLE_CLIENT_ID', 'APPLE_PRIVATE_KEY', 'ALLOWED_EMAILS']) delete process.env[k]; + let cfg = loadConfig(); + assert.equal(cfg.apple, null); + assert.deepEqual(cfg.adminEmails, ['tony@x.fr', 'b@x.fr']); + assert.equal('allowedEmails' in cfg, false); + + Object.assign(process.env, { APPLE_TEAM_ID: 'T', APPLE_KEY_ID: 'K' }); + assert.throws(() => loadConfig(), /Apple.*APPLE_CLIENT_ID, APPLE_PRIVATE_KEY/); + + Object.assign(process.env, { APPLE_CLIENT_ID: 'C', APPLE_PRIVATE_KEY: `${PEM_HEAD}\\nABC\\n${PEM_FOOT}` }); + cfg = loadConfig(); + assert.deepEqual({ ...cfg.apple, privateKey: undefined }, { teamId: 'T', keyId: 'K', clientId: 'C', privateKey: undefined }); + assert.equal(cfg.apple.privateKey, `${PEM_HEAD}\nABC\n${PEM_FOOT}`,'les \\n littéraux du .env redeviennent des retours à la ligne'); + // la clé fournie par prov.apple se relit telle quelle + assert.ok(appleClientSecret(prov.apple).split('.').length === 3); + } finally { + for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; + Object.assign(process.env, keep); + } +}); + +test('ADMIN_EMAILS désigne les admins ; le compte préparé par la migration est retrouvé par son email', async () => { + // Compte propriétaire préparé (sans fournisseur) avec ses données + const prepared = await addUser(s.db, { email: 'admin@x.fr', provider: null, sub: null, admin: false }); + await s.db.prepare('UPDATE users SET provider = NULL, provider_sub = NULL WHERE id = ?').run(prepared); + await s.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(prepared, 'Existant', 'https://git.test/e.git', now()); + + const st = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-admin', email: 'ADMIN@x.fr' })); + assert.equal((await google(st)).headers.get('location'), '/'); + const u = await userByEmail('admin@x.fr'); + assert.equal(Number(u.id), prepared, 'même compte, pas de doublon'); + assert.equal(u.provider, 'google'); + assert.equal(u.provider_sub, 'g-admin'); + assert.equal(u.is_admin, 1); + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(prepared)).n, 1, 'ses données sont toujours là'); + + // un non-admin n'est pas promu, et ADMIN_EMAILS fait foi au démarrage + assert.equal((await userByEmail('ada@example.com')).is_admin, 0); +}); + +test('un email déjà lié à un autre fournisseur n\'est pas fusionné automatiquement', async () => { + const st = await start('apple'); + issue = () => prov.idToken(APPLE_CLAIMS(st.nonce, { sub: 'apple-ada', email: 'ada@example.com' })); + const r = await apple(st); + assert.match(failure(r), /déjà associé à un compte Google/); + assert.equal(cookieOf(r, 'sid'), undefined); + assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM users WHERE email = 'ada@example.com'").get()).n, 1); +}); + +test('compte suspendu : connexion refusée, session existante inutilisable et supprimée', async () => { + const u = await s.newUser({ email: 'susp@x.fr' }); + assert.equal((await u.get('/api/system')).status, 200); + await s.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(u.id); + + let r = await u.get('/api/system'); + assert.equal(r.status, 401, 'la session existante ne marche plus'); + r = await u.get('/'); + assert.equal(r.status, 303); + assert.equal(r.headers.get('location'), '/login'); + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(u.id)).n, 0, 'sessions supprimées'); + r = await u.post('/api/projects', { name: 'x', gitUrl: 'https://a/b/c.git' }); + assert.equal(r.status, 401); + + // et il ne peut pas se reconnecter + await s.db.prepare('UPDATE users SET provider = ?, provider_sub = ? WHERE id = ?').run('google', 'g-susp', u.id); + const st = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-susp', email: 'susp@x.fr' })); + const login = await google(st); + assert.match(failure(login), /suspendu/); + assert.equal(cookieOf(login, 'sid'), undefined); + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(u.id)).n, 0); + + // réactivé : tout refonctionne + await s.db.prepare("UPDATE users SET status = 'active' WHERE id = ?").run(u.id); + const st2 = await start('google'); + issue = () => prov.idToken(GOOGLE_CLAIMS(st2.nonce, { sub: 'g-susp', email: 'susp@x.fr' })); + assert.equal((await google(st2)).headers.get('location'), '/'); +}); + +test('déconnexion : la session est détruite côté serveur', async () => { + const u = await s.newUser(); + assert.equal((await u.get('/api/system')).status, 200); + const r = await u.post('/logout', {}, { form: true }); + assert.equal(r.status, 303); + assert.equal((await u.get('/api/system')).status, 401); +}); diff --git a/test/core.test.js b/test/core.test.js index 3fcbd75..85fe5c2 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -6,6 +6,7 @@ import { getSetting, setSetting, MIGRATIONS } from '../src/db.js'; import { testDb } from './helpers/db.js'; import { Router, esc } from '../src/http.js'; import { checkIdTokenClaims, checkOrigin } from '../src/auth.js'; +import { addUser } from './helpers/users.js'; const key = randomBytes(32); @@ -30,9 +31,10 @@ test('migrations et settings', async () => { const db = await testDb(); const v = await db.prepare('SELECT COUNT(*) n, MAX(version) v FROM schema_migrations').get(); assert.deepEqual({ n: v.n, v: v.v }, { n: MIGRATIONS.length, v: MIGRATIONS.length }); - await setSetting(db, 'a', '1'); await setSetting(db, 'a', '2'); - assert.equal(await getSetting(db, 'a'), '2'); - assert.equal(await getSetting(db, 'nope', 'x'), 'x'); + const u = await addUser(db); + await setSetting(db, u, 'a', '1'); await setSetting(db, u, 'a', '2'); + assert.equal(await getSetting(db, u, 'a'), '2'); + assert.equal(await getSetting(db, u, 'nope', 'x'), 'x'); }); test('router avec paramètres', () => { @@ -47,15 +49,20 @@ test('échappement HTML', () => { assert.equal(esc('\'&'), '<a href="x">'&'); }); -test('claims id_token Google', () => { - const base = { iss: 'https://accounts.google.com', aud: 'cid', exp: 2e9, nonce: 'n', email_verified: true, email: 'Me@Gmail.com' }; - const opts = { clientId: 'cid', nonce: 'n', allowedEmails: ['me@gmail.com'], at: 1e9 }; - assert.equal(checkIdTokenClaims(base, opts), 'me@gmail.com'); - assert.throws(() => checkIdTokenClaims({ ...base, email: 'pirate@gmail.com' }, opts), /non autorisé/); +test('claims id_token : émetteur, audience, expiration, nonce, email vérifié', () => { + const base = { iss: 'https://accounts.google.com', aud: 'cid', exp: 2e9, nonce: 'n', sub: '123', email_verified: true, email: 'Me@Gmail.com' }; + const opts = { issuers: ['https://accounts.google.com', 'accounts.google.com'], clientId: 'cid', nonce: 'n', at: 1e9 }; + assert.deepEqual(checkIdTokenClaims(base, opts), { sub: '123', email: 'me@gmail.com', name: null }); + assert.equal(checkIdTokenClaims({ ...base, aud: ['x', 'cid'] }, opts).sub, '123', 'audience en liste'); + assert.equal(checkIdTokenClaims({ ...base, email_verified: 'true' }, opts).sub, '123', 'Apple envoie "true" en chaîne'); + assert.throws(() => checkIdTokenClaims({ ...base, iss: 'https://evil.com' }, opts), /Émetteur/); assert.throws(() => checkIdTokenClaims({ ...base, aud: 'x' }, opts), /Audience/); assert.throws(() => checkIdTokenClaims({ ...base, nonce: 'z' }, opts), /Nonce/); + assert.throws(() => checkIdTokenClaims({ ...base, nonce: undefined }, { ...opts, nonce: undefined }), /Nonce/); assert.throws(() => checkIdTokenClaims({ ...base, email_verified: false }, opts), /vérifié/); assert.throws(() => checkIdTokenClaims({ ...base, exp: 1 }, opts), /expiré/); + assert.throws(() => checkIdTokenClaims({ ...base, sub: '' }, opts), /Identifiant/); + assert.throws(() => checkIdTokenClaims({ ...base, email: '' }, opts), /Email manquant/); }); test('contrôle d\'origine', () => { diff --git a/test/helpers/oidc.js b/test/helpers/oidc.js new file mode 100644 index 0000000..4a819ce --- /dev/null +++ b/test/helpers/oidc.js @@ -0,0 +1,29 @@ +// Faux fournisseur OIDC (Google / Apple) : clés RSA pour les id_token, clé EC pour le secret client Apple. +import { generateKeyPairSync, sign } from 'node:crypto'; + +const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url'); + +export function makeProvider() { + const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const other = generateKeyPairSync('rsa', { modulusLength: 2048 }); // clé d'un faussaire + const jwk = { ...rsa.publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'RS256', use: 'sig' }; + const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' }); + + /** id_token signé. `claims` complète/écrase les valeurs par défaut ; `opts` choisit clé, kid et algorithme. */ + function idToken(claims, { key = rsa.privateKey, kid = 'k1', alg = 'RS256' } = {}) { + const head = b64({ alg, kid, typ: 'JWT' }); + const body = b64(claims); + if (alg === 'none') return `${head}.${body}.`; + const sig = sign('RSA-SHA256', Buffer.from(`${head}.${body}`), key); + return `${head}.${body}.${sig.toString('base64url')}`; + } + + return { + jwk, idToken, forgerKey: other.privateKey, + apple: { + teamId: 'TEAM123456', keyId: 'KEY1234567', clientId: 'dev.tony.aitools.web', + privateKey: ec.privateKey.export({ type: 'pkcs8', format: 'pem' }), + publicKey: ec.publicKey, + }, + }; +} diff --git a/test/helpers/server.js b/test/helpers/server.js new file mode 100644 index 0000000..110b876 --- /dev/null +++ b/test/helpers/server.js @@ -0,0 +1,50 @@ +// Serveur HTTP de test : vraie application sur un port libre, base de test, comptes créés à la demande. +import { randomBytes } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { now } from '../../src/db.js'; +import { createApp } from '../../src/server.js'; +import { testDb } from './db.js'; +import { addUser } from './users.js'; + +export const APP_URL = 'https://ai.tony-averty.dev'; + +export async function startApp({ cfg = {}, worker = false } = {}) { + const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-')); + const config = { + appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [], + secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, ...cfg, + }; + const app = await createApp(config, { db: await testDb(), worker }); + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${app.server.address().port}`; + + /** Requêtes avec la session d'un cookie (ou sans). */ + const client = (cookie) => ({ + get: (p, opts = {}) => fetch(base + p, { redirect: 'manual', headers: { ...(cookie ? { cookie } : {}), accept: 'application/json', ...opts.headers } }), + post: (p, body = {}, { origin = APP_URL, form = false } = {}) => fetch(base + p, { + method: 'POST', redirect: 'manual', + headers: { + ...(cookie ? { cookie } : {}), ...(origin ? { origin } : {}), accept: 'application/json', + 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json', + }, + body: form ? new URLSearchParams(body).toString() : JSON.stringify(body), + }), + }); + + /** Crée un compte avec une session ouverte. */ + let n = 0; + const newUser = async (opts = {}) => { + n++; + const email = opts.email || `user${n}@test.fr`; + const id = await addUser(app.db, { ...opts, email }); + const sid = `sess-${id}-${n}`; + await app.db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run(sid, id, now(), now() + 3600); + const cookie = `sid=${sid}`; + return { id, email, cookie, ...client(cookie) }; + }; + + const close = async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); }; + return { app, db: app.db, base, tmp, client, newUser, close, anon: client(null) }; +}