passkey-crypto.test.ts

6.4 KB · raw

1import { describe, expect, it } from "vitest";23import {4  buildAuthenticatorData,5  buildClientDataJSON,6  createAttestationObject,7  generatePasskeyKeypair,8  importPasskeyPrivateKey,9  publicKeyJwkToCose,10  signPasskeyAssertion,11} from "./passkey-crypto";1213// Inverse of the DER encoder inside passkey-crypto: parse SEQUENCE { INTEGER r,14// INTEGER s } back into a fixed-width r||s buffer of 2*coordSize bytes.15function derEcdsaToP1363(der: Uint8Array, coordSize: number): Uint8Array {16  if (der[0] !== 0x30) throw new Error("not a SEQUENCE");17  let off = 2;18  if (der[1]! & 0x80) off = 2 + (der[1]! & 0x7f);19  if (der[off] !== 0x02) throw new Error("missing r INTEGER");20  const rLen = der[off + 1]!;21  let r = der.slice(off + 2, off + 2 + rLen);22  off = off + 2 + rLen;23  if (der[off] !== 0x02) throw new Error("missing s INTEGER");24  const sLen = der[off + 1]!;25  let s = der.slice(off + 2, off + 2 + sLen);26  if (r.length > coordSize) r = r.slice(r.length - coordSize);27  if (s.length > coordSize) s = s.slice(s.length - coordSize);28  const out = new Uint8Array(coordSize * 2);29  out.set(r, coordSize - r.length);30  out.set(s, coordSize * 2 - s.length);31  return out;32}3334describe("passkey crypto", () => {35  it("encodes cross-origin context while defaulting existing callers to same-origin", () => {36    const decode = (crossOrigin?: boolean) => JSON.parse(new TextDecoder().decode(37      buildClientDataJSON("webauthn.get", "Y2g", "https://accounts.example", crossOrigin),38    ));39    expect(decode().crossOrigin).toBe(false);40    expect(decode(false).crossOrigin).toBe(false);41    expect(decode(true).crossOrigin).toBe(true);42  });4344  it("generates importable ES256 passkey material", async () => {45    const generated = await generatePasskeyKeypair(-7);46    const privateKey = await crypto.subtle.importKey(47      "jwk",48      generated.privateKeyJwk,49      { name: "ECDSA", namedCurve: "P-256" },50      true,51      ["sign"]52    );53    const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", privateKey));54    const imported = await importPasskeyPrivateKey(pkcs8);5556    expect(imported.algorithm).toBe(-7);57    expect(imported.privateKeyJwk.kty).toBe("EC");58    expect(imported.publicKeyCose.length).toBeGreaterThan(32);59    expect(generated.publicKeySpki.length).toBeGreaterThan(64);60  });6162  it("generatePasskeyKeypair returns unique keypairs across calls", async () => {63    const first = await generatePasskeyKeypair(-7);64    const second = await generatePasskeyKeypair(-7);6566    expect(first.privateKeyJwk.d).not.toBe(second.privateKeyJwk.d);67    expect(first.publicKeySpki).not.toEqual(second.publicKeySpki);68  });6970  it("builds authenticator data and signs an assertion", async () => {71    const generated = await generatePasskeyKeypair(-7);72    const credentialId = crypto.getRandomValues(new Uint8Array(32));73    const registrationAuthData = await buildAuthenticatorData({74      rpId: "webauthn.io",75      flags: 0x4d,76      signCount: 0,77      credentialId,78      publicKeyCose: generated.publicKeyCose,79    });80    const assertionAuthData = await buildAuthenticatorData({81      rpId: "webauthn.io",82      flags: 0x05,83      signCount: 1,84    });85    const clientDataJSON = buildClientDataJSON(86      "webauthn.get",87      "ZmFrZS1jaGFsbGVuZ2U",88      "https://webauthn.io"89    );90    const clientDataHash = new Uint8Array(91      await crypto.subtle.digest("SHA-256", new Uint8Array(clientDataJSON))92    );93    const signature = await signPasskeyAssertion(94      generated.privateKeyJwk,95      -7,96      assertionAuthData,97      clientDataHash98    );99100    expect(registrationAuthData.length).toBeGreaterThan(80);101    expect(assertionAuthData.length).toBe(37);102    expect(signature.length).toBeGreaterThan(40);103  });104105  it("signPasskeyAssertion produces a signature verifiable with the corresponding public key", async () => {106    const generated = await generatePasskeyKeypair(-7);107    const authenticatorData = await buildAuthenticatorData({108      rpId: "webauthn.io",109      flags: 0x05,110      signCount: 1,111    });112    const clientDataJSON = buildClientDataJSON(113      "webauthn.get",114      "ZmFrZS1jaGFsbGVuZ2U",115      "https://webauthn.io"116    );117    const clientDataHash = new Uint8Array(118      await crypto.subtle.digest("SHA-256", clientDataJSON.buffer as ArrayBuffer)119    );120    const signature = await signPasskeyAssertion(121      generated.privateKeyJwk,122      -7,123      authenticatorData,124      clientDataHash125    );126    const publicKey = await crypto.subtle.importKey(127      "spki",128      generated.publicKeySpki.buffer as ArrayBuffer,129      { name: "ECDSA", namedCurve: "P-256" },130      false,131      ["verify"]132    );133134    // signPasskeyAssertion returns DER (WebAuthn-spec format). SubtleCrypto.verify135    // expects raw IEEE P1363 (r||s) for ECDSA. Convert before verifying.136    const raw = derEcdsaToP1363(signature, 32);137    const verified = await crypto.subtle.verify(138      { name: "ECDSA", hash: "SHA-256" },139      publicKey,140      raw.buffer as ArrayBuffer,141      new Uint8Array([...authenticatorData, ...clientDataHash]).buffer as ArrayBuffer142    );143144    expect(verified).toBe(true);145  });146147  it("buildAuthenticatorData embeds the rpId hash, flags, and signCount", async () => {148    const authData = await buildAuthenticatorData({149      rpId: "webauthn.io",150      flags: 0x05,151      signCount: 7,152    });153    const expectedHash = new Uint8Array(154      await crypto.subtle.digest(155        "SHA-256",156        new TextEncoder().encode("webauthn.io").buffer as ArrayBuffer157      )158    );159160    expect(authData.slice(0, 32)).toEqual(expectedHash);161    expect(authData[32]).toBe(0x05);162    expect(new DataView(authData.buffer).getUint32(33, false)).toBe(7);163  });164165  it("createAttestationObject includes fmt:none and the supplied authData", async () => {166    const authData = await buildAuthenticatorData({167      rpId: "webauthn.io",168      flags: 0x41,169      signCount: 0,170    });171    const attestation = createAttestationObject(authData);172    const ascii = new TextDecoder().decode(attestation);173174    expect(ascii).toContain("fmt");175    expect(ascii).toContain("none");176    expect(ascii).toContain("authData");177    expect(attestation.includes(authData[0])).toBe(true);178  });179180  it("publicKeyJwkToCose encodes a P-256 public key into COSE bytes", async () => {181    const generated = await generatePasskeyKeypair(-7);182    const cose = publicKeyJwkToCose(generated.privateKeyJwk, -7);183184    expect(cose[0]).toBeGreaterThanOrEqual(0xa0);185    expect(cose.length).toBeGreaterThan(16);186  });187});