Open History to see the last commit
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 attestationData = {
20 credentialId: base64Url([1, 2, 3]),
21 clientDataJSON: base64Url([4]),
22 attestationObject: base64Url([10]),
23 authData: base64Url([11]),
24 publicKey: base64Url([12]),
25 publicKeyAlgorithm: -7,
26 transports: [],
27 extensions: { credProps: { rk: true } },
28};
29
30const creationOptions: PublicKeyCredentialCreationOptions = {
31 challenge: new Uint8Array([1]),
32 rp: { name: "Example" },
33 user: { id: new Uint8Array([2]), name: "alice", displayName: "Alice" },
34 pubKeyCredParams: [{ type: "public-key", alg: -7 }],
35};
36
37const illegalInvocation = (): never => {
38 throw new TypeError("Illegal invocation");
39};
40
41/**
42 * Installs the bridge over fresh stand-ins for the page's DOM classes. Like
43 * Chromium's, their getters only work on objects the browser created itself.
44 */
45const install = (respond: (channel: string) => unknown) => {
46 const nativeCreate = vi.fn(async () => "native-create");
47 const nativeGet = vi.fn(async () => "native-get");
48 class FakeCredentialsContainer {
49 create() {
50 return nativeCreate();
51 }
52 get() {
53 return nativeGet();
54 }
55 }
56 class FakePublicKeyCredential {
57 get id() {
58 return illegalInvocation();
59 }
60 get response() {
61 return illegalInvocation();
62 }
63 }
64 class FakeAttestationResponse {
65 get clientDataJSON() {
66 return illegalInvocation();
67 }
68 }
69 class FakeAssertionResponse {
70 get signature() {
71 return illegalInvocation();
72 }
73 }
74 vi.stubGlobal("CredentialsContainer", FakeCredentialsContainer);
75 vi.stubGlobal("PublicKeyCredential", FakePublicKeyCredential);
76 vi.stubGlobal("AuthenticatorAttestationResponse", FakeAttestationResponse);
77 vi.stubGlobal("AuthenticatorAssertionResponse", FakeAssertionResponse);
78
79 const invoke = vi.fn(async (channel: string, _publicKey: unknown) => respond(channel));
80 installPasskeyBridge(invoke);
81 return {
82 invoke,
83 nativeCreate,
84 nativeGet,
85 credentials: new FakeCredentialsContainer() as unknown as CredentialsContainer,
86 FakePublicKeyCredential,
87 FakeAttestationResponse,
88 FakeAssertionResponse,
89 };
90};
91
92describe("installPasskeyBridge", () => {
93 afterEach(() => {
94 vi.unstubAllGlobals();
95 });
96
97 it("serves passkey sign-in through the main process with a credential pages can verify", async () => {
98 const { invoke, credentials, FakePublicKeyCredential, FakeAssertionResponse } = install(() => ({
99 success: true,
100 data: assertionData,
101 }));
102 const challenge = new Uint8Array([0, 1, 2, 3]).subarray(1);
103
104 const credential = (await credentials.get({
105 publicKey: {
106 challenge,
107 rpId: "example.com",
108 allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
109 extensions: { onHint: () => {} } as AuthenticationExtensionsClientInputs,
110 },
111 })) as PublicKeyCredential;
112
113 assert.deepStrictEqual(invoke.mock.calls[0], [
114 PASSKEY_GET_CHANNEL,
115 {
116 challenge: new Uint8Array([1, 2, 3]),
117 rpId: "example.com",
118 allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
119 extensions: {},
120 },
121 ]);
122 const response = credential.response as AuthenticatorAssertionResponse;
123 assert.instanceOf(credential, FakePublicKeyCredential);
124 assert.instanceOf(response, FakeAssertionResponse);
125 assert.strictEqual(credential.id, assertionData.credentialId);
126 assert.deepStrictEqual(bytesOf(credential.rawId), [1, 2, 3]);
127 assert.deepStrictEqual(bytesOf(response.signature), [6, 7]);
128 assert.deepStrictEqual(bytesOf(response.userHandle), [8]);
129 assert.deepStrictEqual(
130 bytesOf(credential.getClientExtensionResults().prf?.results?.first as ArrayBuffer),
131 [9],
132 );
133 assert.deepStrictEqual(credential.toJSON(), {
134 id: assertionData.credentialId,
135 rawId: assertionData.credentialId,
136 type: "public-key",
137 response: {
138 clientDataJSON: assertionData.clientDataJSON,
139 authenticatorData: assertionData.authenticatorData,
140 signature: assertionData.signature,
141 userHandle: assertionData.userHandle,
142 },
143 clientExtensionResults: { prf: { results: { first: base64Url([9]) } } },
144 });
145 });
146
147 it("returns registrations with their attestation and public key", async () => {
148 const { invoke, credentials, FakeAttestationResponse } = install(() => ({
149 success: true,
150 data: attestationData,
151 }));
152
153 const credential = (await credentials.create({
154 publicKey: creationOptions,
155 })) as PublicKeyCredential;
156
157 assert.strictEqual(invoke.mock.calls[0]?.[0], PASSKEY_CREATE_CHANNEL);
158 const response = credential.response as AuthenticatorAttestationResponse;
159 assert.instanceOf(response, FakeAttestationResponse);
160 assert.isNull(credential.authenticatorAttachment);
161 assert.deepStrictEqual(bytesOf(response.attestationObject), [10]);
162 assert.deepStrictEqual(bytesOf(response.getAuthenticatorData()), [11]);
163 assert.deepStrictEqual(bytesOf(response.getPublicKey()), [12]);
164 assert.strictEqual(response.getPublicKeyAlgorithm(), -7);
165 assert.deepStrictEqual(credential.getClientExtensionResults(), { credProps: { rk: true } });
166 assert.deepStrictEqual(credential.toJSON(), {
167 id: attestationData.credentialId,
168 rawId: attestationData.credentialId,
169 type: "public-key",
170 response: {
171 clientDataJSON: attestationData.clientDataJSON,
172 attestationObject: attestationData.attestationObject,
173 authenticatorData: attestationData.authData,
174 transports: [],
175 publicKey: attestationData.publicKey,
176 publicKeyAlgorithm: -7,
177 },
178 clientExtensionResults: { credProps: { rk: true } },
179 });
180 });
181
182 it("leaves autofill and non-passkey requests to Chromium", async () => {
183 const { invoke, credentials, nativeCreate, nativeGet } = install(() => ({
184 success: true,
185 data: assertionData,
186 }));
187
188 await credentials.get({
189 mediation: "conditional",
190 publicKey: { challenge: new Uint8Array([1]) },
191 });
192 await credentials.get({ password: true } as CredentialRequestOptions);
193 const upgrade = { mediation: "conditional", publicKey: creationOptions } as const;
194 await credentials.create(upgrade);
195 await credentials.create({ password: {} } as CredentialCreationOptions);
196 assert.strictEqual(invoke.mock.calls.length, 0);
197 assert.strictEqual(nativeGet.mock.calls.length, 2);
198 assert.strictEqual(nativeCreate.mock.calls.length, 2);
199 assert.isFalse(await PublicKeyCredential.isConditionalMediationAvailable());
200 assert.isTrue(await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable());
201 });
202
203 it("rejects with the WebAuthn error the ceremony ended with", async () => {
204 const { credentials } = install((channel) => ({
205 success: false,
206 error: channel === PASSKEY_CREATE_CHANNEL ? "InvalidStateError" : "TypeError",
207 }));
208 const created = await credentials
209 .create({ publicKey: creationOptions })
210 .catch((error: unknown) => error);
211 assert.instanceOf(created, DOMException);
212 assert.strictEqual((created as DOMException).name, "InvalidStateError");
213 const fetched = await credentials
214 .get({ publicKey: { challenge: new Uint8Array([1]) } })
215 .catch((error: unknown) => error);
216 assert.instanceOf(fetched, TypeError);
217 });
218
219 it("refuses when the main process has no handler for the page", async () => {
220 const { credentials } = install(() => {
221 throw new Error("Error invoking remote method 'preview:passkey-get': No handler registered");
222 });
223
224 const error = await credentials
225 .get({ publicKey: { challenge: new Uint8Array([1]) } })
226 .catch((caught: unknown) => caught);
227 assert.instanceOf(error, DOMException);
228 assert.strictEqual((error as DOMException).name, "NotAllowedError");
229 });
230
231 it("rejects as soon as the page aborts, without waiting on the system sheet", async () => {
232 const { credentials } = install(() => new Promise(() => {}));
233 const controller = new AbortController();
234
235 const pending = credentials
236 .get({ publicKey: { challenge: new Uint8Array([1]) }, signal: controller.signal })
237 .catch((error: unknown) => error);
238 controller.abort();
239
240 const error = await pending;
241 assert.instanceOf(error, DOMException);
242 assert.strictEqual((error as DOMException).name, "AbortError");
243 });
244});