Skip to content

Commit a28690b

Browse files
committed
chore(server): sync service updates with main
2 parents 0df12e8 + 82e6ca2 commit a28690b

278 files changed

Lines changed: 7249 additions & 3860 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/desktop/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@
2727
"electron": "44.4.5",
2828
"electron-store": "^8.2.0",
2929
"electron-updater": "^6.8.9",
30+
"electron-webauthn": "catalog:",
3031
"ffi-rs": "1.3.2",
3132
"playwright-core": "1.60.0",
32-
"react-grab": "^0.1.32"
33+
"react-grab": "^0.1.32",
34+
"tldts": "catalog:"
3335
},
3436
"devDependencies": {
3537
"@effect/vitest": "catalog:",

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
1717
import * as DesktopClerk from "./DesktopClerk.ts";
1818
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
1919
import * as DesktopWindow from "../window/DesktopWindow.ts";
20+
import * as PreviewPasskeys from "../preview/Passkeys.ts";
2021
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
2122
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
2223
import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
@@ -276,6 +277,7 @@ const startup = Effect.gen(function* () {
276277
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
277278
const updates = yield* DesktopUpdates.DesktopUpdates;
278279
const environment = yield* DesktopEnvironment.DesktopEnvironment;
280+
const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
279281

280282
yield* shellEnvironment.installIntoProcess;
281283
const hasCommandLinePasswordStore =
@@ -329,6 +331,7 @@ const startup = Effect.gen(function* () {
329331
});
330332
}
331333
yield* appIdentity.configure;
334+
yield* previewPasskeys.configure;
332335
yield* applicationMenu.configure;
333336
yield* updates.configure;
334337
yield* DesktopRemoteUpdates.listen;

‎apps/desktop/src/main.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.
7070
import * as BrowserSession from "./preview/BrowserSession.ts";
7171
import * as DesktopBrowserHost from "./preview/DesktopBrowserHost.ts";
7272
import * as PreviewManager from "./preview/Manager.ts";
73+
import * as PreviewPasskeys from "./preview/Passkeys.ts";
7374
import * as DesktopWindow from "./window/DesktopWindow.ts";
7475
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
7576
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
@@ -168,6 +169,7 @@ const layerDesktopPreview = PreviewManager.layer.pipe(
168169
// service alongside the manager; both sit on the same BrowserSession.
169170
Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
170171
Layer.provideMerge(BrowserSession.layer),
172+
Layer.provideMerge(PreviewPasskeys.layer),
171173
Layer.provideMerge(layerDesktopFoundation),
172174
);
173175

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,10 @@
1+
import { ipcRenderer } from "electron";
2+
3+
import { PASSKEY_BRIDGE_ARGUMENT } from "./preview/GuestProtocol.ts";
4+
import { installPasskeyBridge } from "./preview/PasskeyBridge.ts";
15
import "./preview/PickPreload.ts";
6+
7+
// Electron hands webPreferences.additionalArguments to sandboxed preloads in process.argv.
8+
if (process.argv.includes(PASSKEY_BRIDGE_ARGUMENT)) {
9+
installPasskeyBridge((channel, publicKey) => ipcRenderer.invoke(channel, publicKey));
10+
}

‎apps/desktop/src/preview/GuestProtocol.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,7 @@ export const RECORDING_POINTER_CHANNEL = "preview:recording-pointer";
1111
export const RECORDING_KEY_CHANNEL = "preview:recording-key";
1212
export const RECORDING_INPUT_CHANNEL = "preview:recording-input";
1313
export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller";
14+
export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create";
15+
export const PASSKEY_GET_CHANNEL = "preview:passkey-get";
16+
/** Renderer argument that turns on the guest passkey bridge; see Passkeys.ts. */
17+
export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge";

‎apps/desktop/src/preview/Manager.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
2929
import * as BrowserSession from "./BrowserSession.ts";
3030
import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
3131
import * as PreviewManager from "./Manager.ts";
32+
import * as PreviewPasskeys from "./Passkeys.ts";
3233

3334
describe("fitPictureInPictureContentSize", () => {
3435
it("preserves the PiP content area across aspect-ratio changes", () => {
@@ -301,6 +302,13 @@ const managerLayer = (platform: NodeJS.Platform = "darwin") =>
301302
),
302303
Layer.provideMerge(DesktopBrowserHost.layer),
303304
Layer.provideMerge(layerBrowserSession),
305+
Layer.provideMerge(
306+
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
307+
bridgeEnabled: false,
308+
installSessionHandlers: () => {},
309+
attachGuest: () => () => {},
310+
}),
311+
),
304312
Layer.provideMerge(layerEnvironment),
305313
Layer.provideMerge(layerFileSystem),
306314
Layer.provideMerge(Path.layer),

‎apps/desktop/src/preview/Manager.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
6464
import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
6565
import { MENU_ACTION_CHANNEL, PREVIEW_PICTURE_IN_PICTURE_FRAME_CHANNEL } from "../ipc/channels.ts";
6666
import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
67+
import * as PreviewPasskeys from "./Passkeys.ts";
6768
import * as BrowserSession from "./BrowserSession.ts";
6869
import {
6970
ANNOTATION_CAPTURED_CHANNEL,
@@ -548,6 +549,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
548549
const crypto = yield* Crypto.Crypto;
549550
const parentScope = yield* Scope.Scope;
550551
const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
552+
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
551553
const context = yield* Effect.context<never>();
552554
const runFork = Effect.runForkWith(context);
553555
const resolvedArtifactDirectory = path.resolve(artifactDirectory);
@@ -1254,6 +1256,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
12541256
) {
12551257
const scope = yield* Scope.fork(parentScope, "sequential");
12561258
const attachmentId = Symbol();
1259+
let detachPasskeys = () => {};
12571260
let documentId = 0;
12581261
let nextRequestId = 0;
12591262
let activeCapture: {
@@ -1589,6 +1592,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
15891592
wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput);
15901593
wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput);
15911594
wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
1595+
detachPasskeys();
15921596
}).pipe(Effect.ignore),
15931597
);
15941598
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
@@ -1609,6 +1613,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
16091613
wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput);
16101614
wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput);
16111615
wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
1616+
detachPasskeys = passkeys.attachGuest(wc);
16121617
wc.setWindowOpenHandler((details) => {
16131618
const action = previewWindowOpenAction(details);
16141619
if (action === "popup") {
@@ -3686,6 +3691,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
36863691
const environment = yield* DesktopEnvironment.DesktopEnvironment;
36873692
const browserSession = yield* BrowserSession.BrowserSession;
36883693
const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
3694+
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
36893695
const downloadSessions = new WeakSet<Electron.Session>();
36903696
const fileSystem = yield* FileSystem.FileSystem;
36913697
const path = yield* Path.Path;
@@ -3750,6 +3756,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
37503756
),
37513757
);
37523758
placeServerDownloads(session);
3759+
passkeys.installSessionHandlers(session);
37533760
return session;
37543761
},
37553762
),
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Reads the raw `authData` bytes out of a CBOR attestation object
3+
* (`{ fmt, attStmt, authData }`). Returns undefined for anything malformed.
4+
* Only the definite-length encodings authenticators emit are understood.
5+
*/
6+
export const authenticatorDataFromAttestation = (bytes: Uint8Array) => {
7+
let offset = 0;
8+
const readHead = () => {
9+
const initial = bytes[offset++];
10+
if (initial === undefined) return undefined;
11+
const info = initial & 31;
12+
let length = info;
13+
if (info >= 24) {
14+
if (info > 27) return undefined;
15+
const size = 1 << (info - 24);
16+
if (offset + size > bytes.length) return undefined;
17+
length = 0;
18+
for (let index = 0; index < size; index++) length = length * 256 + (bytes[offset++] ?? 0);
19+
}
20+
return { major: initial >> 5, length };
21+
};
22+
const skipValue = (): boolean => {
23+
const head = readHead();
24+
if (!head) return false;
25+
switch (head.major) {
26+
case 2:
27+
case 3:
28+
offset += head.length;
29+
return offset <= bytes.length;
30+
case 4:
31+
for (let index = 0; index < head.length; index++) if (!skipValue()) return false;
32+
return true;
33+
case 5:
34+
for (let index = 0; index < head.length * 2; index++) if (!skipValue()) return false;
35+
return true;
36+
case 6:
37+
return skipValue();
38+
default:
39+
return true;
40+
}
41+
};
42+
43+
const map = readHead();
44+
if (map?.major !== 5) return undefined;
45+
for (let entry = 0; entry < map.length; entry++) {
46+
const key = readHead();
47+
if (key?.major !== 3 || offset + key.length > bytes.length) return undefined;
48+
const name = new TextDecoder().decode(bytes.subarray(offset, offset + key.length));
49+
offset += key.length;
50+
if (name !== "authData") {
51+
if (!skipValue()) return undefined;
52+
continue;
53+
}
54+
const value = readHead();
55+
if (value?.major !== 2 || offset + value.length > bytes.length) return undefined;
56+
return bytes.slice(offset, offset + value.length);
57+
}
58+
return undefined;
59+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
2+
3+
/** What the shared bridge has already checked before a backend runs a ceremony. */
4+
export interface PasskeyCeremonyContext {
5+
/** The committed origin of the frame that asked; never the page's own claim. */
6+
readonly origin: string;
7+
/** The window the system sheet attaches to. */
8+
readonly nativeWindowHandle: Buffer;
9+
}
10+
11+
/**
12+
* One platform's way to create and use passkeys for a preview page. The
13+
* bridge in `Passkeys.ts` owns everything platform-neutral: which frame may
14+
* ask, focus, one ceremony at a time, the deadline, and dropping results for
15+
* a page that navigated away. A backend only talks to the platform.
16+
*/
17+
export interface PasskeyBackend {
18+
readonly create: (
19+
publicKey: PublicKeyCredentialCreationOptions,
20+
context: PasskeyCeremonyContext,
21+
) => Promise<PasskeyCeremonyResult>;
22+
readonly get: (
23+
publicKey: PublicKeyCredentialRequestOptions,
24+
context: PasskeyCeremonyContext,
25+
) => Promise<PasskeyCeremonyResult>;
26+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { getPublicSuffix } from "tldts";
2+
3+
import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
4+
import { authenticatorDataFromAttestation } from "./PasskeyAttestation.ts";
5+
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
6+
7+
const ES256 = -7;
8+
9+
// WebAuthn rejects RP IDs that are public suffixes, private registries
10+
// included, so one github.io site cannot mint passkeys for every other one.
11+
const isPublicSuffix = (domain: string) =>
12+
domain !== "localhost" && getPublicSuffix(domain, { allowPrivateDomains: true }) === domain;
13+
14+
// Loaded only once a ceremony runs: the module and its native addon ship on macOS alone.
15+
const nativeOptions = async (context: PasskeyCeremonyContext) => ({
16+
webauthn: await import("electron-webauthn"),
17+
options: {
18+
currentOrigin: context.origin,
19+
topFrameOrigin: context.origin,
20+
nativeWindowHandle: context.nativeWindowHandle,
21+
isPublicSuffix,
22+
},
23+
});
24+
25+
const isBufferSource = (value: unknown): value is BufferSource =>
26+
value instanceof ArrayBuffer || ArrayBuffer.isView(value);
27+
28+
const toBase64Url = (value: BufferSource) =>
29+
Buffer.from(
30+
ArrayBuffer.isView(value)
31+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
32+
: new Uint8Array(value),
33+
).toString("base64url");
34+
35+
/**
36+
* macOS passkeys through AuthenticationServices (`electron-webauthn`): the
37+
* system sheet offers iCloud Keychain, password managers, phones, and security
38+
* keys. Needs Apple's managed browser entitlement in the signed build.
39+
*/
40+
export const macPasskeyBackend: PasskeyBackend = {
41+
create: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
42+
// The native layer only converts P-256 keys and never settles for any
43+
// other algorithm, so ES256 is the only one it may negotiate.
44+
const params: unknown = publicKey.pubKeyCredParams;
45+
if (params !== undefined && !Array.isArray(params))
46+
return { success: false, error: "TypeError" };
47+
const allowsEs256 =
48+
params === undefined ||
49+
params.length === 0 ||
50+
params.some(
51+
(param: unknown) =>
52+
typeof param === "object" && param !== null && "alg" in param && param.alg === ES256,
53+
);
54+
if (!allowsEs256) return { success: false, error: "NotSupportedError" };
55+
const { webauthn, options } = await nativeOptions(context);
56+
const result = await webauthn.createCredential(
57+
{ ...publicKey, pubKeyCredParams: [{ type: "public-key", alg: ES256 }] },
58+
options,
59+
);
60+
if (!result.success) return { success: false, error: result.error };
61+
// The native layer reports parsed authenticator data as JSON and claims
62+
// every credential is a synced platform passkey; neither is reliable.
63+
const authData = authenticatorDataFromAttestation(
64+
Buffer.from(result.data.attestationObject, "base64url"),
65+
);
66+
// Sites verify the new credential from its authenticator data; without it
67+
// the passkey is unusable, so say so now rather than let sign-up fail later.
68+
if (!authData) return { success: false, error: "NotAllowedError" };
69+
return {
70+
success: true,
71+
data: {
72+
...result.data,
73+
authData: Buffer.from(authData).toString("base64url"),
74+
transports: [],
75+
},
76+
};
77+
},
78+
get: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
79+
const { webauthn, options } = await nativeOptions(context);
80+
// WebAuthn defaults the RP ID to the caller's host; the native layer requires it.
81+
const result = await webauthn.getCredential(
82+
{ ...publicKey, rpId: publicKey.rpId ?? new URL(context.origin).hostname },
83+
options,
84+
);
85+
if (!result.success) return { success: false, error: result.error };
86+
// The native layer applies the site's allow list to platform passkeys only,
87+
// so a security key can answer with a credential the site did not ask for.
88+
const allowed = (Array.isArray(publicKey.allowCredentials) ? publicKey.allowCredentials : [])
89+
.filter((credential) => credential?.type === "public-key" && isBufferSource(credential.id))
90+
.map((credential) => toBase64Url(credential.id));
91+
if (allowed.length > 0 && !allowed.includes(result.data.credentialId)) {
92+
return { success: false, error: "NotAllowedError" };
93+
}
94+
return result;
95+
},
96+
};

0 commit comments

Comments
 (0)