SPB Git

Repository Public

webauthn.test.ts 7.3 KB 130 lines typescript

1import { afterEach, describe, expect, it, vi } from "vitest";2import { bytesToBase64url } from "./base64url";3import { createPasskey, creationOptionsFromJSON, credentialToJSON, getPasskey, requestOptionsFromJSON, WebAuthnError } from "./webauthn";45const b = (...n: number[]) => new Uint8Array(n).buffer;6const bytes = (v: BufferSource) => [...new Uint8Array(v instanceof ArrayBuffer ? v : (v as ArrayBufferView).buffer)];78describe("creationOptionsFromJSON", () => {9  const json = {10    rp: { id: "localhost", name: "MCC" },11    user: { id: bytesToBase64url(b(1, 2, 3)), name: "e2e", displayName: "E2E" },12    challenge: bytesToBase64url(b(250, 251, 252, 253)),13    pubKeyCredParams: [{ type: "public-key", alg: -7 }, { type: "public-key", alg: -257 }],14    timeout: 300000,15    authenticatorSelection: { residentKey: "required", userVerification: "required" },16    attestation: "none",17    excludeCredentials: [{ type: "public-key", id: bytesToBase64url(b(9, 9)), transports: ["internal"] }],18  };19  it("converts challenge, user.id and excludeCredentials ids to buffers and keeps the rest", () => {20    const o = creationOptionsFromJSON(json);21    expect(bytes(o.challenge)).toEqual([250, 251, 252, 253]);22    expect(bytes(o.user.id)).toEqual([1, 2, 3]);23    expect(o.user.name).toBe("e2e");24    expect(bytes(o.excludeCredentials?.[0]?.id as ArrayBuffer)).toEqual([9, 9]);25    expect(o.excludeCredentials?.[0]?.transports).toEqual(["internal"]);26    expect(o.pubKeyCredParams).toEqual(json.pubKeyCredParams);27    expect(o.authenticatorSelection).toEqual(json.authenticatorSelection);28    expect(o.timeout).toBe(300000);29  });30  it("omits excludeCredentials when absent and rejects incomplete options", () => {31    const { excludeCredentials: _x, ...rest } = json;32    expect("excludeCredentials" in creationOptionsFromJSON(rest)).toBe(false);33    expect(() => creationOptionsFromJSON({ challenge: "AA" })).toThrow(TypeError);34  });35});3637describe("requestOptionsFromJSON", () => {38  it("converts challenge and allowCredentials", () => {39    const o = requestOptionsFromJSON({ challenge: bytesToBase64url(b(7, 7, 7)), rpId: "localhost", userVerification: "required", allowCredentials: [{ type: "public-key", id: bytesToBase64url(b(4, 5)) }] });40    expect(bytes(o.challenge)).toEqual([7, 7, 7]);41    expect(o.rpId).toBe("localhost");42    expect(bytes(o.allowCredentials?.[0]?.id as ArrayBuffer)).toEqual([4, 5]);43  });44  it("supports discoverable-credential requests without allowCredentials", () => {45    expect("allowCredentials" in requestOptionsFromJSON({ challenge: "AAAA" })).toBe(false);46  });47});4849describe("credentialToJSON (manual fallback)", () => {50  const attestation = {51    id: "abc",52    rawId: b(1, 2),53    type: "public-key",54    authenticatorAttachment: "platform",55    response: {56      clientDataJSON: b(10, 11),57      attestationObject: b(20, 21, 22),58      getTransports: () => ["internal", "hybrid"],59      getPublicKeyAlgorithm: () => -7,60      getPublicKey: () => b(30),61      getAuthenticatorData: () => b(40, 41),62    },63    getClientExtensionResults: () => ({ credProps: { rk: true } }),64  };65  it("serialises an attestation response", () => {66    expect(credentialToJSON(attestation, false)).toEqual({67      id: "abc",68      rawId: "AQI",69      type: "public-key",70      authenticatorAttachment: "platform",71      clientExtensionResults: { credProps: { rk: true } },72      response: { clientDataJSON: "Cgs", attestationObject: "FBUW", transports: ["internal", "hybrid"], publicKeyAlgorithm: -7, publicKey: "Hg", authenticatorData: "KCk" },73    });74  });75  it("serialises an assertion response, userHandle only when present", () => {76    const assertion = { id: "x", rawId: b(5), type: "public-key", response: { clientDataJSON: b(1), authenticatorData: b(2), signature: b(3), userHandle: b(4) } };77    expect(credentialToJSON(assertion, false).response).toEqual({ clientDataJSON: "AQ", authenticatorData: "Ag", signature: "Aw", userHandle: "BA" });78    const noHandle = { ...assertion, response: { ...assertion.response, userHandle: new ArrayBuffer(0) } };79    expect(credentialToJSON(noHandle, false).response).not.toHaveProperty("userHandle");80    expect(credentialToJSON(assertion, false).clientExtensionResults).toEqual({});81  });82  it("prefers the native toJSON and falls back when it throws", () => {83    expect(credentialToJSON({ ...attestation, toJSON: () => ({ id: "native", response: {} }) })).toEqual({ id: "native", response: {} });84    expect(credentialToJSON({ ...attestation, toJSON: () => { throw new Error("boom"); } }).rawId).toBe("AQI");85    expect(credentialToJSON({ ...attestation, toJSON: () => "nonsense" }).rawId).toBe("AQI");86  });87});8889describe("createPasskey / getPasskey", () => {90  afterEach(() => vi.unstubAllGlobals());91  const stub = (credentials: Partial<CredentialsContainer>, statics: Record<string, unknown> = {}) => {92    vi.stubGlobal("PublicKeyCredential", Object.assign(function PublicKeyCredential() {}, statics));93    vi.stubGlobal("navigator", { credentials });94  };9596  it("uses parseCreationOptionsFromJSON when the platform has it", async () => {97    const parsed = { marker: true };98    const create = vi.fn().mockResolvedValue({ id: "c", rawId: b(1), type: "public-key", response: { clientDataJSON: b(1), attestationObject: b(2) } });99    stub({ create }, { parseCreationOptionsFromJSON: () => parsed });100    const out = await createPasskey({ challenge: "AAAA", user: { id: "AQ" } });101    expect(create).toHaveBeenCalledWith({ publicKey: parsed });102    expect(out.rawId).toBe("AQ");103  });104  it("falls back to the manual conversion when the platform helper throws or is missing", async () => {105    const create = vi.fn().mockResolvedValue({ id: "c", rawId: b(1), type: "public-key", response: { clientDataJSON: b(1), attestationObject: b(2) } });106    stub({ create }, { parseCreationOptionsFromJSON: () => { throw new Error("unsupported field"); } });107    await createPasskey({ challenge: "AAAA", user: { id: "AQ", name: "n", displayName: "d" } });108    expect(bytes(create.mock.calls[0]?.[0].publicKey.challenge)).toEqual([0, 0, 0]);109  });110  it("passes conditional mediation and the abort signal to get()", async () => {111    const get = vi.fn().mockResolvedValue({ id: "c", rawId: b(1), type: "public-key", response: { clientDataJSON: b(1), authenticatorData: b(2), signature: b(3) } });112    stub({ get });113    const signal = new AbortController().signal;114    await getPasskey({ challenge: "AAAA" }, { conditional: true, signal });115    expect(get.mock.calls[0]?.[0]).toMatchObject({ mediation: "conditional", signal });116  });117  it("classifies browser errors", async () => {118    const named = (name: string) => Object.assign(new Error(name), { name });119    stub({ get: vi.fn().mockRejectedValue(named("NotAllowedError")), create: vi.fn().mockRejectedValue(named("InvalidStateError")) });120    await expect(getPasskey({ challenge: "AAAA" })).rejects.toMatchObject({ reason: "cancelled" });121    await expect(createPasskey({ challenge: "AAAA", user: { id: "AQ" } })).rejects.toMatchObject({ reason: "duplicate" });122    stub({ get: vi.fn().mockResolvedValue(null) });123    await expect(getPasskey({ challenge: "AAAA" })).rejects.toBeInstanceOf(WebAuthnError);124  });125  it("reports unsupported browsers", async () => {126    vi.stubGlobal("PublicKeyCredential", undefined);127    await expect(getPasskey({ challenge: "AAAA" })).rejects.toMatchObject({ reason: "unsupported" });128  });129});130
Files main
Menu

Theme