feat(desktop): passkeys in the in-app browser on macOS (#16952)
Co-authored-by: Ben Davis <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
24 files changed
+1762
-4
No files matched your search
@@ -27,9 +27,11 @@
|
||||
"electron": "44.4.5",
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.8.9",
|
||||
"electron-webauthn": "catalog:",
|
||||
"ffi-rs": "1.3.2",
|
||||
"playwright-core": "1.60.0",
|
||||
"react-grab": "^0.1.32"
|
||||
"react-grab": "^0.1.32",
|
||||
"tldts": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as PreviewPasskeys from "../preview/Passkeys.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
|
||||
@@ -276,6 +277,7 @@ const startup = Effect.gen(function* () {
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
|
||||
yield* shellEnvironment.installIntoProcess;
|
||||
const hasCommandLinePasswordStore =
|
||||
@@ -329,6 +331,7 @@ const startup = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
yield* appIdentity.configure;
|
||||
yield* previewPasskeys.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen;
|
||||
|
||||
@@ -70,6 +70,7 @@ import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as DesktopBrowserHost from "./preview/DesktopBrowserHost.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PreviewPasskeys from "./preview/Passkeys.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
@@ -168,6 +169,7 @@ const layerDesktopPreview = PreviewManager.layer.pipe(
|
||||
// service alongside the manager; both sit on the same BrowserSession.
|
||||
Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
|
||||
Layer.provideMerge(BrowserSession.layer),
|
||||
Layer.provideMerge(PreviewPasskeys.layer),
|
||||
Layer.provideMerge(layerDesktopFoundation),
|
||||
);
|
||||
|
||||
|
||||
@@ -1 +1,10 @@
|
||||
import { ipcRenderer } from "electron";
|
||||
|
||||
import { PASSKEY_BRIDGE_ARGUMENT } from "./preview/GuestProtocol.ts";
|
||||
import { installPasskeyBridge } from "./preview/PasskeyBridge.ts";
|
||||
import "./preview/PickPreload.ts";
|
||||
|
||||
// Electron hands webPreferences.additionalArguments to sandboxed preloads in process.argv.
|
||||
if (process.argv.includes(PASSKEY_BRIDGE_ARGUMENT)) {
|
||||
installPasskeyBridge((channel, publicKey) => ipcRenderer.invoke(channel, publicKey));
|
||||
}
|
||||
@@ -11,3 +11,7 @@ export const RECORDING_POINTER_CHANNEL = "preview:recording-pointer";
|
||||
export const RECORDING_KEY_CHANNEL = "preview:recording-key";
|
||||
export const RECORDING_INPUT_CHANNEL = "preview:recording-input";
|
||||
export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller";
|
||||
export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create";
|
||||
export const PASSKEY_GET_CHANNEL = "preview:passkey-get";
|
||||
/** Renderer argument that turns on the guest passkey bridge; see Passkeys.ts. */
|
||||
export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge";
|
||||
@@ -29,6 +29,7 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
import * as PreviewPasskeys from "./Passkeys.ts";
|
||||
|
||||
describe("fitPictureInPictureContentSize", () => {
|
||||
it("preserves the PiP content area across aspect-ratio changes", () => {
|
||||
@@ -301,6 +302,13 @@ const managerLayer = (platform: NodeJS.Platform = "darwin") =>
|
||||
),
|
||||
Layer.provideMerge(DesktopBrowserHost.layer),
|
||||
Layer.provideMerge(layerBrowserSession),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
|
||||
bridgeEnabled: false,
|
||||
installSessionHandlers: () => {},
|
||||
attachGuest: () => () => {},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(layerEnvironment),
|
||||
Layer.provideMerge(layerFileSystem),
|
||||
Layer.provideMerge(Path.layer),
|
||||
|
||||
@@ -64,6 +64,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
|
||||
import { MENU_ACTION_CHANNEL, PREVIEW_PICTURE_IN_PICTURE_FRAME_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
|
||||
import * as PreviewPasskeys from "./Passkeys.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
@@ -548,6 +549,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const context = yield* Effect.context<never>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const resolvedArtifactDirectory = path.resolve(artifactDirectory);
|
||||
@@ -1254,6 +1256,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const attachmentId = Symbol();
|
||||
let detachPasskeys = () => {};
|
||||
let documentId = 0;
|
||||
let nextRequestId = 0;
|
||||
let activeCapture: {
|
||||
@@ -1589,6 +1592,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput);
|
||||
wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput);
|
||||
wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
|
||||
detachPasskeys();
|
||||
}).pipe(Effect.ignore),
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
@@ -1609,6 +1613,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput);
|
||||
wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput);
|
||||
wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
|
||||
detachPasskeys = passkeys.attachGuest(wc);
|
||||
wc.setWindowOpenHandler((details) => {
|
||||
const action = previewWindowOpenAction(details);
|
||||
if (action === "popup") {
|
||||
@@ -3686,6 +3691,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const browserSession = yield* BrowserSession.BrowserSession;
|
||||
const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const downloadSessions = new WeakSet<Electron.Session>();
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -3750,6 +3756,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
),
|
||||
);
|
||||
placeServerDownloads(session);
|
||||
passkeys.installSessionHandlers(session);
|
||||
return session;
|
||||
},
|
||||
),
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Reads the raw `authData` bytes out of a CBOR attestation object
|
||||
* (`{ fmt, attStmt, authData }`). Returns undefined for anything malformed.
|
||||
* Only the definite-length encodings authenticators emit are understood.
|
||||
*/
|
||||
export const authenticatorDataFromAttestation = (bytes: Uint8Array) => {
|
||||
let offset = 0;
|
||||
const readHead = () => {
|
||||
const initial = bytes[offset++];
|
||||
if (initial === undefined) return undefined;
|
||||
const info = initial & 31;
|
||||
let length = info;
|
||||
if (info >= 24) {
|
||||
if (info > 27) return undefined;
|
||||
const size = 1 << (info - 24);
|
||||
if (offset + size > bytes.length) return undefined;
|
||||
length = 0;
|
||||
for (let index = 0; index < size; index++) length = length * 256 + (bytes[offset++] ?? 0);
|
||||
}
|
||||
return { major: initial >> 5, length };
|
||||
};
|
||||
const skipValue = (): boolean => {
|
||||
const head = readHead();
|
||||
if (!head) return false;
|
||||
switch (head.major) {
|
||||
case 2:
|
||||
case 3:
|
||||
offset += head.length;
|
||||
return offset <= bytes.length;
|
||||
case 4:
|
||||
for (let index = 0; index < head.length; index++) if (!skipValue()) return false;
|
||||
return true;
|
||||
case 5:
|
||||
for (let index = 0; index < head.length * 2; index++) if (!skipValue()) return false;
|
||||
return true;
|
||||
case 6:
|
||||
return skipValue();
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
const map = readHead();
|
||||
if (map?.major !== 5) return undefined;
|
||||
for (let entry = 0; entry < map.length; entry++) {
|
||||
const key = readHead();
|
||||
if (key?.major !== 3 || offset + key.length > bytes.length) return undefined;
|
||||
const name = new TextDecoder().decode(bytes.subarray(offset, offset + key.length));
|
||||
offset += key.length;
|
||||
if (name !== "authData") {
|
||||
if (!skipValue()) return undefined;
|
||||
continue;
|
||||
}
|
||||
const value = readHead();
|
||||
if (value?.major !== 2 || offset + value.length > bytes.length) return undefined;
|
||||
return bytes.slice(offset, offset + value.length);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
|
||||
|
||||
/** What the shared bridge has already checked before a backend runs a ceremony. */
|
||||
export interface PasskeyCeremonyContext {
|
||||
/** The committed origin of the frame that asked; never the page's own claim. */
|
||||
readonly origin: string;
|
||||
/** The window the system sheet attaches to. */
|
||||
readonly nativeWindowHandle: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* One platform's way to create and use passkeys for a preview page. The
|
||||
* bridge in `Passkeys.ts` owns everything platform-neutral: which frame may
|
||||
* ask, focus, one ceremony at a time, the deadline, and dropping results for
|
||||
* a page that navigated away. A backend only talks to the platform.
|
||||
*/
|
||||
export interface PasskeyBackend {
|
||||
readonly create: (
|
||||
publicKey: PublicKeyCredentialCreationOptions,
|
||||
context: PasskeyCeremonyContext,
|
||||
) => Promise<PasskeyCeremonyResult>;
|
||||
readonly get: (
|
||||
publicKey: PublicKeyCredentialRequestOptions,
|
||||
context: PasskeyCeremonyContext,
|
||||
) => Promise<PasskeyCeremonyResult>;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { getPublicSuffix } from "tldts";
|
||||
|
||||
import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
|
||||
import { authenticatorDataFromAttestation } from "./PasskeyAttestation.ts";
|
||||
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
|
||||
|
||||
const ES256 = -7;
|
||||
|
||||
// WebAuthn rejects RP IDs that are public suffixes, private registries
|
||||
// included, so one github.io site cannot mint passkeys for every other one.
|
||||
const isPublicSuffix = (domain: string) =>
|
||||
domain !== "localhost" && getPublicSuffix(domain, { allowPrivateDomains: true }) === domain;
|
||||
|
||||
// Loaded only once a ceremony runs: the module and its native addon ship on macOS alone.
|
||||
const nativeOptions = async (context: PasskeyCeremonyContext) => ({
|
||||
webauthn: await import("electron-webauthn"),
|
||||
options: {
|
||||
currentOrigin: context.origin,
|
||||
topFrameOrigin: context.origin,
|
||||
nativeWindowHandle: context.nativeWindowHandle,
|
||||
isPublicSuffix,
|
||||
},
|
||||
});
|
||||
|
||||
const isBufferSource = (value: unknown): value is BufferSource =>
|
||||
value instanceof ArrayBuffer || ArrayBuffer.isView(value);
|
||||
|
||||
const toBase64Url = (value: BufferSource) =>
|
||||
Buffer.from(
|
||||
ArrayBuffer.isView(value)
|
||||
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
||||
: new Uint8Array(value),
|
||||
).toString("base64url");
|
||||
|
||||
/**
|
||||
* macOS passkeys through AuthenticationServices (`electron-webauthn`): the
|
||||
* system sheet offers iCloud Keychain, password managers, phones, and security
|
||||
* keys. Needs Apple's managed browser entitlement in the signed build.
|
||||
*/
|
||||
export const macPasskeyBackend: PasskeyBackend = {
|
||||
create: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
|
||||
// The native layer only converts P-256 keys and never settles for any
|
||||
// other algorithm, so ES256 is the only one it may negotiate.
|
||||
const params: unknown = publicKey.pubKeyCredParams;
|
||||
if (params !== undefined && !Array.isArray(params))
|
||||
return { success: false, error: "TypeError" };
|
||||
const allowsEs256 =
|
||||
params === undefined ||
|
||||
params.length === 0 ||
|
||||
params.some(
|
||||
(param: unknown) =>
|
||||
typeof param === "object" && param !== null && "alg" in param && param.alg === ES256,
|
||||
);
|
||||
if (!allowsEs256) return { success: false, error: "NotSupportedError" };
|
||||
const { webauthn, options } = await nativeOptions(context);
|
||||
const result = await webauthn.createCredential(
|
||||
{ ...publicKey, pubKeyCredParams: [{ type: "public-key", alg: ES256 }] },
|
||||
options,
|
||||
);
|
||||
if (!result.success) return { success: false, error: result.error };
|
||||
// The native layer reports parsed authenticator data as JSON and claims
|
||||
// every credential is a synced platform passkey; neither is reliable.
|
||||
const authData = authenticatorDataFromAttestation(
|
||||
Buffer.from(result.data.attestationObject, "base64url"),
|
||||
);
|
||||
// Sites verify the new credential from its authenticator data; without it
|
||||
// the passkey is unusable, so say so now rather than let sign-up fail later.
|
||||
if (!authData) return { success: false, error: "NotAllowedError" };
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
...result.data,
|
||||
authData: Buffer.from(authData).toString("base64url"),
|
||||
transports: [],
|
||||
},
|
||||
};
|
||||
},
|
||||
get: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
|
||||
const { webauthn, options } = await nativeOptions(context);
|
||||
// WebAuthn defaults the RP ID to the caller's host; the native layer requires it.
|
||||
const result = await webauthn.getCredential(
|
||||
{ ...publicKey, rpId: publicKey.rpId ?? new URL(context.origin).hostname },
|
||||
options,
|
||||
);
|
||||
if (!result.success) return { success: false, error: result.error };
|
||||
// The native layer applies the site's allow list to platform passkeys only,
|
||||
// so a security key can answer with a credential the site did not ask for.
|
||||
const allowed = (Array.isArray(publicKey.allowCredentials) ? publicKey.allowCredentials : [])
|
||||
.filter((credential) => credential?.type === "public-key" && isBufferSource(credential.id))
|
||||
.map((credential) => toBase64Url(credential.id));
|
||||
if (allowed.length > 0 && !allowed.includes(result.data.credentialId)) {
|
||||
return { success: false, error: "NotAllowedError" };
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,246 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { afterEach, vi } from "vite-plus/test";
|
||||
|
||||
import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
|
||||
import { installPasskeyBridge } from "./PasskeyBridge.ts";
|
||||
|
||||
const base64Url = (bytes: ReadonlyArray<number>) => Buffer.from(bytes).toString("base64url");
|
||||
const bytesOf = (buffer: ArrayBuffer | null) => (buffer ? [...new Uint8Array(buffer)] : null);
|
||||
|
||||
const assertionData = {
|
||||
credentialId: base64Url([1, 2, 3]),
|
||||
clientDataJSON: base64Url([4]),
|
||||
authenticatorData: base64Url([5]),
|
||||
signature: base64Url([6, 7]),
|
||||
userHandle: base64Url([8]),
|
||||
extensions: { prf: { results: { first: base64Url([9]) } } },
|
||||
};
|
||||
|
||||
const attestationData = {
|
||||
credentialId: base64Url([1, 2, 3]),
|
||||
clientDataJSON: base64Url([4]),
|
||||
attestationObject: base64Url([10]),
|
||||
authData: base64Url([11]),
|
||||
publicKey: base64Url([12]),
|
||||
publicKeyAlgorithm: -7,
|
||||
transports: [],
|
||||
extensions: { credProps: { rk: true } },
|
||||
};
|
||||
|
||||
const creationOptions: PublicKeyCredentialCreationOptions = {
|
||||
challenge: new Uint8Array([1]),
|
||||
rp: { name: "Example" },
|
||||
user: { id: new Uint8Array([2]), name: "alice", displayName: "Alice" },
|
||||
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
|
||||
};
|
||||
|
||||
const illegalInvocation = (): never => {
|
||||
throw new TypeError("Illegal invocation");
|
||||
};
|
||||
|
||||
/**
|
||||
* Installs the bridge over fresh stand-ins for the page's DOM classes. Like
|
||||
* Chromium's, their getters only work on objects the browser created itself.
|
||||
*/
|
||||
const install = (respond: (channel: string) => unknown) => {
|
||||
const nativeCreate = vi.fn(async () => "native-create");
|
||||
const nativeGet = vi.fn(async () => "native-get");
|
||||
class FakeCredentialsContainer {
|
||||
create() {
|
||||
return nativeCreate();
|
||||
}
|
||||
get() {
|
||||
return nativeGet();
|
||||
}
|
||||
}
|
||||
class FakePublicKeyCredential {
|
||||
get id() {
|
||||
return illegalInvocation();
|
||||
}
|
||||
get response() {
|
||||
return illegalInvocation();
|
||||
}
|
||||
}
|
||||
class FakeAttestationResponse {
|
||||
get clientDataJSON() {
|
||||
return illegalInvocation();
|
||||
}
|
||||
}
|
||||
class FakeAssertionResponse {
|
||||
get signature() {
|
||||
return illegalInvocation();
|
||||
}
|
||||
}
|
||||
vi.stubGlobal("CredentialsContainer", FakeCredentialsContainer);
|
||||
vi.stubGlobal("PublicKeyCredential", FakePublicKeyCredential);
|
||||
vi.stubGlobal("AuthenticatorAttestationResponse", FakeAttestationResponse);
|
||||
vi.stubGlobal("AuthenticatorAssertionResponse", FakeAssertionResponse);
|
||||
|
||||
const invoke = vi.fn(async (channel: string, _publicKey: unknown) => respond(channel));
|
||||
installPasskeyBridge(invoke);
|
||||
return {
|
||||
invoke,
|
||||
nativeCreate,
|
||||
nativeGet,
|
||||
credentials: new FakeCredentialsContainer() as unknown as CredentialsContainer,
|
||||
FakePublicKeyCredential,
|
||||
FakeAttestationResponse,
|
||||
FakeAssertionResponse,
|
||||
};
|
||||
};
|
||||
|
||||
describe("installPasskeyBridge", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("serves passkey sign-in through the main process with a credential pages can verify", async () => {
|
||||
const { invoke, credentials, FakePublicKeyCredential, FakeAssertionResponse } = install(() => ({
|
||||
success: true,
|
||||
data: assertionData,
|
||||
}));
|
||||
const challenge = new Uint8Array([0, 1, 2, 3]).subarray(1);
|
||||
|
||||
const credential = (await credentials.get({
|
||||
publicKey: {
|
||||
challenge,
|
||||
rpId: "example.com",
|
||||
allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
|
||||
// Unknown members the page adds must not break IPC cloning.
|
||||
extensions: { onHint: () => {} } as AuthenticationExtensionsClientInputs,
|
||||
},
|
||||
})) as PublicKeyCredential;
|
||||
|
||||
assert.deepStrictEqual(invoke.mock.calls[0], [
|
||||
PASSKEY_GET_CHANNEL,
|
||||
{
|
||||
challenge: new Uint8Array([1, 2, 3]),
|
||||
rpId: "example.com",
|
||||
allowCredentials: [{ type: "public-key", id: new Uint8Array([1, 2, 3]) }],
|
||||
extensions: {},
|
||||
},
|
||||
]);
|
||||
const response = credential.response as AuthenticatorAssertionResponse;
|
||||
assert.instanceOf(credential, FakePublicKeyCredential);
|
||||
assert.instanceOf(response, FakeAssertionResponse);
|
||||
assert.strictEqual(credential.id, assertionData.credentialId);
|
||||
assert.deepStrictEqual(bytesOf(credential.rawId), [1, 2, 3]);
|
||||
assert.deepStrictEqual(bytesOf(response.signature), [6, 7]);
|
||||
assert.deepStrictEqual(bytesOf(response.userHandle), [8]);
|
||||
assert.deepStrictEqual(
|
||||
bytesOf(credential.getClientExtensionResults().prf?.results?.first as ArrayBuffer),
|
||||
[9],
|
||||
);
|
||||
assert.deepStrictEqual(credential.toJSON(), {
|
||||
id: assertionData.credentialId,
|
||||
rawId: assertionData.credentialId,
|
||||
type: "public-key",
|
||||
response: {
|
||||
clientDataJSON: assertionData.clientDataJSON,
|
||||
authenticatorData: assertionData.authenticatorData,
|
||||
signature: assertionData.signature,
|
||||
userHandle: assertionData.userHandle,
|
||||
},
|
||||
clientExtensionResults: { prf: { results: { first: base64Url([9]) } } },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns registrations with their attestation and public key", async () => {
|
||||
const { invoke, credentials, FakeAttestationResponse } = install(() => ({
|
||||
success: true,
|
||||
data: attestationData,
|
||||
}));
|
||||
|
||||
const credential = (await credentials.create({
|
||||
publicKey: creationOptions,
|
||||
})) as PublicKeyCredential;
|
||||
|
||||
assert.strictEqual(invoke.mock.calls[0]?.[0], PASSKEY_CREATE_CHANNEL);
|
||||
const response = credential.response as AuthenticatorAttestationResponse;
|
||||
assert.instanceOf(response, FakeAttestationResponse);
|
||||
assert.isNull(credential.authenticatorAttachment);
|
||||
assert.deepStrictEqual(bytesOf(response.attestationObject), [10]);
|
||||
assert.deepStrictEqual(bytesOf(response.getAuthenticatorData()), [11]);
|
||||
assert.deepStrictEqual(bytesOf(response.getPublicKey()), [12]);
|
||||
assert.strictEqual(response.getPublicKeyAlgorithm(), -7);
|
||||
assert.deepStrictEqual(credential.getClientExtensionResults(), { credProps: { rk: true } });
|
||||
assert.deepStrictEqual(credential.toJSON(), {
|
||||
id: attestationData.credentialId,
|
||||
rawId: attestationData.credentialId,
|
||||
type: "public-key",
|
||||
response: {
|
||||
clientDataJSON: attestationData.clientDataJSON,
|
||||
attestationObject: attestationData.attestationObject,
|
||||
authenticatorData: attestationData.authData,
|
||||
transports: [],
|
||||
publicKey: attestationData.publicKey,
|
||||
publicKeyAlgorithm: -7,
|
||||
},
|
||||
clientExtensionResults: { credProps: { rk: true } },
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves autofill and non-passkey requests to Chromium", async () => {
|
||||
const { invoke, credentials, nativeCreate, nativeGet } = install(() => ({
|
||||
success: true,
|
||||
data: assertionData,
|
||||
}));
|
||||
|
||||
await credentials.get({
|
||||
mediation: "conditional",
|
||||
publicKey: { challenge: new Uint8Array([1]) },
|
||||
});
|
||||
await credentials.get({ password: true } as CredentialRequestOptions);
|
||||
// Conditional create upgrades a password sign-in silently; no modal sheet.
|
||||
const upgrade = { mediation: "conditional", publicKey: creationOptions } as const;
|
||||
await credentials.create(upgrade);
|
||||
await credentials.create({ password: {} } as CredentialCreationOptions);
|
||||
assert.strictEqual(invoke.mock.calls.length, 0);
|
||||
assert.strictEqual(nativeGet.mock.calls.length, 2);
|
||||
assert.strictEqual(nativeCreate.mock.calls.length, 2);
|
||||
assert.isFalse(await PublicKeyCredential.isConditionalMediationAvailable());
|
||||
assert.isTrue(await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable());
|
||||
});
|
||||
|
||||
it("rejects with the WebAuthn error the ceremony ended with", async () => {
|
||||
const { credentials } = install((channel) => ({
|
||||
success: false,
|
||||
error: channel === PASSKEY_CREATE_CHANNEL ? "InvalidStateError" : "TypeError",
|
||||
}));
|
||||
const created = await credentials
|
||||
.create({ publicKey: creationOptions })
|
||||
.catch((error: unknown) => error);
|
||||
assert.instanceOf(created, DOMException);
|
||||
assert.strictEqual((created as DOMException).name, "InvalidStateError");
|
||||
const fetched = await credentials
|
||||
.get({ publicKey: { challenge: new Uint8Array([1]) } })
|
||||
.catch((error: unknown) => error);
|
||||
assert.instanceOf(fetched, TypeError);
|
||||
});
|
||||
|
||||
it("refuses when the main process has no handler for the page", async () => {
|
||||
const { credentials } = install(() => {
|
||||
throw new Error("Error invoking remote method 'preview:passkey-get': No handler registered");
|
||||
});
|
||||
|
||||
const error = await credentials
|
||||
.get({ publicKey: { challenge: new Uint8Array([1]) } })
|
||||
.catch((caught: unknown) => caught);
|
||||
assert.instanceOf(error, DOMException);
|
||||
assert.strictEqual((error as DOMException).name, "NotAllowedError");
|
||||
});
|
||||
|
||||
it("rejects as soon as the page aborts, without waiting on the system sheet", async () => {
|
||||
const { credentials } = install(() => new Promise(() => {}));
|
||||
const controller = new AbortController();
|
||||
|
||||
const pending = credentials
|
||||
.get({ publicKey: { challenge: new Uint8Array([1]) }, signal: controller.signal })
|
||||
.catch((error: unknown) => error);
|
||||
controller.abort();
|
||||
|
||||
const error = await pending;
|
||||
assert.instanceOf(error, DOMException);
|
||||
assert.strictEqual((error as DOMException).name, "AbortError");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import type { CreateCredentialResult, GetCredentialResult } from "electron-webauthn";
|
||||
|
||||
import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
|
||||
|
||||
/** What the main process answers a guest passkey ceremony with. */
|
||||
export type PasskeyCeremonyResult =
|
||||
| Extract<CreateCredentialResult, { success: true }>
|
||||
| Extract<GetCredentialResult, { success: true }>
|
||||
| { readonly success: false; readonly error: string };
|
||||
|
||||
type PasskeyChannel = typeof PASSKEY_CREATE_CHANNEL | typeof PASSKEY_GET_CHANNEL;
|
||||
// Credential Management Level 1 added `mediation` to creation requests.
|
||||
type CreationOptions = CredentialCreationOptions & {
|
||||
readonly mediation?: CredentialMediationRequirement;
|
||||
};
|
||||
type InvokePasskeyCeremony = (channel: PasskeyChannel, publicKey: unknown) => Promise<unknown>;
|
||||
|
||||
const NOT_ALLOWED_MESSAGE =
|
||||
"The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client.";
|
||||
const DOM_EXCEPTION_NAMES = new Set([
|
||||
"AbortError",
|
||||
"InvalidStateError",
|
||||
"NotAllowedError",
|
||||
"NotSupportedError",
|
||||
"SecurityError",
|
||||
]);
|
||||
|
||||
const fromBase64Url = (value: string) => {
|
||||
const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
|
||||
const binary = atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "="));
|
||||
return Uint8Array.from(binary, (character) => character.charCodeAt(0)).buffer;
|
||||
};
|
||||
|
||||
const toBase64Url = (buffer: ArrayBuffer) =>
|
||||
btoa(String.fromCharCode(...new Uint8Array(buffer)))
|
||||
.replaceAll("+", "-")
|
||||
.replaceAll("/", "_")
|
||||
.replace(/=+$/u, "");
|
||||
|
||||
const ceremonyError = (name: string) =>
|
||||
name === "TypeError"
|
||||
? new TypeError("The passkey request options are invalid.")
|
||||
: new DOMException(
|
||||
NOT_ALLOWED_MESSAGE,
|
||||
DOM_EXCEPTION_NAMES.has(name) ? name : "NotAllowedError",
|
||||
);
|
||||
|
||||
/**
|
||||
* Copies request options into plain IPC-cloneable data. Chromium ignores
|
||||
* members it does not know, so functions and other uncloneable values drop out
|
||||
* here instead of failing the whole ceremony.
|
||||
*/
|
||||
const toCloneable = (value: unknown): unknown => {
|
||||
if (value instanceof ArrayBuffer) return value.slice(0);
|
||||
if (ArrayBuffer.isView(value)) {
|
||||
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice();
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(toCloneable);
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).flatMap(([key, member]) =>
|
||||
typeof member === "function" || member === undefined ? [] : [[key, toCloneable(member)]],
|
||||
),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
// The objects below borrow the native prototypes so `instanceof` checks pass.
|
||||
// Their own properties shadow the native getters, which only work on objects
|
||||
// Chromium created itself.
|
||||
const withValues = <T extends object>(target: T, values: Record<string, unknown>) => {
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
Object.defineProperty(target, key, { value, enumerable: true, configurable: true });
|
||||
}
|
||||
return target;
|
||||
};
|
||||
|
||||
const prfOutputs = (prf: {
|
||||
readonly enabled?: boolean;
|
||||
readonly results?: { readonly first?: string; readonly second?: string };
|
||||
}): AuthenticationExtensionsPRFOutputs => {
|
||||
const first = prf.results?.first;
|
||||
const second = prf.results?.second;
|
||||
return {
|
||||
...(prf.enabled === undefined ? {} : { enabled: prf.enabled }),
|
||||
...(first === undefined
|
||||
? {}
|
||||
: {
|
||||
results: {
|
||||
first: fromBase64Url(first),
|
||||
...(second === undefined ? {} : { second: fromBase64Url(second) }),
|
||||
},
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const extensionResultsJson = (results: AuthenticationExtensionsClientOutputs) =>
|
||||
JSON.parse(
|
||||
JSON.stringify(results, (_key, value: unknown) =>
|
||||
value instanceof ArrayBuffer ? toBase64Url(value) : value,
|
||||
),
|
||||
) as unknown;
|
||||
|
||||
const makeCredential = (input: {
|
||||
readonly id: string;
|
||||
readonly authenticatorAttachment: AuthenticatorAttachment | null;
|
||||
readonly response: AuthenticatorResponse;
|
||||
readonly responseJson: Record<string, unknown>;
|
||||
readonly extensionResults: AuthenticationExtensionsClientOutputs;
|
||||
}) =>
|
||||
withValues(Object.create(PublicKeyCredential.prototype) as PublicKeyCredential, {
|
||||
id: input.id,
|
||||
rawId: fromBase64Url(input.id),
|
||||
type: "public-key",
|
||||
authenticatorAttachment: input.authenticatorAttachment,
|
||||
response: input.response,
|
||||
getClientExtensionResults: () => input.extensionResults,
|
||||
toJSON: () => ({
|
||||
id: input.id,
|
||||
rawId: input.id,
|
||||
type: "public-key",
|
||||
...(input.authenticatorAttachment === null
|
||||
? {}
|
||||
: { authenticatorAttachment: input.authenticatorAttachment }),
|
||||
response: input.responseJson,
|
||||
clientExtensionResults: extensionResultsJson(input.extensionResults),
|
||||
}),
|
||||
});
|
||||
|
||||
const credentialFromCreateResult = (
|
||||
data: Extract<CreateCredentialResult, { success: true }>["data"],
|
||||
) => {
|
||||
const transports = [...data.transports];
|
||||
const publicKey = data.publicKey.length > 0 ? data.publicKey : null;
|
||||
const extensionResults: AuthenticationExtensionsClientOutputs = {
|
||||
...(data.extensions.credProps ? { credProps: { ...data.extensions.credProps } } : {}),
|
||||
...(data.extensions.prf ? { prf: prfOutputs(data.extensions.prf) } : {}),
|
||||
...(data.extensions.largeBlob ? { largeBlob: { ...data.extensions.largeBlob } } : {}),
|
||||
};
|
||||
return makeCredential({
|
||||
id: data.credentialId,
|
||||
// The native layer cannot tell a synced passkey from a security key.
|
||||
authenticatorAttachment: null,
|
||||
response: withValues(
|
||||
Object.create(AuthenticatorAttestationResponse.prototype) as AuthenticatorAttestationResponse,
|
||||
{
|
||||
clientDataJSON: fromBase64Url(data.clientDataJSON),
|
||||
attestationObject: fromBase64Url(data.attestationObject),
|
||||
getTransports: () => [...transports],
|
||||
getAuthenticatorData: () => fromBase64Url(data.authData),
|
||||
getPublicKey: () => (publicKey === null ? null : fromBase64Url(publicKey)),
|
||||
getPublicKeyAlgorithm: () => data.publicKeyAlgorithm,
|
||||
},
|
||||
),
|
||||
responseJson: {
|
||||
clientDataJSON: data.clientDataJSON,
|
||||
attestationObject: data.attestationObject,
|
||||
authenticatorData: data.authData,
|
||||
transports,
|
||||
...(publicKey === null ? {} : { publicKey }),
|
||||
publicKeyAlgorithm: data.publicKeyAlgorithm,
|
||||
},
|
||||
extensionResults,
|
||||
});
|
||||
};
|
||||
|
||||
const credentialFromGetResult = (data: Extract<GetCredentialResult, { success: true }>["data"]) => {
|
||||
const userHandle = data.userHandle.length > 0 ? data.userHandle : null;
|
||||
const { prf, largeBlob } = data.extensions ?? {};
|
||||
const extensionResults: AuthenticationExtensionsClientOutputs = {
|
||||
...(prf ? { prf: prfOutputs(prf) } : {}),
|
||||
...(largeBlob
|
||||
? {
|
||||
largeBlob: {
|
||||
...(largeBlob.blob === undefined ? {} : { blob: fromBase64Url(largeBlob.blob) }),
|
||||
...(largeBlob.written === undefined ? {} : { written: largeBlob.written }),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return makeCredential({
|
||||
id: data.credentialId,
|
||||
authenticatorAttachment: null,
|
||||
response: withValues(
|
||||
Object.create(AuthenticatorAssertionResponse.prototype) as AuthenticatorAssertionResponse,
|
||||
{
|
||||
clientDataJSON: fromBase64Url(data.clientDataJSON),
|
||||
authenticatorData: fromBase64Url(data.authenticatorData),
|
||||
signature: fromBase64Url(data.signature),
|
||||
userHandle: userHandle === null ? null : fromBase64Url(userHandle),
|
||||
},
|
||||
),
|
||||
responseJson: {
|
||||
clientDataJSON: data.clientDataJSON,
|
||||
authenticatorData: data.authenticatorData,
|
||||
signature: data.signature,
|
||||
...(userHandle === null ? {} : { userHandle }),
|
||||
},
|
||||
extensionResults,
|
||||
});
|
||||
};
|
||||
|
||||
const abortReason = (signal: AbortSignal) =>
|
||||
signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
||||
|
||||
/**
|
||||
* Routes this page's WebAuthn ceremonies to the system passkey sheet through
|
||||
* the main process, which supplies the frame's real origin. Runs in the page's
|
||||
* own world (the preview preload has contextIsolation off), before any page
|
||||
* script. Conditional (autofill and automatic upgrade) requests stay native:
|
||||
* the system sheet is modal and must not open on its own.
|
||||
*/
|
||||
export function installPasskeyBridge(invoke: InvokePasskeyCeremony) {
|
||||
// Insecure contexts have no WebAuthn to bridge.
|
||||
if (typeof CredentialsContainer === "undefined" || typeof PublicKeyCredential === "undefined") {
|
||||
return;
|
||||
}
|
||||
const run = async (
|
||||
channel: PasskeyChannel,
|
||||
publicKey: unknown,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<PublicKeyCredential> => {
|
||||
if (signal?.aborted) throw abortReason(signal);
|
||||
const ceremony = invoke(channel, toCloneable(publicKey)).then(
|
||||
(value) => {
|
||||
const result = value as PasskeyCeremonyResult;
|
||||
if (!result.success) throw ceremonyError(result.error);
|
||||
return "attestationObject" in result.data
|
||||
? credentialFromCreateResult(result.data)
|
||||
: credentialFromGetResult(result.data);
|
||||
},
|
||||
// No handler yet (or any more) for this guest: answer like a refusal.
|
||||
(error: unknown) => {
|
||||
throw error instanceof DOMException || error instanceof TypeError
|
||||
? error
|
||||
: ceremonyError("NotAllowedError");
|
||||
},
|
||||
);
|
||||
if (!signal) return ceremony;
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => reject(abortReason(signal));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
ceremony.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
||||
});
|
||||
};
|
||||
|
||||
const container = CredentialsContainer.prototype;
|
||||
const nativeCreate = container.create;
|
||||
const nativeGet = container.get;
|
||||
const define = (target: object, key: string, value: unknown) =>
|
||||
Object.defineProperty(target, key, { value, configurable: true, writable: true });
|
||||
|
||||
define(
|
||||
container,
|
||||
"create",
|
||||
function create(this: CredentialsContainer, options?: CreationOptions) {
|
||||
return options?.publicKey && options.mediation !== "conditional"
|
||||
? run(PASSKEY_CREATE_CHANNEL, options.publicKey, options.signal)
|
||||
: Reflect.apply(nativeCreate, this, [options]);
|
||||
},
|
||||
);
|
||||
define(
|
||||
container,
|
||||
"get",
|
||||
function get(this: CredentialsContainer, options?: CredentialRequestOptions) {
|
||||
return options?.publicKey && options.mediation !== "conditional"
|
||||
? run(PASSKEY_GET_CHANNEL, options.publicKey, options.signal)
|
||||
: Reflect.apply(nativeGet, this, [options]);
|
||||
},
|
||||
);
|
||||
|
||||
define(PublicKeyCredential, "isUserVerifyingPlatformAuthenticatorAvailable", async () => true);
|
||||
define(PublicKeyCredential, "isConditionalMediationAvailable", async () => false);
|
||||
const nativeCapabilities = PublicKeyCredential.getClientCapabilities;
|
||||
if (typeof nativeCapabilities === "function") {
|
||||
define(PublicKeyCredential, "getClientCapabilities", async () => ({
|
||||
...(await Reflect.apply(nativeCapabilities, PublicKeyCredential, [])),
|
||||
conditionalCreate: false,
|
||||
conditionalGet: false,
|
||||
hybridTransport: true,
|
||||
passkeyPlatformAuthenticator: true,
|
||||
userVerifyingPlatformAuthenticator: true,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { afterEach, beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const electron = vi.hoisted(() => ({
|
||||
configureWebAuthn: vi.fn(),
|
||||
showMessageBox: vi.fn(),
|
||||
fromWebContents: vi.fn(),
|
||||
}));
|
||||
const webauthn = vi.hoisted(() => ({ createCredential: vi.fn(), getCredential: vi.fn() }));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { configureWebAuthn: electron.configureWebAuthn },
|
||||
dialog: { showMessageBox: electron.showMessageBox },
|
||||
BrowserWindow: { fromWebContents: electron.fromWebContents },
|
||||
webContents: { fromFrame: () => undefined },
|
||||
}));
|
||||
vi.mock("electron-webauthn", () => webauthn);
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
|
||||
import * as PreviewPasskeys from "./Passkeys.ts";
|
||||
|
||||
const layerFor = (packageJson: object, isPackaged = true) =>
|
||||
PreviewPasskeys.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
DesktopEnvironment.DesktopEnvironment,
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "darwin",
|
||||
isPackaged,
|
||||
appRoot: "/app",
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
} as DesktopEnvironment.DesktopEnvironment["Service"]),
|
||||
),
|
||||
),
|
||||
Layer.provide(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.succeed(JSON.stringify(packageJson)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
type Handler = (event: { readonly senderFrame: object | null }, publicKey: unknown) => unknown;
|
||||
|
||||
const makeGuest = (origin = "https://accounts.example.com") => {
|
||||
const handlers = new Map<string, Handler>();
|
||||
const state = { focused: true };
|
||||
const mainFrame = { origin, isDestroyed: () => false };
|
||||
const guest = {
|
||||
mainFrame,
|
||||
hostWebContents: {},
|
||||
isFocused: () => state.focused,
|
||||
ipc: {
|
||||
handle: (channel: string, handler: Handler) => handlers.set(channel, handler),
|
||||
removeHandler: (channel: string) => handlers.delete(channel),
|
||||
},
|
||||
};
|
||||
const call = (channel: string, publicKey: unknown, senderFrame: object | null = mainFrame) =>
|
||||
Effect.promise(async () => handlers.get(channel)?.({ senderFrame }, publicKey));
|
||||
return { guest: guest as unknown as Electron.WebContents, mainFrame, handlers, state, call };
|
||||
};
|
||||
|
||||
const bridgeLayer = layerFor({ t3codeWebAuthn: { browserPasskeys: true } });
|
||||
|
||||
/** CBOR `{ fmt: "packed", attStmt: { alg: -7, sig }, authData }`, as authenticators encode it. */
|
||||
const attestationObject = (authData: ReadonlyArray<number>) => {
|
||||
const text = (value: string) => [0x60 + value.length, ...Buffer.from(value)];
|
||||
const bytes = (value: ReadonlyArray<number>) => [0x58, value.length, ...value];
|
||||
return Buffer.from([
|
||||
0xa3,
|
||||
...text("fmt"),
|
||||
...text("packed"),
|
||||
...text("attStmt"),
|
||||
0xa2,
|
||||
...text("alg"),
|
||||
0x26,
|
||||
...text("sig"),
|
||||
...bytes(Array.from({ length: 70 }, () => 7)),
|
||||
...text("authData"),
|
||||
...bytes(authData),
|
||||
]).toString("base64url");
|
||||
};
|
||||
|
||||
describe("PreviewPasskeys", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
electron.fromWebContents.mockReturnValue({
|
||||
isDestroyed: () => false,
|
||||
getNativeWindowHandle: () => Buffer.from([1]),
|
||||
});
|
||||
});
|
||||
// Restored here so a failing fake-timer test cannot leak fake timers into the next one.
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it.effect("pins each guest ceremony to the origin of the frame that asked", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const { guest, handlers, call } = makeGuest();
|
||||
webauthn.getCredential.mockResolvedValue({
|
||||
success: false,
|
||||
error: "NotAllowedError",
|
||||
errorObject: new Error("native detail"),
|
||||
});
|
||||
|
||||
const detach = passkeys.attachGuest(guest);
|
||||
const publicKey = { challenge: new Uint8Array([1]), rpId: "example.com" };
|
||||
const result = yield* call(PASSKEY_GET_CHANNEL, publicKey);
|
||||
|
||||
assert.deepStrictEqual(result, { success: false, error: "NotAllowedError" });
|
||||
const [sentPublicKey, options] = webauthn.getCredential.mock.calls[0] ?? [];
|
||||
assert.deepStrictEqual(sentPublicKey, publicKey);
|
||||
assert.strictEqual(options.currentOrigin, "https://accounts.example.com");
|
||||
assert.strictEqual(options.topFrameOrigin, "https://accounts.example.com");
|
||||
assert.isTrue(options.isPublicSuffix("com"));
|
||||
assert.isTrue(options.isPublicSuffix("github.io"));
|
||||
assert.isFalse(options.isPublicSuffix("example.com"));
|
||||
assert.isFalse(options.isPublicSuffix("localhost"));
|
||||
|
||||
// WebAuthn defaults the RP ID to the caller's own host.
|
||||
yield* call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]) });
|
||||
assert.strictEqual(webauthn.getCredential.mock.calls[1]?.[0].rpId, "accounts.example.com");
|
||||
|
||||
// Only the main frame runs the preload; anything else is not the page.
|
||||
const forged = yield* call(PASSKEY_CREATE_CHANNEL, publicKey, {
|
||||
origin: "https://evil.example",
|
||||
});
|
||||
assert.deepStrictEqual(forged, { success: false, error: "NotAllowedError" });
|
||||
assert.strictEqual(webauthn.createCredential.mock.calls.length, 0);
|
||||
|
||||
detach();
|
||||
assert.strictEqual(handlers.size, 0);
|
||||
}).pipe(Effect.provide(bridgeLayer)),
|
||||
);
|
||||
|
||||
it.effect("registers ES256 keys only and reports their real authenticator data", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const { guest, call } = makeGuest();
|
||||
passkeys.attachGuest(guest);
|
||||
webauthn.createCredential.mockResolvedValue({
|
||||
success: true,
|
||||
data: {
|
||||
credentialId: "AQ",
|
||||
clientDataJSON: "Ag",
|
||||
attestationObject: attestationObject([1, 2, 3, 4]),
|
||||
authData: Buffer.from('{"parsed":true}').toString("base64url"),
|
||||
publicKey: "BQ",
|
||||
publicKeyAlgorithm: -7,
|
||||
transports: ["hybrid", "internal"],
|
||||
extensions: {},
|
||||
},
|
||||
});
|
||||
const publicKey = {
|
||||
challenge: new Uint8Array([1]),
|
||||
pubKeyCredParams: [
|
||||
{ type: "public-key", alg: -8 },
|
||||
{ type: "public-key", alg: -7 },
|
||||
{ type: "public-key", alg: -257 },
|
||||
],
|
||||
};
|
||||
|
||||
const result = yield* call(PASSKEY_CREATE_CHANNEL, publicKey);
|
||||
|
||||
assert.deepStrictEqual(webauthn.createCredential.mock.calls[0]?.[0].pubKeyCredParams, [
|
||||
{ type: "public-key", alg: -7 },
|
||||
]);
|
||||
assert.deepInclude(result, { success: true });
|
||||
const data = (result as { readonly data: Record<string, unknown> }).data;
|
||||
assert.strictEqual(data.authData, Buffer.from([1, 2, 3, 4]).toString("base64url"));
|
||||
assert.deepStrictEqual(data.transports, []);
|
||||
|
||||
const unsupported = yield* call(PASSKEY_CREATE_CHANNEL, {
|
||||
...publicKey,
|
||||
pubKeyCredParams: [{ type: "public-key", alg: -8 }],
|
||||
});
|
||||
assert.deepStrictEqual(unsupported, { success: false, error: "NotSupportedError" });
|
||||
assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
|
||||
|
||||
// A malformed algorithm list is the page's error, not a cue to pick ES256.
|
||||
const malformed = yield* call(PASSKEY_CREATE_CHANNEL, {
|
||||
...publicKey,
|
||||
pubKeyCredParams: { type: "public-key", alg: -7 },
|
||||
});
|
||||
assert.deepStrictEqual(malformed, { success: false, error: "TypeError" });
|
||||
assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
|
||||
|
||||
// Without authenticator data the site cannot verify the passkey.
|
||||
webauthn.createCredential.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { credentialId: "AQ", attestationObject: Buffer.from([0x00]).toString("base64url") },
|
||||
});
|
||||
assert.deepStrictEqual(yield* call(PASSKEY_CREATE_CHANNEL, publicKey), {
|
||||
success: false,
|
||||
error: "NotAllowedError",
|
||||
});
|
||||
}).pipe(Effect.provide(bridgeLayer)),
|
||||
);
|
||||
|
||||
it.effect("answers only with a credential the site allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const { guest, call } = makeGuest();
|
||||
passkeys.attachGuest(guest);
|
||||
const assertion = (credentialId: string) => ({
|
||||
success: true,
|
||||
data: {
|
||||
credentialId,
|
||||
clientDataJSON: "Ag",
|
||||
authenticatorData: "Aw",
|
||||
signature: "BA",
|
||||
userHandle: "BQ",
|
||||
},
|
||||
});
|
||||
const publicKey = {
|
||||
challenge: new Uint8Array([1]),
|
||||
rpId: "example.com",
|
||||
allowCredentials: [{ type: "public-key", id: new Uint8Array([1]) }],
|
||||
};
|
||||
|
||||
// macOS applies the allow list to passkeys but not to security keys.
|
||||
webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
|
||||
const other = yield* call(PASSKEY_GET_CHANNEL, publicKey);
|
||||
assert.deepStrictEqual(other, { success: false, error: "NotAllowedError" });
|
||||
|
||||
webauthn.getCredential.mockResolvedValueOnce(assertion("AQ"));
|
||||
assert.deepInclude(yield* call(PASSKEY_GET_CHANNEL, publicKey), { success: true });
|
||||
|
||||
// With no allow list, any of the site's credentials will do.
|
||||
webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
|
||||
const discoverable = yield* call(PASSKEY_GET_CHANNEL, {
|
||||
challenge: new Uint8Array([1]),
|
||||
rpId: "example.com",
|
||||
});
|
||||
assert.deepInclude(discoverable, { success: true });
|
||||
}).pipe(Effect.provide(bridgeLayer)),
|
||||
);
|
||||
|
||||
it.effect("opens the sheet only for a focused, secure page with nothing else pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const notAllowed = { success: false, error: "NotAllowedError" };
|
||||
const publicKey = { challenge: new Uint8Array([1]), rpId: "example.com" };
|
||||
|
||||
const lan = makeGuest("http://192.168.1.5:3000");
|
||||
passkeys.attachGuest(lan.guest);
|
||||
assert.deepStrictEqual(yield* lan.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
|
||||
// macOS refuses `*.localhost`, so the page hears no rather than a native error.
|
||||
const subdomain = makeGuest("http://app.localhost:3000");
|
||||
passkeys.attachGuest(subdomain.guest);
|
||||
assert.deepStrictEqual(yield* subdomain.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
|
||||
|
||||
const page = makeGuest();
|
||||
passkeys.attachGuest(page.guest);
|
||||
page.state.focused = false;
|
||||
assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
|
||||
assert.strictEqual(webauthn.getCredential.mock.calls.length, 0);
|
||||
|
||||
page.state.focused = true;
|
||||
let finish: (value: unknown) => void = () => {};
|
||||
webauthn.getCredential.mockReturnValueOnce(new Promise((resolve) => (finish = resolve)));
|
||||
const first = yield* Effect.forkChild(page.call(PASSKEY_GET_CHANNEL, publicKey));
|
||||
yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
|
||||
assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
|
||||
|
||||
// The page navigated while the sheet was up; its credential goes nowhere.
|
||||
page.mainFrame.origin = "https://other.example";
|
||||
finish({ success: true, data: { credentialId: "AQ" } });
|
||||
assert.deepStrictEqual(yield* Fiber.join(first), notAllowed);
|
||||
}).pipe(Effect.provide(bridgeLayer)),
|
||||
);
|
||||
|
||||
it.effect("answers the page even when the native ceremony never settles", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const { guest, call } = makeGuest();
|
||||
passkeys.attachGuest(guest);
|
||||
webauthn.getCredential.mockReturnValueOnce(new Promise(() => {}));
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
|
||||
const pending = yield* Effect.forkChild(
|
||||
call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]), timeout: 1_000 }),
|
||||
);
|
||||
yield* Effect.promise(() => vi.advanceTimersByTimeAsync(6_000));
|
||||
|
||||
assert.deepStrictEqual(yield* Fiber.join(pending), {
|
||||
success: false,
|
||||
error: "NotAllowedError",
|
||||
});
|
||||
}).pipe(Effect.provide(bridgeLayer)),
|
||||
);
|
||||
|
||||
it.effect("turns each path on only for builds signed for it", () =>
|
||||
Effect.gen(function* () {
|
||||
const entitled = yield* PreviewPasskeys.PreviewPasskeys.pipe(
|
||||
Effect.provide(
|
||||
layerFor({
|
||||
t3codeWebAuthn: {
|
||||
touchIdKeychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn",
|
||||
browserPasskeys: false,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* entitled.configure;
|
||||
assert.deepStrictEqual(electron.configureWebAuthn.mock.calls, [
|
||||
[{ touchID: { keychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn" } }],
|
||||
]);
|
||||
assert.isFalse(entitled.bridgeEnabled);
|
||||
const { guest, handlers } = makeGuest();
|
||||
entitled.attachGuest(guest);
|
||||
assert.strictEqual(handlers.size, 0);
|
||||
|
||||
const unpackaged = yield* PreviewPasskeys.PreviewPasskeys.pipe(
|
||||
Effect.provide(
|
||||
layerFor(
|
||||
{ t3codeWebAuthn: { touchIdKeychainAccessGroup: "X", browserPasskeys: true } },
|
||||
false,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* unpackaged.configure;
|
||||
assert.strictEqual(electron.configureWebAuthn.mock.calls.length, 1);
|
||||
assert.isFalse(unpackaged.bridgeEnabled);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks which passkey to use only when a site has several", () =>
|
||||
Effect.gen(function* () {
|
||||
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const listeners: Array<(...args: ReadonlyArray<unknown>) => void> = [];
|
||||
const session = {
|
||||
on: (_event: string, listener: (...args: ReadonlyArray<unknown>) => void) =>
|
||||
listeners.push(listener),
|
||||
} as unknown as Electron.Session;
|
||||
passkeys.installSessionHandlers(session);
|
||||
passkeys.installSessionHandlers(session);
|
||||
assert.strictEqual(listeners.length, 1);
|
||||
|
||||
const select = (accounts: ReadonlyArray<Electron.WebAuthnAccount>) =>
|
||||
Effect.promise(
|
||||
() =>
|
||||
new Promise<unknown>((resolve) =>
|
||||
listeners[0]?.(
|
||||
{},
|
||||
{ relyingPartyId: "example.com", accounts, frame: null },
|
||||
(credentialId?: string) => resolve(credentialId),
|
||||
),
|
||||
),
|
||||
);
|
||||
const alice = { credentialId: "alice", name: "[email protected]" };
|
||||
const bob = { credentialId: "bob", displayName: "Bob", name: "[email protected]" };
|
||||
|
||||
assert.strictEqual(yield* select([alice]), "alice");
|
||||
assert.strictEqual(electron.showMessageBox.mock.calls.length, 0);
|
||||
|
||||
electron.showMessageBox.mockResolvedValueOnce({ response: 1 });
|
||||
assert.strictEqual(yield* select([alice, bob]), "bob");
|
||||
assert.deepStrictEqual(electron.showMessageBox.mock.calls[0]?.[0]?.buttons, [
|
||||
"[email protected]",
|
||||
"Bob ([email protected])",
|
||||
"Cancel",
|
||||
]);
|
||||
|
||||
electron.showMessageBox.mockResolvedValueOnce({ response: 2 });
|
||||
assert.isUndefined(yield* select([alice, bob]));
|
||||
}).pipe(Effect.provide(layerFor({}))),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
// @effect-diagnostics globalTimers:off - Ceremonies settle inside IPC handlers, outside an Effect runtime.
|
||||
import type { IpcMainInvokeEvent, Session, WebContents, WebFrameMain } from "electron";
|
||||
import { app, BrowserWindow, dialog, webContents as electronWebContents } from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
|
||||
import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
|
||||
import { macPasskeyBackend } from "./PasskeyBackendMac.ts";
|
||||
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
|
||||
|
||||
const PasskeyPackageMetadata = Schema.Struct({
|
||||
t3codeWebAuthn: Schema.optional(
|
||||
Schema.Struct({
|
||||
touchIdKeychainAccessGroup: Schema.optional(Schema.String),
|
||||
browserPasskeys: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const decodePasskeyPackageMetadata = Schema.decodeEffect(
|
||||
Schema.fromJsonString(PasskeyPackageMetadata),
|
||||
);
|
||||
|
||||
export class PreviewPasskeysConfigureError extends Schema.TaggedError<PreviewPasskeysConfigureError>()(
|
||||
"PreviewPasskeysConfigureError",
|
||||
{
|
||||
keychainAccessGroup: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to enable Touch ID passkeys for the in-app browser (keychain group ${this.keychainAccessGroup}).`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Passkeys for in-app browser pages on macOS, where Electron has no WebAuthn UI
|
||||
* of its own. Signed builds record which entitlements their provisioning
|
||||
* profile granted (scripts/build-desktop-artifact.ts), and each path turns on
|
||||
* only when its entitlement is present:
|
||||
*
|
||||
* - Touch ID: Electron's built-in platform authenticator. Passkeys it creates
|
||||
* stay on this Mac, in T3 Code's keychain group.
|
||||
* - Browser passkeys: Apple's managed browser entitlement lets the system sheet
|
||||
* (iCloud Keychain, password managers, phones, security keys) serve any
|
||||
* site. The guest preload hands each ceremony to this process, which pins
|
||||
* the requesting frame's real origin.
|
||||
*
|
||||
* Windows needs neither: Chromium already uses Windows Hello there.
|
||||
*/
|
||||
export class PreviewPasskeys extends Context.Service<
|
||||
PreviewPasskeys,
|
||||
{
|
||||
/** Whether preview pages route WebAuthn through the system passkey sheet. */
|
||||
readonly bridgeEnabled: boolean;
|
||||
/** Turns on Touch ID passkeys when this build is entitled to them. Runs after app ready. */
|
||||
readonly configure: Effect.Effect<void>;
|
||||
/** Lets the user choose between several passkeys for one site. Idempotent. */
|
||||
readonly installSessionHandlers: (session: Session) => void;
|
||||
/** Serves a preview guest's passkey ceremonies. Returns the detach function. */
|
||||
readonly attachGuest: (guest: WebContents) => () => void;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/Passkeys/PreviewPasskeys") {}
|
||||
|
||||
const notAllowed: PasskeyCeremonyResult = { success: false, error: "NotAllowedError" };
|
||||
|
||||
const accountLabel = (account: Electron.WebAuthnAccount) =>
|
||||
account.displayName && account.name && account.displayName !== account.name
|
||||
? `${account.displayName} (${account.name})`
|
||||
: (account.name ?? account.displayName ?? "Unnamed passkey");
|
||||
|
||||
const ownerWindow = (frame: WebFrameMain | null) => {
|
||||
const contents = frame ? electronWebContents.fromFrame(frame) : undefined;
|
||||
const owner = contents?.hostWebContents ?? contents;
|
||||
return owner ? BrowserWindow.fromWebContents(owner) : null;
|
||||
};
|
||||
|
||||
const chooseAccount = async (details: Electron.SelectWebauthnAccountDetails) => {
|
||||
const [onlyAccount] = details.accounts;
|
||||
// The Touch ID prompt that follows already asks the user to confirm.
|
||||
if (details.accounts.length === 1) return onlyAccount?.credentialId;
|
||||
const options: Electron.MessageBoxOptions = {
|
||||
type: "none",
|
||||
message: "Choose a passkey",
|
||||
detail: details.relyingPartyId,
|
||||
buttons: [...details.accounts.map(accountLabel), "Cancel"],
|
||||
cancelId: details.accounts.length,
|
||||
defaultId: 0,
|
||||
noLink: true,
|
||||
};
|
||||
const parent = ownerWindow(details.frame);
|
||||
const { response } = parent
|
||||
? await dialog.showMessageBox(parent, options)
|
||||
: await dialog.showMessageBox(options);
|
||||
return details.accounts[response]?.credentialId;
|
||||
};
|
||||
|
||||
const NATIVE_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
const NATIVE_MAX_TIMEOUT_MS = 60 * 60 * 1000;
|
||||
|
||||
// Mirrors the native layer's own clamp, plus a margin: it can leave a ceremony
|
||||
// unsettled, and the page must still get an answer.
|
||||
const ceremonyDeadline = (timeout: unknown) =>
|
||||
(typeof timeout === "number" && timeout > 0
|
||||
? Math.min(timeout, NATIVE_MAX_TIMEOUT_MS)
|
||||
: NATIVE_DEFAULT_TIMEOUT_MS) + 5_000;
|
||||
|
||||
const withDeadline = (ceremony: Promise<PasskeyCeremonyResult>, milliseconds: number) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const deadline = new Promise<PasskeyCeremonyResult>((resolve) => {
|
||||
timer = setTimeout(() => resolve(notAllowed), milliseconds);
|
||||
});
|
||||
return Promise.race([ceremony, deadline]).finally(() => clearTimeout(timer));
|
||||
};
|
||||
|
||||
// Secure contexts only: https, or http on this machine. Chromium also trusts
|
||||
// `*.localhost`, but the macOS layer refuses it, so it is turned away here
|
||||
// instead of failing deeper with a less useful error.
|
||||
const isTrustworthyOrigin = (origin: string) => {
|
||||
if (!URL.canParse(origin)) return false;
|
||||
const { protocol, hostname } = new URL(origin);
|
||||
return (
|
||||
protocol === "https:" ||
|
||||
(protocol === "http:" &&
|
||||
(hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]"))
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The platform that serves preview pages' passkey ceremonies, or none. Windows
|
||||
* needs none: Chromium already hands WebAuthn to Windows Hello there.
|
||||
*/
|
||||
const backendFor = (platform: NodeJS.Platform): PasskeyBackend | undefined =>
|
||||
platform === "darwin" ? macPasskeyBackend : undefined;
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const metadata =
|
||||
environment.platform === "darwin" && environment.isPackaged
|
||||
? yield* fileSystem
|
||||
.readFileString(environment.path.join(environment.appRoot, "package.json"))
|
||||
.pipe(
|
||||
Effect.flatMap(decodePasskeyPackageMetadata),
|
||||
Effect.map((parsed) => parsed.t3codeWebAuthn),
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
)
|
||||
: undefined;
|
||||
const keychainAccessGroup = metadata?.touchIdKeychainAccessGroup;
|
||||
const backend = metadata?.browserPasskeys === true ? backendFor(environment.platform) : undefined;
|
||||
const bridgeEnabled = backend !== undefined;
|
||||
const sessionsWithHandlers = new WeakSet<Session>();
|
||||
|
||||
return PreviewPasskeys.of({
|
||||
bridgeEnabled,
|
||||
configure: Effect.gen(function* () {
|
||||
if (keychainAccessGroup === undefined) return;
|
||||
yield* Effect.try({
|
||||
try: () => app.configureWebAuthn({ touchID: { keychainAccessGroup } }),
|
||||
catch: (cause) => new PreviewPasskeysConfigureError({ keychainAccessGroup, cause }),
|
||||
}).pipe(Effect.catch((error) => Effect.logWarning(error.message, { cause: error.cause })));
|
||||
}).pipe(Effect.withSpan("desktop.previewPasskeys.configure")),
|
||||
installSessionHandlers: (session) => {
|
||||
if (sessionsWithHandlers.has(session)) return;
|
||||
sessionsWithHandlers.add(session);
|
||||
session.on("select-webauthn-account", (_event, details, callback) => {
|
||||
// The request stays pending until the callback runs, so it must run once.
|
||||
void chooseAccount(details).then(
|
||||
(credentialId) => callback(credentialId),
|
||||
() => callback(),
|
||||
);
|
||||
});
|
||||
},
|
||||
attachGuest: (guest) => {
|
||||
if (backend === undefined) return () => {};
|
||||
let ceremonyPending = false;
|
||||
const serve = async (
|
||||
event: IpcMainInvokeEvent,
|
||||
publicKey: { readonly timeout?: unknown } | undefined,
|
||||
ceremony: (context: PasskeyCeremonyContext) => Promise<PasskeyCeremonyResult>,
|
||||
): Promise<PasskeyCeremonyResult> => {
|
||||
// Only the guest's main frame runs the bridge preload.
|
||||
const frame = event.senderFrame;
|
||||
if (!frame || frame !== guest.mainFrame) return notAllowed;
|
||||
// The page shares a JS world with the preload, so nothing it sends can
|
||||
// be trusted for the origin. Read the committed origin before any await:
|
||||
// the frame object outlives a navigation.
|
||||
const origin = frame.origin;
|
||||
// Like Chromium, only a focused page may open the sheet, one at a time.
|
||||
if (!isTrustworthyOrigin(origin) || ceremonyPending || !guest.isFocused()) {
|
||||
return notAllowed;
|
||||
}
|
||||
if (typeof publicKey !== "object" || publicKey === null) {
|
||||
return { success: false, error: "TypeError" };
|
||||
}
|
||||
const host = guest.hostWebContents
|
||||
? BrowserWindow.fromWebContents(guest.hostWebContents)
|
||||
: null;
|
||||
if (!host || host.isDestroyed()) return notAllowed;
|
||||
|
||||
ceremonyPending = true;
|
||||
try {
|
||||
const result = await withDeadline(
|
||||
ceremony({ origin, nativeWindowHandle: host.getNativeWindowHandle() }),
|
||||
ceremonyDeadline(publicKey.timeout),
|
||||
);
|
||||
// A credential minted for a document that navigated away belongs to nobody.
|
||||
const sameDocument =
|
||||
!frame.isDestroyed() && frame === guest.mainFrame && frame.origin === origin;
|
||||
return sameDocument ? result : notAllowed;
|
||||
} catch {
|
||||
return notAllowed;
|
||||
} finally {
|
||||
ceremonyPending = false;
|
||||
}
|
||||
};
|
||||
const detach = () => {
|
||||
guest.ipc.removeHandler(PASSKEY_CREATE_CHANNEL);
|
||||
guest.ipc.removeHandler(PASSKEY_GET_CHANNEL);
|
||||
};
|
||||
detach();
|
||||
// Option shapes are the page's to get wrong: the native layer validates
|
||||
// them and answers with a TypeError.
|
||||
guest.ipc.handle(
|
||||
PASSKEY_CREATE_CHANNEL,
|
||||
(event, publicKey: PublicKeyCredentialCreationOptions) =>
|
||||
serve(event, publicKey, (context) => backend.create(publicKey, context)),
|
||||
);
|
||||
guest.ipc.handle(PASSKEY_GET_CHANNEL, (event, publicKey: PublicKeyCredentialRequestOptions) =>
|
||||
serve(event, publicKey, (context) => backend.get(publicKey, context)),
|
||||
);
|
||||
return detach;
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.withSpan("PreviewPasskeys.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewPasskeys, make);
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as PreviewPasskeys from "../preview/Passkeys.ts";
|
||||
|
||||
const environmentInput = {
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
@@ -325,6 +326,11 @@ function layerTest(input: {
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
layerElectronTheme,
|
||||
layerElectronWindow,
|
||||
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
|
||||
bridgeEnabled: false,
|
||||
installSessionHandlers: () => {},
|
||||
attachGuest: () => () => {},
|
||||
}),
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
@@ -433,6 +439,11 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
} satisfies ElectronShell.ElectronShell["Service"]),
|
||||
layerElectronTheme,
|
||||
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
|
||||
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
|
||||
bridgeEnabled: false,
|
||||
installSessionHandlers: () => {},
|
||||
attachGuest: () => () => {},
|
||||
}),
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
getBrowserSession: () => Effect.succeed({} as Electron.Session),
|
||||
setMainWindow: () => Effect.void,
|
||||
|
||||
@@ -25,7 +25,9 @@ import {
|
||||
TRACKPAD_SCROLL_END_CHANNEL,
|
||||
WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
} from "../ipc/channels.ts";
|
||||
import { PASSKEY_BRIDGE_ARGUMENT } from "../preview/GuestProtocol.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as PreviewPasskeys from "../preview/Passkeys.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
@@ -326,6 +328,7 @@ export const make = Effect.gen(function* () {
|
||||
const electronTheme = yield* ElectronTheme.ElectronTheme;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const previewPasskeys = yield* PreviewPasskeys.PreviewPasskeys;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
@@ -537,6 +540,12 @@ export const make = Effect.gen(function* () {
|
||||
webPreferences.nodeIntegrationInSubFrames = false;
|
||||
webPreferences.contextIsolation = false;
|
||||
webPreferences.disableHtmlFullscreenWindowResize = true;
|
||||
if (previewPasskeys.bridgeEnabled) {
|
||||
webPreferences.additionalArguments = [
|
||||
...(webPreferences.additionalArguments ?? []),
|
||||
PASSKEY_BRIDGE_ARGUMENT,
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
const contextMenuContents = new WeakSet<Electron.WebContents>();
|
||||
|
||||
@@ -553,6 +553,16 @@ Notes:
|
||||
- The workflow writes it to a temporary `AuthKey_<id>.p8` file at runtime.
|
||||
- The workflow decodes `MACOS_PROVISIONING_PROFILE`, validates it with `security cms`, and passes it
|
||||
to the desktop packager.
|
||||
- In-app browser passkeys depend on the same profile. The packager adds each entitlement only when
|
||||
the profile grants it, because macOS will not launch an app that claims more than its profile
|
||||
allows. The build log reports which ones it enabled.
|
||||
- `keychain-access-groups` (`<TEAM_ID>.com.t3tools.t3code.webauthn`) enables Touch ID passkeys.
|
||||
Profiles that grant the team's keychain groups (`<TEAM_ID>.*`) cover it.
|
||||
- `com.apple.developer.web-browser.public-key-credential` lets the system passkey sheet (iCloud
|
||||
Keychain, password managers, phones, security keys) serve any site. Apple grants it as a
|
||||
managed capability: the Account Holder requests it through the
|
||||
[macOS Browsers Passkeys form](https://developer.apple.com/contact/request/macos-browsers-passkeys/).
|
||||
After approval, regenerate the profile and update `MACOS_PROVISIONING_PROFILE`.
|
||||
|
||||
## 3) Azure Trusted Signing setup (Windows)
|
||||
|
||||
|
||||
Generated
+136
@@ -27,6 +27,12 @@ catalogs:
|
||||
'@pierre/diffs':
|
||||
specifier: 1.5.2
|
||||
version: 1.5.2
|
||||
'@types/plist':
|
||||
specifier: 3.0.5
|
||||
version: 3.0.5
|
||||
electron-webauthn:
|
||||
specifier: 1.3.1
|
||||
version: 1.3.1
|
||||
jose:
|
||||
specifier: 6.2.2
|
||||
version: 6.2.2
|
||||
@@ -42,6 +48,9 @@ catalogs:
|
||||
micromark-util-types:
|
||||
specifier: 2.0.2
|
||||
version: 2.0.2
|
||||
plist:
|
||||
specifier: 3.1.1
|
||||
version: 3.1.1
|
||||
rehype-raw:
|
||||
specifier: 7.0.0
|
||||
version: 7.0.0
|
||||
@@ -60,6 +69,9 @@ catalogs:
|
||||
remark-rehype:
|
||||
specifier: 11.1.2
|
||||
version: 11.1.2
|
||||
tldts:
|
||||
specifier: 7.4.2
|
||||
version: 7.4.2
|
||||
typescript:
|
||||
specifier: 7.0.2
|
||||
version: 7.0.2
|
||||
@@ -117,6 +129,8 @@ overrides:
|
||||
'@opencode/protocol>effect': 4.0.2
|
||||
'@opencode/schema>effect': 4.0.2
|
||||
node-abi: 4.33.0
|
||||
electron-webauthn>@electron-webauthn/macos: 1.3.1
|
||||
'@electron-webauthn/macos>objc-js': 1.5.0
|
||||
lightningcss: 1.33.0
|
||||
tailwindcss: 4.3.3
|
||||
'@types/ws@^8': 8.18.2
|
||||
@@ -229,6 +243,9 @@ importers:
|
||||
electron-updater:
|
||||
specifier: ^6.8.9
|
||||
version: 6.8.9
|
||||
electron-webauthn:
|
||||
specifier: 'catalog:'
|
||||
version: 1.3.1([email protected])
|
||||
ffi-rs:
|
||||
specifier: 1.3.2
|
||||
version: 1.3.2
|
||||
@@ -238,6 +255,9 @@ importers:
|
||||
react-grab:
|
||||
specifier: ^0.1.32
|
||||
version: 0.1.44([email protected])
|
||||
tldts:
|
||||
specifier: 'catalog:'
|
||||
version: 7.4.2
|
||||
devDependencies:
|
||||
'@effect/vitest':
|
||||
specifier: 4.0.2
|
||||
@@ -1554,6 +1574,9 @@ importers:
|
||||
effect:
|
||||
specifier: 4.0.2
|
||||
version: 4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688)
|
||||
plist:
|
||||
specifier: 'catalog:'
|
||||
version: 3.1.1
|
||||
pngjs:
|
||||
specifier: 7.0.0
|
||||
version: 7.0.0
|
||||
@@ -1564,6 +1587,9 @@ importers:
|
||||
'@effect/vitest':
|
||||
specifier: 4.0.2
|
||||
version: 4.0.2(patch_hash=595b7d26fb635caba9c3d39fcb189bb78a000192f8d3b60ead7174b310d1ade9)(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688))([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])
|
||||
'@types/plist':
|
||||
specifier: 'catalog:'
|
||||
version: 3.0.5
|
||||
'@types/pngjs':
|
||||
specifier: 6.0.5
|
||||
version: 6.0.5
|
||||
@@ -2868,6 +2894,15 @@ packages:
|
||||
resolution: {integrity: sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==}
|
||||
engines: {node: '>=22.12.0'}
|
||||
|
||||
'@electron-webauthn/[email protected]':
|
||||
resolution: {integrity: sha512-NJA4I83ulh3pOfkv7sBkEGecTxaCtjFUbGTAi+BLNWdFc463AY7DaUprsqbGr+WAnD8SIUpuHSO7vC0C+HPu6g==}
|
||||
os: [darwin]
|
||||
peerDependencies:
|
||||
typescript: ^6.0.2
|
||||
|
||||
'@electron-webauthn/[email protected]':
|
||||
resolution: {integrity: sha512-C7Jy6dg32/QzIAl1E110acjpp6+b67xqZJL4L0rL2X2VIOJx4m+vfcWl3AjC4JgkxUBcSMSNa85bay2/473y/Q==}
|
||||
|
||||
'@electron/[email protected]':
|
||||
resolution: {integrity: sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==}
|
||||
engines: {node: '>=10.12.0'}
|
||||
@@ -4215,9 +4250,32 @@ packages:
|
||||
'@opencode/[email protected]':
|
||||
resolution: {integrity: sha512-DglA+CCNmCaiAJ8FqAKo2EKIkCOF9/EmMEYowcXhTrQcoJ7eaTx7ytGjPgis6VHQuU4aaAgwZYw96ypS3ojsIw==}
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-9RCU6OwXU6p67H4NODbuxv2S3eenuQ4/WFLrsq+K/k682xrznH5EVWA7N4VFk9VYVcbFtKqur5YQQZc0ySGhsQ==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-AY6Lknexs7n2xp8Cgey95c+975VG7XOk4UEdRdNFxHmDDbuf47OC/LAVRsl14DeTLwo8W6xr3HLFwUFmKcndTQ==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-dVz8TkkgYdr3tlwxHd7SCYGxoN7ynwHLA0nei/Aq9C+ERU0BK+U8+/3soEzBUxUNKYBf42351DyJUZ2REla50w==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-dyIB0SdZgMm5BhGwdSp8rMxEFIopLKxDG1vxIBaiogyom6ZqH2aXPb6DEC2WzOOWKdPSq1cxdNeRx2wAn1Z+ZQ==}
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==}
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
resolution: {integrity: sha512-2ZRpbt3msNURwvjmavzq9vrNlxUnWFBGMYqbC1kO3fYBLskL7r4DiLJT1wbtLoI+hclFwjhl48YhRFBl6RWg1A==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@oxc-parser/[email protected]':
|
||||
resolution: {integrity: sha512-fOtoGvIoirkvxQVw9J1WJPxz571XPgLsPf9uhRD+PJteUnvrJHMDmK9pw2yZEGGyismtRoEsp+JcXUdF/JDMDw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -6049,6 +6107,9 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}
|
||||
|
||||
@@ -7991,6 +8052,11 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-I8/SOjPfnIiVjN38eTX3BRZfuFDGzLWtlByh4OecmlVkfxQt9R/zCwEm4PquyvaqP+xtGgkFrBxwOuJ+DhWlDg==}
|
||||
peerDependencies:
|
||||
typescript: ^6.0.2
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
@@ -9813,6 +9879,10 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==}
|
||||
engines: {node: ^18 || ^20 || >= 21}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
|
||||
|
||||
@@ -9908,6 +9978,10 @@ packages:
|
||||
resolution: {integrity: sha512-i8iA8uij0g1YQzS8uOJPSRCgwDjO9warIHUAu1Fqj877Wc3wlfxDYBioYWgKTBF2+URVJttyDWSEpmd99nlvtQ==}
|
||||
engines: {node: ^22.13.0 || ^24.3.0 || >= 26.0.0}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-IHmouX5xYrE2UyGRRlpwY7u2HJVjF6P/P+jy6Vqga+Ya7RAf/hFeNkt4KgTkGUMM3VmnBVUEMJ0tKWY2RlYgKg==}
|
||||
os: [darwin]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -13599,6 +13673,16 @@ snapshots:
|
||||
|
||||
'@electron-internal/[email protected]': {}
|
||||
|
||||
'@electron-webauthn/[email protected]([email protected])':
|
||||
dependencies:
|
||||
'@electron-webauthn/types': 1.3.1
|
||||
'@oslojs/webauthn': 1.0.0
|
||||
objc-js: 1.5.0
|
||||
typescript: 7.0.2
|
||||
optional: true
|
||||
|
||||
'@electron-webauthn/[email protected]': {}
|
||||
|
||||
'@electron/[email protected]':
|
||||
dependencies:
|
||||
commander: 5.1.0
|
||||
@@ -14991,8 +15075,39 @@ snapshots:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
effect: 4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688)
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
dependencies:
|
||||
'@oslojs/binary': 1.0.0
|
||||
optional: true
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
dependencies:
|
||||
'@oslojs/binary': 1.0.0
|
||||
optional: true
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
dependencies:
|
||||
'@oslojs/asn1': 1.0.0
|
||||
'@oslojs/binary': 1.0.0
|
||||
optional: true
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@oslojs/[email protected]': {}
|
||||
|
||||
'@oslojs/[email protected]':
|
||||
dependencies:
|
||||
'@oslojs/asn1': 1.0.0
|
||||
'@oslojs/binary': 1.0.0
|
||||
'@oslojs/cbor': 1.0.0
|
||||
'@oslojs/crypto': 1.0.0
|
||||
'@oslojs/encoding': 1.0.0
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/[email protected]':
|
||||
optional: true
|
||||
|
||||
@@ -16589,6 +16704,11 @@ snapshots:
|
||||
dependencies:
|
||||
undici-types: 7.16.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 24.12.4
|
||||
xmlbuilder: 15.1.1
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 24.12.4
|
||||
@@ -18436,6 +18556,13 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
'@electron-webauthn/types': 1.3.1
|
||||
typescript: 7.0.2
|
||||
optionalDependencies:
|
||||
'@electron-webauthn/macos': 1.3.1([email protected])
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@electron/asar': 3.4.1
|
||||
@@ -20739,6 +20866,9 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
semver: 7.8.5
|
||||
@@ -20857,6 +20987,12 @@ snapshots:
|
||||
dependencies:
|
||||
flow-enums-runtime: 0.0.6
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
node-addon-api: 8.9.2
|
||||
node-gyp-build: 4.8.4
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -18,6 +18,8 @@ allowBuilds:
|
||||
msgpackr-extract: true
|
||||
msw: false
|
||||
node-pty: true
|
||||
# Ships N-API prebuilds; its install script only rebuilds from source.
|
||||
objc-js: false
|
||||
sharp: true
|
||||
utf-8-validate: false
|
||||
workerd: false
|
||||
@@ -38,6 +40,7 @@ catalog:
|
||||
"@effect/sql-sqlite-do": 4.0.2
|
||||
"@effect/tsgo": 0.46.1
|
||||
"@effect/vitest": 4.0.2
|
||||
"@electron-webauthn/macos": 1.3.1
|
||||
"@legendapp/list": 3.3.5
|
||||
"@noble/curves": 1.9.1
|
||||
"@noble/hashes": 1.8.0
|
||||
@@ -46,11 +49,16 @@ catalog:
|
||||
"@tailwindcss/oxide": 4.3.3
|
||||
"@tailwindcss/vite": 4.3.3
|
||||
"@types/node": 24.12.4
|
||||
"@types/plist": 3.0.5
|
||||
"@types/ws": 8.18.2
|
||||
effect: 4.0.2
|
||||
electron-webauthn: 1.3.1
|
||||
jose: 6.2.2
|
||||
lightningcss: 1.33.0
|
||||
objc-js: 1.5.0
|
||||
plist: 3.1.1
|
||||
tailwindcss: 4.3.3
|
||||
tldts: 7.4.2
|
||||
typescript: 7.0.2
|
||||
undici: 8.11.2
|
||||
vite: npm:@voidzero-dev/[email protected]
|
||||
@@ -249,6 +257,10 @@ overrides:
|
||||
"@opencode/protocol>effect": "catalog:"
|
||||
"@opencode/schema>effect": "catalog:"
|
||||
node-abi: 4.33.0
|
||||
# The desktop app installs these without a lockfile when it packages them, so
|
||||
# pin the native passkey code that runs in its main process.
|
||||
"electron-webauthn>@electron-webauthn/macos": "catalog:"
|
||||
"@electron-webauthn/macos>objc-js": "catalog:"
|
||||
lightningcss: "catalog:"
|
||||
tailwindcss: "catalog:"
|
||||
# Ranges from @effect/platform-node, jsdom, unifont, Expo and libsql otherwise
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
preflightMacDesktopBuild,
|
||||
preflightWindowsDesktopBuild,
|
||||
renderMacPasskeyEntitlements,
|
||||
resolveMacWebAuthnEntitlements,
|
||||
resolveClerkPasskeyNativeArtifacts,
|
||||
resolveMacPasskeySigningConfiguration,
|
||||
resolveDesktopRuntimeDependencies,
|
||||
@@ -95,6 +96,12 @@ import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
|
||||
|
||||
// Keeps pnpm from auto-installing TypeScript, a types-only peer, into the app.
|
||||
const stagePackageExtensions = {
|
||||
"electron-webauthn": { peerDependenciesMeta: { typescript: { optional: true } } },
|
||||
"@electron-webauthn/macos": { peerDependenciesMeta: { typescript: { optional: true } } },
|
||||
};
|
||||
|
||||
// A minimal stand-in for the Linux CLI release archive: one top-level
|
||||
// directory named after the archive stem holding the executable, the web
|
||||
// client, and the runtime externals with node-pty built from source.
|
||||
@@ -454,6 +461,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
os: ["darwin"],
|
||||
cpu: ["x64"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
});
|
||||
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "linux", arch: "x64" }), {
|
||||
supportedArchitectures: {
|
||||
@@ -461,6 +469,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
cpu: ["x64"],
|
||||
libc: ["glibc"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
});
|
||||
// Windows stages only win32 natives; WSL runs the separately built Linux
|
||||
// CLI archive rather than anything installed here.
|
||||
@@ -469,18 +478,21 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
os: ["win32"],
|
||||
cpu: ["x64"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
});
|
||||
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "arm64" }), {
|
||||
supportedArchitectures: {
|
||||
os: ["win32"],
|
||||
cpu: ["arm64"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
});
|
||||
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
|
||||
supportedArchitectures: {
|
||||
os: ["darwin"],
|
||||
cpu: ["arm64", "x64"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -507,6 +519,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
cpu: ["x64"],
|
||||
libc: ["glibc"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
allowBuilds: {
|
||||
electron: true,
|
||||
"node-pty": true,
|
||||
@@ -537,6 +550,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
os: ["darwin"],
|
||||
cpu: ["arm64"],
|
||||
},
|
||||
packageExtensions: stagePackageExtensions,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1886,7 +1900,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
T3CODE_CLERK_PASSKEY_RP_DOMAINS:
|
||||
" Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",
|
||||
});
|
||||
const entitlements = renderMacPasskeyEntitlements(configuration);
|
||||
const entitlements = renderMacPasskeyEntitlements(configuration, {
|
||||
touchIdKeychainAccessGroup: undefined,
|
||||
browserPasskeys: false,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(configuration.rpDomains, [
|
||||
"clerk.example.com",
|
||||
@@ -1896,6 +1913,78 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");
|
||||
assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");
|
||||
assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");
|
||||
assert.notInclude(entitlements, "keychain-access-groups");
|
||||
assert.notInclude(entitlements, "com.apple.developer.web-browser.public-key-credential");
|
||||
});
|
||||
|
||||
it("grants in-app browser passkey entitlements only when the provisioning profile does", () => {
|
||||
const configuration = { appId: "com.t3tools.t3code", teamId: "ABC1234567" };
|
||||
// Profiles are CMS envelopes around a plain XML plist.
|
||||
const profile = (entitlements: string, outside = "") =>
|
||||
`0\x82\x1f\x9a\x06\t*\x86H<?xml version="1.0"?><plist version="1.0"><dict>${outside}<key>Entitlements</key><dict>${entitlements}</dict></dict></plist>\x00\x01`;
|
||||
const teamWildcardGroups = `<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>ABC1234567.*</string>
|
||||
<string>com.apple.token</string>
|
||||
</array>`;
|
||||
|
||||
assert.deepStrictEqual(resolveMacWebAuthnEntitlements(profile(""), configuration), {
|
||||
touchIdKeychainAccessGroup: undefined,
|
||||
browserPasskeys: false,
|
||||
});
|
||||
assert.deepStrictEqual(
|
||||
resolveMacWebAuthnEntitlements(
|
||||
profile("<key>keychain-access-groups</key><array><string>OTHERTEAM1.*</string></array>"),
|
||||
configuration,
|
||||
),
|
||||
{ touchIdKeychainAccessGroup: undefined, browserPasskeys: false },
|
||||
);
|
||||
// Only real values inside the Entitlements dict count: not comments, not
|
||||
// explicit false, not keys elsewhere in the profile.
|
||||
assert.deepStrictEqual(
|
||||
resolveMacWebAuthnEntitlements(
|
||||
profile(
|
||||
`<!-- ${teamWildcardGroups}
|
||||
<key>com.apple.developer.web-browser.public-key-credential</key><true/> -->
|
||||
<key>com.apple.developer.web-browser.public-key-credential</key><false/>`,
|
||||
teamWildcardGroups,
|
||||
),
|
||||
configuration,
|
||||
),
|
||||
{ touchIdKeychainAccessGroup: undefined, browserPasskeys: false },
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
resolveMacWebAuthnEntitlements(
|
||||
profile(
|
||||
`${teamWildcardGroups}
|
||||
<key>com.apple.developer.web-browser.public-key-credential</key>
|
||||
<true/>`,
|
||||
),
|
||||
configuration,
|
||||
),
|
||||
{
|
||||
touchIdKeychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn",
|
||||
browserPasskeys: true,
|
||||
},
|
||||
);
|
||||
|
||||
const entitlements = renderMacPasskeyEntitlements(
|
||||
{ ...configuration, rpDomains: ["clerk.example.com"], provisioningProfilePath: "" },
|
||||
resolveMacWebAuthnEntitlements(
|
||||
profile(
|
||||
`${teamWildcardGroups}<key>com.apple.developer.web-browser.public-key-credential</key><true/>`,
|
||||
),
|
||||
configuration,
|
||||
),
|
||||
);
|
||||
assert.match(
|
||||
entitlements,
|
||||
/<key>keychain-access-groups<\/key>\s*<array>\s*<string>ABC1234567\.com\.t3tools\.t3code\.webauthn<\/string>\s*<\/array>/u,
|
||||
);
|
||||
assert.match(
|
||||
entitlements,
|
||||
/<key>com\.apple\.developer\.web-browser\.public-key-credential<\/key>\s*<true\/>/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects incomplete macOS passkey signing configuration", () => {
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as NodeModule from "node:module";
|
||||
// plist is CommonJS; Node cannot load its named exports from an ES module.
|
||||
import Plist from "plist";
|
||||
|
||||
import {
|
||||
createPackageWithOptions,
|
||||
@@ -80,10 +82,28 @@ const StageWorkspaceConfig = Schema.Struct({
|
||||
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
|
||||
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
||||
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
||||
packageExtensions: Schema.optional(
|
||||
Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({
|
||||
peerDependenciesMeta: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({ optional: Schema.Boolean }),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
nodeLinker: Schema.optional(Schema.Literals(["hoisted"])),
|
||||
});
|
||||
type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type;
|
||||
|
||||
// electron-webauthn declares TypeScript as a peer only for its typings. pnpm
|
||||
// auto-installs missing peers, which would ship a compiler inside the app.
|
||||
const STAGE_PACKAGE_EXTENSIONS = {
|
||||
"electron-webauthn": { peerDependenciesMeta: { typescript: { optional: true } } },
|
||||
"@electron-webauthn/macos": { peerDependenciesMeta: { typescript: { optional: true } } },
|
||||
} as const;
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
|
||||
);
|
||||
@@ -926,6 +946,7 @@ interface StagePackageJson {
|
||||
readonly version: string;
|
||||
readonly buildVersion: string;
|
||||
readonly t3codeCommitHash: string;
|
||||
readonly t3codeWebAuthn?: MacWebAuthnEntitlements;
|
||||
readonly private: true;
|
||||
readonly packageManager: string;
|
||||
readonly description: string;
|
||||
@@ -1289,12 +1310,80 @@ function escapeXml(value: string): string {
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Passkey entitlements for the in-app browser. Each is granted only when the
|
||||
* provisioning profile authorizes it: macOS refuses to launch an app that
|
||||
* claims a restricted entitlement its embedded profile does not carry.
|
||||
*/
|
||||
export interface MacWebAuthnEntitlements {
|
||||
/** Keychain group for Electron's Touch ID passkeys. */
|
||||
readonly touchIdKeychainAccessGroup: string | undefined;
|
||||
/** Apple's managed browser entitlement, which allows passkeys for any site. */
|
||||
readonly browserPasskeys: boolean;
|
||||
}
|
||||
|
||||
const BROWSER_PASSKEYS_ENTITLEMENT = "com.apple.developer.web-browser.public-key-credential";
|
||||
|
||||
const ProvisioningProfilePlist = Schema.Struct({
|
||||
Entitlements: Schema.Struct({
|
||||
"keychain-access-groups": Schema.optional(Schema.Array(Schema.String)),
|
||||
[BROWSER_PASSKEYS_ENTITLEMENT]: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
const isProvisioningProfilePlist = Schema.is(ProvisioningProfilePlist);
|
||||
|
||||
/**
|
||||
* Reads the Entitlements dict of the XML plist a provisioning profile wraps in
|
||||
* its CMS envelope. Anything unreadable grants nothing.
|
||||
*/
|
||||
const readProfileEntitlements = (provisioningProfile: string) => {
|
||||
const start = provisioningProfile.indexOf("<?xml");
|
||||
const end = provisioningProfile.indexOf("</plist>", start);
|
||||
if (start === -1 || end === -1) return undefined;
|
||||
try {
|
||||
const profile: unknown = Plist.parse(provisioningProfile.slice(start, end + "</plist>".length));
|
||||
return isProvisioningProfilePlist(profile) ? profile.Entitlements : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export function resolveMacWebAuthnEntitlements(
|
||||
provisioningProfile: string,
|
||||
configuration: Pick<MacPasskeySigningConfiguration, "appId" | "teamId">,
|
||||
): MacWebAuthnEntitlements {
|
||||
const entitlements = readProfileEntitlements(provisioningProfile);
|
||||
const keychainAccessGroup = `${configuration.teamId}.${configuration.appId}.webauthn`;
|
||||
const keychainGroupAuthorized = (entitlements?.["keychain-access-groups"] ?? []).some((group) =>
|
||||
group.endsWith("*")
|
||||
? keychainAccessGroup.startsWith(group.slice(0, -1))
|
||||
: group === keychainAccessGroup,
|
||||
);
|
||||
return {
|
||||
touchIdKeychainAccessGroup: keychainGroupAuthorized ? keychainAccessGroup : undefined,
|
||||
browserPasskeys: entitlements?.[BROWSER_PASSKEYS_ENTITLEMENT] === true,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderMacPasskeyEntitlements(
|
||||
configuration: MacPasskeySigningConfiguration,
|
||||
webAuthn: MacWebAuthnEntitlements,
|
||||
): string {
|
||||
const associatedDomains = configuration.rpDomains
|
||||
.map((domain) => ` <string>webcredentials:${escapeXml(domain)}</string>`)
|
||||
.join("\n");
|
||||
const keychainAccessGroups = webAuthn.touchIdKeychainAccessGroup
|
||||
? `
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>${escapeXml(webAuthn.touchIdKeychainAccessGroup)}</string>
|
||||
</array>`
|
||||
: "";
|
||||
const browserPasskeys = webAuthn.browserPasskeys
|
||||
? `
|
||||
<key>${BROWSER_PASSKEYS_ENTITLEMENT}</key>
|
||||
<true/>`
|
||||
: "";
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
@@ -1307,7 +1396,7 @@ export function renderMacPasskeyEntitlements(
|
||||
<key>com.apple.developer.associated-domains</key>
|
||||
<array>
|
||||
${associatedDomains}
|
||||
</array>
|
||||
</array>${keychainAccessGroups}${browserPasskeys}
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
@@ -1535,6 +1624,7 @@ export function createStageWorkspaceConfig(input: {
|
||||
? { patchedDependencies }
|
||||
: {}),
|
||||
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
|
||||
packageExtensions: STAGE_PACKAGE_EXTENSIONS,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3673,13 +3763,24 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
const macEntitlementsPath = macPasskeySigning
|
||||
? path.join(stageAppDir, "entitlements.mac.plist")
|
||||
: undefined;
|
||||
let macWebAuthn: MacWebAuthnEntitlements | undefined;
|
||||
if (macPasskeySigning && macEntitlementsPath) {
|
||||
if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
|
||||
return yield* new MacProvisioningProfileNotFoundError({
|
||||
provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
|
||||
});
|
||||
}
|
||||
yield* fs.writeFileString(macEntitlementsPath, renderMacPasskeyEntitlements(macPasskeySigning));
|
||||
macWebAuthn = resolveMacWebAuthnEntitlements(
|
||||
yield* fs.readFileString(macPasskeySigning.provisioningProfilePath),
|
||||
macPasskeySigning,
|
||||
);
|
||||
yield* Effect.log(
|
||||
`[desktop-artifact] In-app browser passkeys: Touch ID ${macWebAuthn.touchIdKeychainAccessGroup ? "enabled" : "disabled"}, browser passkeys ${macWebAuthn.browserPasskeys ? "enabled" : "disabled"}.`,
|
||||
);
|
||||
yield* fs.writeFileString(
|
||||
macEntitlementsPath,
|
||||
renderMacPasskeyEntitlements(macPasskeySigning, macWebAuthn),
|
||||
);
|
||||
}
|
||||
|
||||
// Windows splits dependencies per process: app.asar carries only the
|
||||
@@ -3709,6 +3810,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
version: appVersion,
|
||||
buildVersion: appVersion,
|
||||
t3codeCommitHash: commitHash,
|
||||
// Read by apps/desktop/src/preview/Passkeys.ts; must match the signed entitlements.
|
||||
...(macWebAuthn ? { t3codeWebAuthn: macWebAuthn } : {}),
|
||||
private: true,
|
||||
packageManager: rootPackageJson.packageManager,
|
||||
description:
|
||||
|
||||
@@ -16,6 +16,7 @@ export const DESKTOP_RUNTIME_EXTERNAL_PREFIXES = [
|
||||
"@napi-rs/keyring",
|
||||
"@crowecawcaw/xa11y",
|
||||
"@clerk/electron-passkeys",
|
||||
"electron-webauthn",
|
||||
"ffi-rs",
|
||||
"@yuuang/",
|
||||
// Reads its own bundle from disk by resolving `playwright-core/package.json`
|
||||
|
||||
@@ -13,11 +13,13 @@
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"plist": "catalog:",
|
||||
"pngjs": "7.0.0",
|
||||
"sharp": "0.35.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/plist": "catalog:",
|
||||
"@types/pngjs": "6.0.5",
|
||||
"typescript": "catalog:",
|
||||
"typescript-legacy": "npm:typescript@~6.0.3",
|
||||
|
||||
@@ -278,6 +278,27 @@
|
||||
"copyrights": ["Copyright (c) 2025 Stephen Crowe"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"repositoryUrl": "https://github.com/iamEvanYT/electron-webauthn",
|
||||
"generatedNotice": {
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2026 iamEvan"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "@electron-webauthn/types",
|
||||
"sourceUrl": "https://github.com/iamEvanYT/electron-webauthn",
|
||||
"generatedNotice": {
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2026 iamEvan"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "objc-js"
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "map-stream",
|
||||
|
||||
Reference in new issue
Block a user