SPB Git

Repository Public

backend-helper.mts 5.5 KB 66 lines typescript

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Scripts/backend-helper.mts3// Description: Test-only helper for the local SP Drive backend: a software WebAuthn authenticator with a persisted4// ES256 key registers the test account, opens device sessions and approves device-link codes over the real HTTP API.5// The server-side verification is the production code path. Never used against production.6import { createHash, createPrivateKey, createSign, generateKeyPairSync, randomBytes } from 'node:crypto';7import { existsSync, readFileSync, writeFileSync } from 'node:fs';89const BASE = process.env.SPDRIVE_BASE!, ORIGIN = process.env.SPD_ORIGIN!, RP = process.env.SPD_RP_ID!, STATE = process.env.SPDRIVE_STATE!;10const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url');11function cbor(v: unknown): Buffer {12  const head = (major: number, n: number) => n < 24 ? Buffer.from([(major << 5) | n]) : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 255]);13  if (typeof v === 'number') return v >= 0 ? head(0, v) : head(1, -1 - v);14  if (Buffer.isBuffer(v)) return Buffer.concat([head(2, v.length), v]);15  if (typeof v === 'string') { const b = Buffer.from(v); return Buffer.concat([head(3, b.length), b]); }16  if (v instanceof Map) return Buffer.concat([head(5, v.size), ...[...v].flatMap(([k, x]) => [cbor(k), cbor(x)])]);17  throw new Error('cbor: unsupported');18}19interface Cred { id: string; jwk: any; userHandle: string; counter: number }20const file = (email: string) => `${STATE}/passkey-${email.replace(/[^a-z0-9]/gi, '_')}.json`;21const load = (email: string): Cred => JSON.parse(readFileSync(file(email), 'utf8'));22const save = (email: string, c: Cred) => writeFileSync(file(email), JSON.stringify(c), { mode: 0o600 });23const authData = (flags: number, counter: number, attested?: Buffer) => { const c = Buffer.alloc(4); c.writeUInt32BE(counter); return Buffer.concat([createHash('sha256').update(RP).digest(), Buffer.from([flags]), c, ...(attested ? [attested] : [])]); };2425function assertion(email: string, challenge: string) {26  const c = load(email); c.counter++; save(email, c);27  const ad = authData(0x05, c.counter);28  const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));29  const signature = createSign('sha256').update(Buffer.concat([ad, createHash('sha256').update(clientDataJSON).digest()])).sign(createPrivateKey({ key: c.jwk, format: 'jwk' }));30  return { id: c.id, rawId: c.id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',31    response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(ad), signature: b64u(signature), userHandle: c.userHandle } };32}33let cookie = '';34async function call(method: string, path: string, body?: unknown, auth?: string) {35  const r = await fetch(`${BASE}/api/v1${path}`, { method, headers: { 'content-type': 'application/json', 'x-spd-csrf': '1', origin: ORIGIN, ...(cookie ? { cookie } : {}), ...(auth ? { authorization: `Bearer ${auth}` } : {}) }, body: method === 'GET' ? undefined : JSON.stringify(body ?? {}) });36  const set = r.headers.getSetCookie?.() ?? [];37  for (const s of set) { const kv = s.split(';')[0]!; if (kv.startsWith('spd=')) cookie = kv; }38  const j: any = await r.json().catch(() => ({}));39  if (!r.ok) throw new Error(`${method} ${path}: ${r.status} ${JSON.stringify(j)}`);40  return j;41}42const [cmd, email, arg] = process.argv.slice(2);43if (cmd === 'register') {44  const o = await call('POST', '/auth/register/options', { invite: arg, displayName: 'Testeur' });45  const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });46  const jwk = publicKey.export({ format: 'jwk' });47  const id = randomBytes(32);48  const cose = cbor(new Map<number, unknown>([[1, 2], [3, -7], [-1, 1], [-2, Buffer.from(jwk.x!, 'base64url')], [-3, Buffer.from(jwk.y!, 'base64url')]]));49  const len = Buffer.alloc(2); len.writeUInt16BE(id.length);50  const ad = authData(0x45, 0, Buffer.concat([Buffer.alloc(16), len, id, cose]));51  save(email!, { id: b64u(id), jwk: privateKey.export({ format: 'jwk' }), userHandle: o.options.user.id, counter: 0 });52  const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.create', challenge: o.options.challenge, origin: ORIGIN, crossOrigin: false }));53  await call('POST', '/auth/register/verify', { invite: arg, challengeId: o.challengeId, label: 'Clé de test', response: { id: b64u(id), rawId: b64u(id), type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',54    response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(cbor(new Map<string, unknown>([['fmt', 'none'], ['attStmt', new Map()], ['authData', ad]]))), transports: ['internal'] } } });55} else if (cmd === 'token') {56  if (!existsSync(file(email!))) throw new Error('account not registered');57  const o = await call('POST', '/auth/login/options');58  const r = await call('POST', '/auth/login/verify', { challengeId: o.challengeId, response: assertion(email!, o.options.challenge), client: { kind: 'native', name: arg ?? 'Mac de test' } });59  process.stdout.write(`${r.token}\n`);60} else if (cmd === 'approve') {61  const o = await call('POST', '/auth/login/options');62  await call('POST', '/auth/login/verify', { challengeId: o.challengeId, response: assertion(email!, o.options.challenge) }); // browser session, passkey just used63  await call('POST', '/auth/device/decide', { code: arg, approve: true });64  process.stdout.write('approved\n');65} else { console.error('usage: register|token|approve'); process.exit(2); }66
Files main
Menu

Theme