SPB Git

Repository Public

webauthn.ts 4.0 KB 60 lines typescript

1import { createHash, createSign, generateKeyPairSync, randomBytes, type KeyObject } from "node:crypto";23/**4 * A software WebAuthn authenticator for the tests: real P-256 keys, real signatures, "none" attestation — the5 * server verifies its responses exactly as it verifies a phone's. It can also misbehave on request (wrong origin,6 * corrupted signature) to prove those are rejected.7 */8const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url");9const sha256 = (b: Buffer | string) => createHash("sha256").update(b).digest();1011// Minimal CBOR encoder (ints, byte strings, text strings, maps) — enough for an attestation object and a COSE key.12function head(major: number, n: number): Buffer {13  if (n < 24) return Buffer.from([(major << 5) | n]);14  if (n < 256) return Buffer.from([(major << 5) | 24, n]);15  if (n < 65536) return Buffer.from([(major << 5) | 25, n >> 8, n & 0xff]);16  const b = Buffer.alloc(5); b[0] = (major << 5) | 26; b.writeUInt32BE(n, 1); return b;17}18type Cbor = number | string | Buffer | Map<Cbor, Cbor>;19function cbor(v: Cbor): Buffer {20  if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);21  if (typeof v === "string") { const b = Buffer.from(v, "utf8"); return Buffer.concat([head(3, b.length), b]); }22  if (Buffer.isBuffer(v)) return Buffer.concat([head(2, v.length), v]);23  return Buffer.concat([head(5, v.size), ...Array.from(v).flatMap(([k, x]) => [cbor(k), cbor(x)])]);24}2526export interface Tamper { origin?: string; badSignature?: boolean; noUserVerification?: boolean; rpId?: string }2728export class SoftAuthenticator {29  private creds = new Map<string, { key: KeyObject; counter: number; userHandle: string }>();30  constructor(private origin: string, private rpId: string) {}3132  create(options: { challenge: string; user: { id: string } }, t: Tamper = {}) {33    const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });34    const jwk = publicKey.export({ format: "jwk" });35    const credId = randomBytes(16);36    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")]]));37    const len = Buffer.alloc(2); len.writeUInt16BE(credId.length);38    const authData = Buffer.concat([sha256(t.rpId ?? this.rpId), Buffer.from([t.noUserVerification ? 0x41 : 0x45]), Buffer.alloc(4), Buffer.alloc(16), len, credId, cose]);39    const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: t.origin ?? this.origin, crossOrigin: false }));40    const attestationObject = cbor(new Map<Cbor, Cbor>([["fmt", "none"], ["attStmt", new Map()], ["authData", authData]]));41    this.creds.set(b64u(credId), { key: privateKey, counter: 0, userHandle: options.user.id });42    return { id: b64u(credId), rawId: b64u(credId), type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},43      response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] } };44  }4546  get(options: { challenge: string }, credentialId?: string, t: Tamper = {}) {47    const id = credentialId ?? Array.from(this.creds.keys()).pop()!;48    const c = this.creds.get(id)!;49    c.counter++;50    const counter = Buffer.alloc(4); counter.writeUInt32BE(c.counter);51    const authData = Buffer.concat([sha256(t.rpId ?? this.rpId), Buffer.from([t.noUserVerification ? 0x01 : 0x05]), counter]);52    const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: t.origin ?? this.origin, crossOrigin: false }));53    const signature = createSign("SHA256").update(Buffer.concat([authData, sha256(clientDataJSON)])).sign(c.key);54    if (t.badSignature) signature[signature.length - 1] ^= 0xff;55    return { id, rawId: id, type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},56      response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: c.userHandle } };57  }58  get ids() { return Array.from(this.creds.keys()); }59}60
Files main
Menu

Theme