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

Passkeys.test.ts

367 lines14.3 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import { afterEach, beforeEach, vi } from "vite-plus/test";
7​
8const electron = vi.hoisted(() => ({
9 configureWebAuthn: vi.fn(),
10 showMessageBox: vi.fn(),
11 fromWebContents: vi.fn(),
12}));
13const webauthn = vi.hoisted(() => ({ createCredential: vi.fn(), getCredential: vi.fn() }));
14​
15vi.mock("electron", () => ({
16 app: { configureWebAuthn: electron.configureWebAuthn },
17 dialog: { showMessageBox: electron.showMessageBox },
18 BrowserWindow: { fromWebContents: electron.fromWebContents },
19 webContents: { fromFrame: () => undefined },
20}));
21vi.mock("electron-webauthn", () => webauthn);
22​
23import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
24import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
25import * as PreviewPasskeys from "./Passkeys.ts";
26​
27const layerFor = (packageJson: object, isPackaged = true) =>
28 PreviewPasskeys.layer.pipe(
29 Layer.provide(
30 Layer.succeed(
31 DesktopEnvironment.DesktopEnvironment,
32 DesktopEnvironment.DesktopEnvironment.of({
33 platform: "darwin",
34 isPackaged,
35 appRoot: "/app",
36 path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
37 } as DesktopEnvironment.DesktopEnvironment["Service"]),
38 ),
39 ),
40 Layer.provide(
41 FileSystem.layerNoop({
42 readFileString: () => Effect.succeed(JSON.stringify(packageJson)),
43 }),
44 ),
45 );
46​
47type Handler = (event: { readonly senderFrame: object | null }, publicKey: unknown) => unknown;
48​
49const makeGuest = (origin = "https://accounts.example.com") => {
50 const handlers = new Map<string, Handler>();
51 const state = { focused: true };
52 const mainFrame = { origin, isDestroyed: () => false };
53 const guest = {
54 mainFrame,
55 hostWebContents: {},
56 isFocused: () => state.focused,
57 ipc: {
58 handle: (channel: string, handler: Handler) => handlers.set(channel, handler),
59 removeHandler: (channel: string) => handlers.delete(channel),
60 },
61 };
62 const call = (channel: string, publicKey: unknown, senderFrame: object | null = mainFrame) =>
63 Effect.promise(async () => handlers.get(channel)?.({ senderFrame }, publicKey));
64 return { guest: guest as unknown as Electron.WebContents, mainFrame, handlers, state, call };
65};
66​
67const bridgeLayer = layerFor({ t3codeWebAuthn: { browserPasskeys: true } });
68​
69const attestationObject = (authData: ReadonlyArray<number>) => {
70 const text = (value: string) => [0x60 + value.length, ...Buffer.from(value)];
71 const bytes = (value: ReadonlyArray<number>) => [0x58, value.length, ...value];
72 return Buffer.from([
73 0xa3,
74 ...text("fmt"),
75 ...text("packed"),
76 ...text("attStmt"),
77 0xa2,
78 ...text("alg"),
79 0x26,
80 ...text("sig"),
81 ...bytes(Array.from({ length: 70 }, () => 7)),
82 ...text("authData"),
83 ...bytes(authData),
84 ]).toString("base64url");
85};
86​
87describe("PreviewPasskeys", () => {
88 beforeEach(() => {
89 vi.clearAllMocks();
90 electron.fromWebContents.mockReturnValue({
91 isDestroyed: () => false,
92 getNativeWindowHandle: () => Buffer.from([1]),
93 });
94 });
95 afterEach(() => {
96 vi.useRealTimers();
97 });
98​
99 it.effect("pins each guest ceremony to the origin of the frame that asked", () =>
100 Effect.gen(function* () {
101 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
102 const { guest, handlers, call } = makeGuest();
103 webauthn.getCredential.mockResolvedValue({
104 success: false,
105 error: "NotAllowedError",
106 errorObject: new Error("native detail"),
107 });
108​
109 const detach = passkeys.attachGuest(guest);
110 const publicKey = { challenge: new Uint8Array([1]), rpId: "example.com" };
111 const result = yield* call(PASSKEY_GET_CHANNEL, publicKey);
112​
113 assert.deepStrictEqual(result, { success: false, error: "NotAllowedError" });
114 const [sentPublicKey, options] = webauthn.getCredential.mock.calls[0] ?? [];
115 assert.deepStrictEqual(sentPublicKey, publicKey);
116 assert.strictEqual(options.currentOrigin, "https://accounts.example.com");
117 assert.strictEqual(options.topFrameOrigin, "https://accounts.example.com");
118 assert.isTrue(options.isPublicSuffix("com"));
119 assert.isTrue(options.isPublicSuffix("github.io"));
120 assert.isFalse(options.isPublicSuffix("example.com"));
121 assert.isFalse(options.isPublicSuffix("localhost"));
122​
123 // WebAuthn defaults the RP ID to the caller's own host.
124 yield* call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]) });
125 assert.strictEqual(webauthn.getCredential.mock.calls[1]?.[0].rpId, "accounts.example.com");
126​
127 const forged = yield* call(PASSKEY_CREATE_CHANNEL, publicKey, {
128 origin: "https://evil.example",
129 });
130 assert.deepStrictEqual(forged, { success: false, error: "NotAllowedError" });
131 assert.strictEqual(webauthn.createCredential.mock.calls.length, 0);
132​
133 detach();
134 assert.strictEqual(handlers.size, 0);
135 }).pipe(Effect.provide(bridgeLayer)),
136 );
137​
138 it.effect("registers ES256 keys only and reports their real authenticator data", () =>
139 Effect.gen(function* () {
140 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
141 const { guest, call } = makeGuest();
142 passkeys.attachGuest(guest);
143 webauthn.createCredential.mockResolvedValue({
144 success: true,
145 data: {
146 credentialId: "AQ",
147 clientDataJSON: "Ag",
148 attestationObject: attestationObject([1, 2, 3, 4]),
149 authData: Buffer.from('{"parsed":true}').toString("base64url"),
150 publicKey: "BQ",
151 publicKeyAlgorithm: -7,
152 transports: ["hybrid", "internal"],
153 extensions: {},
154 },
155 });
156 const publicKey = {
157 challenge: new Uint8Array([1]),
158 pubKeyCredParams: [
159 { type: "public-key", alg: -8 },
160 { type: "public-key", alg: -7 },
161 { type: "public-key", alg: -257 },
162 ],
163 };
164​
165 const result = yield* call(PASSKEY_CREATE_CHANNEL, publicKey);
166​
167 assert.deepStrictEqual(webauthn.createCredential.mock.calls[0]?.[0].pubKeyCredParams, [
168 { type: "public-key", alg: -7 },
169 ]);
170 assert.deepInclude(result, { success: true });
171 const data = (result as { readonly data: Record<string, unknown> }).data;
172 assert.strictEqual(data.authData, Buffer.from([1, 2, 3, 4]).toString("base64url"));
173 assert.deepStrictEqual(data.transports, []);
174​
175 const unsupported = yield* call(PASSKEY_CREATE_CHANNEL, {
176 ...publicKey,
177 pubKeyCredParams: [{ type: "public-key", alg: -8 }],
178 });
179 assert.deepStrictEqual(unsupported, { success: false, error: "NotSupportedError" });
180 assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
181​
182 const malformed = yield* call(PASSKEY_CREATE_CHANNEL, {
183 ...publicKey,
184 pubKeyCredParams: { type: "public-key", alg: -7 },
185 });
186 assert.deepStrictEqual(malformed, { success: false, error: "TypeError" });
187 assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
188​
189 webauthn.createCredential.mockResolvedValueOnce({
190 success: true,
191 data: { credentialId: "AQ", attestationObject: Buffer.from([0x00]).toString("base64url") },
192 });
193 assert.deepStrictEqual(yield* call(PASSKEY_CREATE_CHANNEL, publicKey), {
194 success: false,
195 error: "NotAllowedError",
196 });
197 }).pipe(Effect.provide(bridgeLayer)),
198 );
199​
200 it.effect("answers only with a credential the site allowed", () =>
201 Effect.gen(function* () {
202 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
203 const { guest, call } = makeGuest();
204 passkeys.attachGuest(guest);
205 const assertion = (credentialId: string) => ({
206 success: true,
207 data: {
208 credentialId,
209 clientDataJSON: "Ag",
210 authenticatorData: "Aw",
211 signature: "BA",
212 userHandle: "BQ",
213 },
214 });
215 const publicKey = {
216 challenge: new Uint8Array([1]),
217 rpId: "example.com",
218 allowCredentials: [{ type: "public-key", id: new Uint8Array([1]) }],
219 };
220​
221 // macOS applies the allow list to passkeys but not to security keys.
222 webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
223 const other = yield* call(PASSKEY_GET_CHANNEL, publicKey);
224 assert.deepStrictEqual(other, { success: false, error: "NotAllowedError" });
225​
226 webauthn.getCredential.mockResolvedValueOnce(assertion("AQ"));
227 assert.deepInclude(yield* call(PASSKEY_GET_CHANNEL, publicKey), { success: true });
228​
229 webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
230 const discoverable = yield* call(PASSKEY_GET_CHANNEL, {
231 challenge: new Uint8Array([1]),
232 rpId: "example.com",
233 });
234 assert.deepInclude(discoverable, { success: true });
235 }).pipe(Effect.provide(bridgeLayer)),
236 );
237​
238 it.effect("opens the sheet only for a focused, secure page with nothing else pending", () =>
239 Effect.gen(function* () {
240 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
241 const notAllowed = { success: false, error: "NotAllowedError" };
242 const publicKey = { challenge: new Uint8Array([1]), rpId: "example.com" };
243​
244 const lan = makeGuest("http://192.168.1.5:3000");
245 passkeys.attachGuest(lan.guest);
246 assert.deepStrictEqual(yield* lan.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
247 // macOS refuses `*.localhost`, so the page hears no rather than a native error.
248 const subdomain = makeGuest("http://app.localhost:3000");
249 passkeys.attachGuest(subdomain.guest);
250 assert.deepStrictEqual(yield* subdomain.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
251​
252 const page = makeGuest();
253 passkeys.attachGuest(page.guest);
254 page.state.focused = false;
255 assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
256 assert.strictEqual(webauthn.getCredential.mock.calls.length, 0);
257​
258 page.state.focused = true;
259 let finish: (value: unknown) => void = () => {};
260 webauthn.getCredential.mockReturnValueOnce(new Promise((resolve) => (finish = resolve)));
261 const first = yield* Effect.forkChild(page.call(PASSKEY_GET_CHANNEL, publicKey));
262 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
263 assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
264​
265 page.mainFrame.origin = "https://other.example";
266 finish({ success: true, data: { credentialId: "AQ" } });
267 assert.deepStrictEqual(yield* Fiber.join(first), notAllowed);
268 }).pipe(Effect.provide(bridgeLayer)),
269 );
270​
271 it.effect("answers the page even when the native ceremony never settles", () =>
272 Effect.gen(function* () {
273 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
274 const { guest, call } = makeGuest();
275 passkeys.attachGuest(guest);
276 webauthn.getCredential.mockReturnValueOnce(new Promise(() => {}));
277 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
278​
279 const pending = yield* Effect.forkChild(
280 call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]), timeout: 1_000 }),
281 );
282 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(6_000));
283​
284 assert.deepStrictEqual(yield* Fiber.join(pending), {
285 success: false,
286 error: "NotAllowedError",
287 });
288 }).pipe(Effect.provide(bridgeLayer)),
289 );
290​
291 it.effect("turns each path on only for builds signed for it", () =>
292 Effect.gen(function* () {
293 const entitled = yield* PreviewPasskeys.PreviewPasskeys.pipe(
294 Effect.provide(
295 layerFor({
296 t3codeWebAuthn: {
297 touchIdKeychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn",
298 browserPasskeys: false,
299 },
300 }),
301 ),
302 );
303 yield* entitled.configure;
304 assert.deepStrictEqual(electron.configureWebAuthn.mock.calls, [
305 [{ touchID: { keychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn" } }],
306 ]);
307 assert.isFalse(entitled.bridgeEnabled);
308 const { guest, handlers } = makeGuest();
309 entitled.attachGuest(guest);
310 assert.strictEqual(handlers.size, 0);
311​
312 const unpackaged = yield* PreviewPasskeys.PreviewPasskeys.pipe(
313 Effect.provide(
314 layerFor(
315 { t3codeWebAuthn: { touchIdKeychainAccessGroup: "X", browserPasskeys: true } },
316 false,
317 ),
318 ),
319 );
320 yield* unpackaged.configure;
321 assert.strictEqual(electron.configureWebAuthn.mock.calls.length, 1);
322 assert.isFalse(unpackaged.bridgeEnabled);
323 }),
324 );
325​
326 it.effect("asks which passkey to use only when a site has several", () =>
327 Effect.gen(function* () {
328 const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
329 const listeners: Array<(...args: ReadonlyArray<unknown>) => void> = [];
330 const session = {
331 on: (_event: string, listener: (...args: ReadonlyArray<unknown>) => void) =>
332 listeners.push(listener),
333 } as unknown as Electron.Session;
334 passkeys.installSessionHandlers(session);
335 passkeys.installSessionHandlers(session);
336 assert.strictEqual(listeners.length, 1);
337​
338 const select = (accounts: ReadonlyArray<Electron.WebAuthnAccount>) =>
339 Effect.promise(
340 () =>
341 new Promise<unknown>((resolve) =>
342 listeners[0]?.(
343 {},
344 { relyingPartyId: "example.com", accounts, frame: null },
345 (credentialId?: string) => resolve(credentialId),
346 ),
347 ),
348 );
349 const alice = { credentialId: "alice", name: "alice@example.com" };
350 const bob = { credentialId: "bob", displayName: "Bob", name: "bob@example.com" };
351​
352 assert.strictEqual(yield* select([alice]), "alice");
353 assert.strictEqual(electron.showMessageBox.mock.calls.length, 0);
354​
355 electron.showMessageBox.mockResolvedValueOnce({ response: 1 });
356 assert.strictEqual(yield* select([alice, bob]), "bob");
357 assert.deepStrictEqual(electron.showMessageBox.mock.calls[0]?.[0]?.buttons, [
358 "alice@example.com",
359 "Bob (bob@example.com)",
360 "Cancel",
361 ]);
362​
363 electron.showMessageBox.mockResolvedValueOnce({ response: 2 });
364 assert.isUndefined(yield* select([alice, bob]));
365 }).pipe(Effect.provide(layerFor({}))),
366 );
367});