Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Music SP8 * File : tests/webauthn.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/sp-music11 * Project Website : https://music.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1714 *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: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { createHash, createSign, generateKeyPairSync, randomBytes, type KeyObject } from "node:crypto";4445/**46 * A software WebAuthn authenticator for the tests: real P-256 keys, real signatures, "none" attestation — the47 * server verifies its responses exactly as it verifies a phone's. It can also misbehave on request (wrong origin,48 * corrupted signature) to prove those are rejected.49 */50const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url");51const sha256 = (b: Buffer | string) => createHash("sha256").update(b).digest();5253// Minimal CBOR encoder (ints, byte strings, text strings, maps) — enough for an attestation object and a COSE key.54function head(major: number, n: number): Buffer {55 if (n < 24) return Buffer.from([(major << 5) | n]);56 if (n < 256) return Buffer.from([(major << 5) | 24, n]);57 if (n < 65536) return Buffer.from([(major << 5) | 25, n >> 8, n & 0xff]);58 const b = Buffer.alloc(5); b[0] = (major << 5) | 26; b.writeUInt32BE(n, 1); return b;59}60type Cbor = number | string | Buffer | Map<Cbor, Cbor>;61function cbor(v: Cbor): Buffer {62 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);63 if (typeof v === "string") { const b = Buffer.from(v, "utf8"); return Buffer.concat([head(3, b.length), b]); }64 if (Buffer.isBuffer(v)) return Buffer.concat([head(2, v.length), v]);65 return Buffer.concat([head(5, v.size), ...Array.from(v).flatMap(([k, x]) => [cbor(k), cbor(x)])]);66}6768export interface Tamper { origin?: string; badSignature?: boolean; noUserVerification?: boolean; rpId?: string }6970export class SoftAuthenticator {71 private creds = new Map<string, { key: KeyObject; counter: number; userHandle: string }>();72 constructor(private origin: string, private rpId: string) {}7374 create(options: { challenge: string; user: { id: string } }, t: Tamper = {}) {75 const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });76 const jwk = publicKey.export({ format: "jwk" });77 const credId = randomBytes(16);78 const cose = cbor(new Map<Cbor, Cbor>([[1, 2], [3, -7], [-1, 1], [-2, Buffer.from(jwk.x!, "base64url")], [-3, Buffer.from(jwk.y!, "base64url")]]));79 const len = Buffer.alloc(2); len.writeUInt16BE(credId.length);80 const authData = Buffer.concat([sha256(t.rpId ?? this.rpId), Buffer.from([t.noUserVerification ? 0x41 : 0x45]), Buffer.alloc(4), Buffer.alloc(16), len, credId, cose]);81 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: t.origin ?? this.origin, crossOrigin: false }));82 const attestationObject = cbor(new Map<Cbor, Cbor>([["fmt", "none"], ["attStmt", new Map()], ["authData", authData]]));83 this.creds.set(b64u(credId), { key: privateKey, counter: 0, userHandle: options.user.id });84 return { id: b64u(credId), rawId: b64u(credId), type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},85 response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] } };86 }8788 get(options: { challenge: string }, credentialId?: string, t: Tamper = {}) {89 const id = credentialId ?? Array.from(this.creds.keys()).pop()!;90 const c = this.creds.get(id)!;91 c.counter++;92 const counter = Buffer.alloc(4); counter.writeUInt32BE(c.counter);93 const authData = Buffer.concat([sha256(t.rpId ?? this.rpId), Buffer.from([t.noUserVerification ? 0x01 : 0x05]), counter]);94 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: t.origin ?? this.origin, crossOrigin: false }));95 const signature = createSign("SHA256").update(Buffer.concat([authData, sha256(clientDataJSON)])).sign(c.key);96 if (t.badSignature) signature[signature.length - 1] ^= 0xff;97 return { id, rawId: id, type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},98 response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: c.userHandle } };99 }100 get ids() { return Array.from(this.creds.keys()); }101}102