Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PasskeyBridge.test.ts

165 lines5.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import { afterEach, vi } from "vite-plus/test";
3​
4import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
5import { installPasskeyBridge } from "./PasskeyBridge.ts";
6​
7const base64Url = (bytes: ReadonlyArray<number>) => Buffer.from(bytes).toString("base64url");
8const bytesOf = (buffer: ArrayBuffer | null) => (buffer ? [...new Uint8Array(buffer)] : null);
9​
10const assertionData = {
11 credentialId: base64Url([1, 2, 3]),
12 clientDataJSON: base64Url([4]),
13 authenticatorData: base64Url([5]),
14 signature: base64Url([6, 7]),
15 userHandle: base64Url([8]),
16 extensions: { prf: { results: { first: base64Url([9]) } } },
17};
18​
19const creationOptions: PublicKeyCredentialCreationOptions = {
20 challenge: new Uint8Array([1]),
21 rp: { name: "Example" },
22 user: { id: new Uint8Array([2]), name: "alice", displayName: "Alice" },
23 pubKeyCredParams: [{ type: "public-key", alg: -7 }],
24};
25​
26const illegalInvocation = (): never => {
27 throw new TypeError("Illegal invocation");
28};
29​
30/**
31 * Installs the bridge over fresh stand-ins for the page's DOM classes. Like
32 * Chromium's, their getters only work on objects the browser created itself.
33 */
34const install = (respond: (channel: string) => unknown) => {
35 const nativeCreate = vi.fn(async () => "native-create");
36 const nativeGet = vi.fn(async () => "native-get");
37 class FakeCredentialsContainer {
38 create() {
39 return nativeCreate();
40 }
41 get() {
42 return nativeGet();
43 }
44 }
45 class FakePublicKeyCredential {
46 get id() {
47 return illegalInvocation();
48 }
49 get response() {
50 return illegalInvocation();
51 }
52 }
53 class FakeAttestationResponse {
54 get clientDataJSON() {
55 return illegalInvocation();
56 }
57 }
58 class FakeAssertionResponse {
59 get signature() {
60 return illegalInvocation();
61 }
62 }
63 vi.stubGlobal("CredentialsContainer", FakeCredentialsContainer);
64 vi.stubGlobal("PublicKeyCredential", FakePublicKeyCredential);
65 vi.stubGlobal("AuthenticatorAttestationResponse", FakeAttestationResponse);
66 vi.stubGlobal("AuthenticatorAssertionResponse", FakeAssertionResponse);
67​
68 const invoke = vi.fn(async (channel: string, _publicKey: unknown) => respond(channel));
69 installPasskeyBridge(invoke);
70 return {
71 invoke,
72 nativeCreate,
73 nativeGet,
74 credentials: new FakeCredentialsContainer() as unknown as CredentialsContainer,
75 FakePublicKeyCredential,
76 FakeAttestationResponse,
77 FakeAssertionResponse,
78 };
79};
80​
81describe("installPasskeyBridge", () => {
82 afterEach(() => {
83 vi.unstubAllGlobals();
84 });
85​
86 it("serves passkey sign-in through the main process with a credential pages can verify", async () => {
87 const { invoke, credentials, FakePublicKeyCredential, FakeAssertionResponse } = install(() => ({
88 success: true,
89 data: assertionData,
90 }));
91 const challenge = new Uint8Array([0, 1, 2, 3]).subarray(1);
92​
93 const credential = (await credentials.get({
94 publicKey: {
95 challenge,
96 rpId: "example.com",
97 allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
98 extensions: { onHint: () => {} } as AuthenticationExtensionsClientInputs,
99 },
100 })) as PublicKeyCredential;
101​
102 assert.deepStrictEqual(invoke.mock.calls[0], [
103 PASSKEY_GET_CHANNEL,
104 {
105 challenge: new Uint8Array([1, 2, 3]),
106 rpId: "example.com",
107 allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
108 extensions: {},
109 },
110 ]);
111 const response = credential.response as AuthenticatorAssertionResponse;
112 assert.instanceOf(credential, FakePublicKeyCredential);
113 assert.instanceOf(response, FakeAssertionResponse);
114 assert.strictEqual(credential.id, assertionData.credentialId);
115 assert.deepStrictEqual(bytesOf(credential.rawId), [1, 2, 3]);
116 assert.deepStrictEqual(bytesOf(response.signature), [6, 7]);
117 assert.deepStrictEqual(bytesOf(response.userHandle), [8]);
118 assert.deepStrictEqual(
119 bytesOf(credential.getClientExtensionResults().prf?.results?.first as ArrayBuffer),
120 [9],
121 );
122 assert.deepStrictEqual(credential.toJSON(), {
123 id: assertionData.credentialId,
124 rawId: assertionData.credentialId,
125 type: "public-key",
126 response: {
127 clientDataJSON: assertionData.clientDataJSON,
128 authenticatorData: assertionData.authenticatorData,
129 signature: assertionData.signature,
130 userHandle: assertionData.userHandle,
131 },
132 clientExtensionResults: { prf: { results: { first: base64Url([9]) } } },
133 });
134 });
135​
136 it("rejects with the WebAuthn error the ceremony ended with", async () => {
137 const { credentials } = install((channel) => ({
138 success: false,
139 error: channel === PASSKEY_CREATE_CHANNEL ? "InvalidStateError" : "TypeError",
140 }));
141 const created = await credentials
142 .create({ publicKey: creationOptions })
143 .catch((error: unknown) => error);
144 assert.instanceOf(created, DOMException);
145 assert.strictEqual((created as DOMException).name, "InvalidStateError");
146 const fetched = await credentials
147 .get({ publicKey: { challenge: new Uint8Array([1]) } })
148 .catch((error: unknown) => error);
149 assert.instanceOf(fetched, TypeError);
150 });
151​
152 it("rejects as soon as the page aborts, without waiting on the system sheet", async () => {
153 const { credentials } = install(() => new Promise(() => {}));
154 const controller = new AbortController();
155​
156 const pending = credentials
157 .get({ publicKey: { challenge: new Uint8Array([1]) }, signal: controller.signal })
158 .catch((error: unknown) => error);
159 controller.abort();
160​
161 const error = await pending;
162 assert.instanceOf(error, DOMException);
163 assert.strictEqual((error as DOMException).name, "AbortError");
164 });
165});