Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix: integrate macOS browser passkey configuration

yxlyx62084dc41718
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index fff4e02b..6bc4bb58 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -22,6 +22,10 @@ jobs:
bun-version: '1.4.2'
- run: bun install --frozen-lockfile
- run: bun run test:desktop
+ - name: Embedded browser WebAuthn dispatch (virtual authenticator)
+ run: |
+ if [ ! -f node_modules/electron/path.txt ]; then bun node_modules/electron/install.js; fi
+ bun run test:webauthn
- run: bun run build
- run: bunx playwright install chromium
- run: bun run test:queue
diff --git a/apps/native/electron/README.md b/apps/native/electron/README.md
index 4e86329a..d8201d3d 100644
--- a/apps/native/electron/README.md
+++ b/apps/native/electron/README.md
@@ -65,6 +65,56 @@ The existing AppKit/Kuri shell remains a fallback through
this local Electron trial. Browser permissions are denied by default; a
permission UI and release updater are follow-up distribution work.
+## Browser passkeys
+
+Developer ID signing writes the Touch ID keychain group into both the main app's
+entitlements and `Contents/Resources/webauthn.json`. Startup configures Electron
+from that signed resource before creating browser pages. The group uses the
+signing team and bundle identifier; keep both stable across releases so existing
+credentials remain accessible. If the signing identity is a certificate hash,
+set `GRAFF_SIGN_TEAM_ID` to its ten-character Apple team identifier.
+
+Signing also requires `GRAFF_WEBAUTHN_PROFILE`: a valid macOS provisioning profile
+for that signing certificate/team and bundle identifier, authorizing the
+`keychain-access-groups` value (an authorized team wildcard is also accepted).
+The signer checks its platform, expiration, app identifier and group, then embeds
+it and supplies the matching `com.apple.application-identifier`. A bare keychain
+entitlement without an authorizing profile can pass signature verification but
+be rejected by macOS at launch. Do not omit this provisioning step.
+
+On supported Macs, this enables device-bound Touch ID credentials created in
+Codegraff's persistent browser partition. It does **not** expose existing iCloud
+Keychain passkeys or sync credentials to other devices. Development/ad-hoc builds
+without the signing configuration do not enable this authenticator. General
+browser permission policy remains deny-by-default.
+
+When a request offers accounts, choose one in the native account dialog; Cancel
+rejects the request. Navigation, hiding the tab, and closing the page cancel the
+selection. **Tools → Browser passkey help…** explains the limitations and offers
+to open the active HTTP(S) page in the default browser, only after an explicit
+click. Alternatively use the site's password or another sign-in method. A login
+in the default browser does not transfer to the embedded browser.
+
+Verification:
+
+```sh
+node --test apps/native/electron/webauthn*.test.cjs
+node apps/native/scripts/test-webauthn.mjs
+```
+
+The virtual-authenticator regression checks Chromium's real credential and
+account-selection dispatch without biometric prompts. It is **not** proof of
+Secure Enclave access. Before claiming platform support in a release, validate
+the Developer ID-signed app on a supported Mac: verify its signature and matching
+keychain group, register a new device-bound credential on a test relying party,
+complete Touch ID, quit/reopen and authenticate, select between two accounts,
+and cancel a request. Also confirm that an existing iCloud-only credential has a
+clear fallback. These hardware checks require a person; do not automate Touch ID
+or claim a virtual authenticator verifies it. For a noninteractive availability
+check on the signed bundle, run the packaged smoke test with
+`GRAFF_SMOKE_LAUNCH_ONLY=1 GRAFF_SMOKE_WEBAUTHN=1`; this checks production startup,
+not registration or biometric consent.
+
## macOS computer use and agent browser tools
**Codegraff → Computer use…** enables or disables laptop control for this launch
@@ -145,13 +195,15 @@ See [repeatable performance scenarios](VISUAL-TESTS.md) for the model-free runne
## Building a distribution disk image
`build.sh` produces a development app with a local signature. For public downloads,
-run `distribute.sh` with a Developer ID Application identity and a `notarytool`
+run `distribute.sh` with a Developer ID Application identity, an authorizing
+macOS provisioning profile (see Browser passkeys above), and a `notarytool`
keychain profile. Bun installs the pinned Electron signing utility with the other
development dependencies.
```sh
GRAFF_SIGN_IDENTITY="Developer ID Application: Your Name (TEAMID)" \
GRAFF_NOTARY_PROFILE="notary-local" \
+GRAFF_WEBAUTHN_PROFILE="signing/Codegraff.provisionprofile" \
bash apps/native/electron/distribute.sh zig-out/electron/Codegraff.app zig-out/distribution
```
diff --git a/apps/native/electron/browser-tabs.cjs b/apps/native/electron/browser-tabs.cjs
index b8d8abf5..f8ee0e0b 100644
--- a/apps/native/electron/browser-tabs.cjs
+++ b/apps/native/electron/browser-tabs.cjs
@@ -1,4 +1,4 @@
-const { WebContentsView, session } = require('electron');
+const { WebContentsView, session, webContents, dialog } = require('electron');
const path = require('node:path');
const { pageURL, bounds } = require('./policy.cjs');
@@ -8,6 +8,12 @@ class BrowserTabs {
this.visible = null; this.suspendMs = 60_000;
// One persistent browser session shares network/cache processes, separate from the app.
this.session = session.fromPartition('persist:browser');
+ require('./webauthn.cjs').installAccountSelection(this.session, { dialog, ownerForFrame: frame => {
+ if (!frame || frame.detached || this.window.isDestroyed()) return null;
+ const contents = webContents.fromFrame(frame);
+ const tab = this.tabs.get(this.visible);
+ return tab?.view?.webContents === contents ? { window: this.window, contents } : null;
+ } });
this.session.setPermissionRequestHandler((_wc, _permission, callback) => callback(false));
this.session.setPermissionCheckHandler(() => false);
this.session.on('will-download', (_event, item) => { item.setSaveDialogOptions({ title: 'Save download', defaultPath: item.getFilename() }); });
@@ -78,6 +84,7 @@ class BrowserTabs {
}
hide(chat) {
const tab = this.tabs.get(chat); if (!tab) return;
+ tab.view?.webContents.emit('graff-webauthn-cancel');
tab.view?.setVisible(false); if (this.visible === chat) this.visible = null;
clearTimeout(tab.timer);
tab.timer = setTimeout(() => { this.release(tab); this.notify(tab); }, this.suspendMs);
diff --git a/apps/native/electron/distribute.sh b/apps/native/electron/distribute.sh
index b4dbaa06..3e31b928 100755
--- a/apps/native/electron/distribute.sh
+++ b/apps/native/electron/distribute.sh
@@ -4,6 +4,7 @@ set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
: "${GRAFF_SIGN_IDENTITY:?Set a Developer ID Application identity}"
: "${GRAFF_NOTARY_PROFILE:?Set a notarytool keychain profile}"
+: "${GRAFF_WEBAUTHN_PROFILE:?Set a macOS provisioning profile authorizing the app and WebAuthn keychain group}"
source_app="${1:?Usage: distribute.sh /path/Codegraff.app /path/output}"
out="${2:?Provide a new output directory}"
mkdir -p "$out"
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index acaf14ee..c5917854 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -68,6 +68,7 @@ process.on('SIGINT', () => app.quit());
app.whenReady().then(async () => {
app.setAccessibilitySupportEnabled(true);
+ const passkeysConfigured = require('./webauthn.cjs').configureWebAuthn(app, resources);
const token = randomBytes(32).toString('hex');
win = createWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,
title: 'Codegraff', titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 }, backgroundColor: '#fafaf9', show: false,
@@ -170,7 +171,9 @@ app.whenReady().then(async () => {
const installed = await require('./cli-launcher.cjs').installLauncher(path.resolve(app.getPath('exe'), '../../..'), app.getPath('home'));
await dialog.showMessageBox(win, { message: 'Terminal command installed', detail: `Run codegraff . to open a project here. Ensure ${path.dirname(installed)} is on your PATH.` });
} catch (error) { dialog.showErrorBox('Terminal command', error.message); }
- } }] },
+ } }, { label: 'Browser passkey help…', click: () => void require('./webauthn.cjs').showPasskeyHelp({
+ window: win, browser, dialog, shell: require('electron').shell, configured: passkeysConfigured,
+ }).catch(() => dialog.showErrorBox('Browser passkeys', 'Could not open the default browser. Use another sign-in method on the site.')) }] },
{ role: 'editMenu' }, { label: 'View', submenu: [{ role: 'reload' }, { role: 'toggleDevTools' }, { role: 'togglefullscreen' }, { label: 'Release browser pages', click: () => { browser.closeAll(); win.webContents.send('browser-event', { type: 'released' }); } }] },
{ label: 'Performance', submenu: [
{ label: 'Start recording', click: () => void profiler.start() },
diff --git a/apps/native/electron/sign-bundle.mjs b/apps/native/electron/sign-bundle.mjs
index aab06a9a..f840035a 100644
--- a/apps/native/electron/sign-bundle.mjs
+++ b/apps/native/electron/sign-bundle.mjs
@@ -1,13 +1,10 @@
import { sign } from '@electron/osx-sign';
-const app = process.argv[2];
-if (!app || !process.env.GRAFF_SIGN_IDENTITY) throw Error('Provide an app path and GRAFF_SIGN_IDENTITY.');
-await sign({ app, platform: 'darwin', type: 'distribution', identity: process.env.GRAFF_SIGN_IDENTITY,
- preAutoEntitlements: false, preEmbedProvisioningProfile: false,
- optionsForFile(file) {
- const bun = file.endsWith('/Resources/bun');
- const jit = bun || file === app || file.endsWith('.app') || file.includes('/Electron Framework.framework/');
- const entitlements = jit ? ['com.apple.security.cs.allow-jit'] : [];
- if (bun) entitlements.push('com.apple.security.cs.allow-unsigned-executable-memory');
- return { hardenedRuntime: true, entitlements };
- },
+import { signBundle } from './webauthn-signing.cjs';
+
+await signBundle({
+ app: process.argv[2],
+ identity: process.env.GRAFF_SIGN_IDENTITY,
+ teamId: process.env.GRAFF_SIGN_TEAM_ID,
+ profilePath: process.env.GRAFF_WEBAUTHN_PROFILE,
+ sign,
});
diff --git a/apps/native/electron/smoke-launch.cjs b/apps/native/electron/smoke-launch.cjs
index f4c45491..144fff91 100644
--- a/apps/native/electron/smoke-launch.cjs
+++ b/apps/native/electron/smoke-launch.cjs
@@ -27,6 +27,7 @@ async function run({ win, backend, browser, token }) {
assert.match(version, /graff/i);
if (process.env.GRAFF_SMOKE_HTML_TOOL) await require('./smoke-html.cjs').run({ win, backend, token });
const report = { passed: ['bundled server', 'production composer', 'empty browser lifecycle', 'request authentication', 'native module ABI', 'bundled engine executable', 'packaged executable'], version };
+ if (process.env.GRAFF_SMOKE_WEBAUTHN) report.passed.push(await require('./smoke-webauthn.cjs').run({ browser, backend, resources }));
fs.writeFileSync(process.env.GRAFF_ELECTRON_SMOKE, JSON.stringify(report, null, 2));
console.log(process.env.GRAFF_SMOKE_HTML_TOOL ? 'Packaged launch and offline HTML tool checks passed.' : 'Packaged launch checks passed. No prompt sent or coding setting changed.');
}
diff --git a/apps/native/electron/smoke-webauthn.cjs b/apps/native/electron/smoke-webauthn.cjs
new file mode 100644
index 00000000..ad22972d
--- /dev/null
+++ b/apps/native/electron/smoke-webauthn.cjs
@@ -0,0 +1,19 @@
+// Checks the production startup configuration; does not simulate biometric consent.
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+async function run({ browser, backend, resources }) {
+ const config = JSON.parse(fs.readFileSync(path.join(resources, 'webauthn.json'), 'utf8'));
+ assert.match(config.keychainAccessGroup, /^[A-Z0-9]{10}\.[A-Za-z0-9.-]+\.webauthn$/);
+ const chat = 'webauthn-packaging-check';
+ try {
+ await browser.navigate(chat, backend.origin);
+ const available = await browser.tabs.get(chat).view.webContents.executeJavaScript(
+ 'PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()');
+ assert.equal(available, true, 'Signed startup must expose the platform authenticator on supported hardware');
+ assert.equal(browser.session.listenerCount('select-webauthn-account'), 1);
+ return 'signed platform authenticator availability (no biometric ceremony)';
+ } finally { browser.close(chat); }
+}
+module.exports = { run };
diff --git a/apps/native/electron/webauthn-integration.cjs b/apps/native/electron/webauthn-integration.cjs
new file mode 100644
index 00000000..630523fe
--- /dev/null
+++ b/apps/native/electron/webauthn-integration.cjs
@@ -0,0 +1,129 @@
+// Real Chromium -> session -> BrowserTabs -> native-dialog adapter regression (#900).
+// Reference: Electron v44.2.0 webauthn-select-account-listener-throws fixture.
+// This entrypoint is deliberately hidden even if the caller opted into GUI tests.
+process.env.GRAFF_ELECTRON_FOREGROUND = '0';
+process.env.GRAFF_TEST_FOREGROUND = '0';
+process.env.GRAFF_ELECTRON_VISIBLE = '0';
+const desktop = require('./test-desktop.cjs');
+const { app, dialog, webContents } = require('electron');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const http = require('node:http');
+const { BrowserTabs } = require('./browser-tabs.cjs');
+const temp = process.argv[2];
+if (!temp) throw Error('Run through scripts/test-webauthn.mjs to isolate and clean up the browser profile.');
+app.setPath('userData', path.join(temp, 'profile'));
+app.commandLine.appendSwitch('disable-background-networking');
+let browser, win, server, wc, lastAccounts, dialogCalls = 0, events = 0;
+let respond = () => ({ response: 1 });
+const originalDialog = dialog.showMessageBox;
+// Replace the native boundary before any WebAuthn operation; never open a dialog.
+dialog.showMessageBox = async (owner, options) => {
+ dialogCalls++;
+ assert.equal(owner, win);
+ assert.equal(options.title, 'Choose a passkey');
+ assert.equal(options.cancelId, 0);
+ assert.equal(options.buttons.length, lastAccounts.length + 1);
+ desktop.assertSafe();
+ return respond(options);
+};
+let finished = false;
+const deadline = setTimeout(() => finish(Error('WebAuthn integration exceeded 45 seconds')), 45000);
+function finish(error) {
+ if (finished) return;
+ finished = true;
+ clearTimeout(deadline);
+ try { browser?.closeAll(); desktop.assertSafe(); desktop.cleanup(); } catch (e) { error ||= e; }
+ dialog.showMessageBox = originalDialog;
+ server?.close();
+ if (error) console.error(error);
+ app.exit(error ? 1 : 0);
+}
+const get = () => wc.executeJavaScript(`navigator.credentials.get({publicKey:{
+ challenge:crypto.getRandomValues(new Uint8Array(32)),rpId:'localhost',userVerification:'required',timeout:10000
+}}).then(c=>({ok:true,id:c.id,userHandle:Array.from(new Uint8Array(c.response.userHandle))}),e=>({ok:false,name:e.name}))`);
+app.whenReady().then(async () => {
+ win = desktop.createWindow({ width: 800, height: 600, webPreferences: { sandbox: true } });
+ assert.equal(win.isFocusable(), false);
+ server = http.createServer((_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end('<!doctype html><title>Offline passkey fixture</title>');
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const origin = `http://localhost:${server.address().port}`;
+ browser = new BrowserTabs(win, () => {});
+ browser.session.webRequest.onBeforeRequest((details, callback) => {
+ callback({ cancel: !details.url.startsWith(`${origin}/`) });
+ });
+ // Observe, but do not invoke or replace, the real production listener/callback.
+ browser.session.prependListener('select-webauthn-account', (_event, details) => {
+ events++;
+ assert.equal(details.relyingPartyId, 'localhost');
+ assert.equal(webContents.fromFrame(details.frame), wc);
+ lastAccounts = details.accounts;
+ });
+ browser.setBounds('passkeys', { x: 0, y: 0, width: 800, height: 600 });
+ await browser.navigate('passkeys', `${origin}/`);
+ wc = browser.tabs.get('passkeys').view.webContents;
+ await desktop.focusTestPage(wc);
+ await wc.debugger.sendCommand('WebAuthn.enable');
+ const { authenticatorId } = await wc.debugger.sendCommand('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,
+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+ });
+ const ids = [];
+ for (const [index, name] of ['alice', 'bob'].entries()) {
+ const created = await wc.executeJavaScript(`navigator.credentials.create({publicKey:{
+ challenge:crypto.getRandomValues(new Uint8Array(32)),rp:{id:'localhost',name:'Offline fixture'},
+ user:{id:new Uint8Array([${index + 1}]),name:'${name}',displayName:'${name}'},
+ pubKeyCredParams:[{type:'public-key',alg:-7}],
+ authenticatorSelection:{residentKey:'required',userVerification:'required'},timeout:10000
+ }}).then(c=>({ok:true,id:c.id}),e=>({ok:false,name:e.name}))`);
+ assert.equal(created.ok, true, JSON.stringify(created));
+ ids.push(created.id);
+ if (index === 0) {
+ const first = await get();
+ assert.equal(first.ok, true, JSON.stringify(first));
+ assert.equal(first.id, ids[0]);
+ assert.deepEqual(first.userHandle, [1]);
+ }
+ }
+ const stored = await wc.debugger.sendCommand('WebAuthn.getCredentials', { authenticatorId });
+ assert.equal(stored.credentials.length, 2);
+ assert.ok(stored.credentials.every(c => c.isResidentCredential));
+ const before = dialogCalls;
+ respond = () => ({ response: 2 });
+ const selected = await get();
+ assert.equal(dialogCalls, before + 1, 'Must dispatch through BrowserTabs account chooser');
+ assert.equal(lastAccounts.length, 2);
+ assert.equal(selected.ok, true, JSON.stringify(selected));
+ const selectedId = lastAccounts[1].credentialId;
+ assert.equal(selected.id, selectedId, 'Second dialog account must be the returned credential');
+ assert.ok(ids.includes(selected.id));
+ respond = () => ({ response: 0 });
+ assert.deepEqual(await get(), { ok: false, name: 'NotAllowedError' });
+ assert.equal(dialogCalls, before + 2);
+ // Real tab visibility gate: no adapter call is allowed for a hidden tab's frame.
+ browser.hide('passkeys');
+ assert.deepEqual(await get(), { ok: false, name: 'NotAllowedError' });
+ assert.equal(dialogCalls, before + 2);
+ browser.attach(browser.tabs.get('passkeys'));
+ // Same-document navigation keeps the JS promise alive while exercising the
+ // production did-start-navigation abort listener and stale-choice rejection.
+ let opened;
+ const opening = new Promise(resolve => { opened = resolve; });
+ respond = options => new Promise(resolve => {
+ options.signal.addEventListener('abort', () => resolve({ response: 2 }), { once: true });
+ opened();
+ });
+ const pending = get();
+ await opening;
+ await wc.executeJavaScript("location.hash = 'dismiss'; void 0");
+ assert.deepEqual(await pending, { ok: false, name: 'NotAllowedError' });
+ assert.equal(dialogCalls, before + 3);
+ await wc.debugger.sendCommand('WebAuthn.removeVirtualAuthenticator', { authenticatorId });
+ console.log('PASS WebAuthn integration', JSON.stringify({ electron: process.versions.electron,
+ residentCredentials: stored.credentials.length, events, dialogCalls,
+ checks: ['create', 'single-account get', 'second-account selection', 'cancel', 'hidden-tab rejection', 'navigation cancellation'],
+ desktop: desktop.assertSafe() }));
+}).then(() => finish()).catch(finish);
diff --git a/apps/native/electron/webauthn-profile.cjs b/apps/native/electron/webauthn-profile.cjs
new file mode 100644
index 00000000..82427a7c
--- /dev/null
+++ b/apps/native/electron/webauthn-profile.cjs
@@ -0,0 +1,30 @@
+const { execFileSync } = require('node:child_process');
+const { createRequire } = require('node:module');
+const plist = createRequire(require.resolve('@electron/osx-sign'))('plist');
+
+function readProfile(file) {
+ if (!file) throw Error('Set GRAFF_WEBAUTHN_PROFILE to a macOS provisioning profile authorizing the app and keychain group.');
+ return plist.parse(execFileSync('/usr/bin/security', ['cms', '-D', '-i', file],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }));
+}
+
+function allows(pattern, value) {
+ return typeof pattern === 'string' && (pattern === value ||
+ (pattern.endsWith('*') && !pattern.slice(0, -1).includes('*') && value.startsWith(pattern.slice(0, -1))));
+}
+
+function profileEntitlements(profile, config, now = Date.now()) {
+ const group = config.keychainAccessGroup;
+ const team = group.slice(0, group.indexOf('.'));
+ const appId = group.slice(0, -'.webauthn'.length);
+ const entitlements = profile?.Entitlements;
+ if (!profile?.Platform?.includes('OSX') || !profile.TeamIdentifier?.includes(team) ||
+ !(new Date(profile.ExpirationDate).getTime() > now) ||
+ !allows(entitlements?.['com.apple.application-identifier'], appId) ||
+ !entitlements?.['keychain-access-groups']?.some(value => allows(value, group))) {
+ throw Error('The provisioning profile must be unexpired and authorize this macOS app, signing team, and WebAuthn keychain group.');
+ }
+ return { 'com.apple.application-identifier': appId };
+}
+
+module.exports = { readProfile, profileEntitlements };
diff --git a/apps/native/electron/webauthn-profile.test.cjs b/apps/native/electron/webauthn-profile.test.cjs
new file mode 100644
index 00000000..64bc46b7
--- /dev/null
+++ b/apps/native/electron/webauthn-profile.test.cjs
@@ -0,0 +1,85 @@
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const { readProfile, profileEntitlements } = require('./webauthn-profile.cjs');
+
+const config = { keychainAccessGroup: 'ABCDE12345.org.example.fixture.webauthn' };
+const appId = 'ABCDE12345.org.example.fixture';
+const now = Date.parse('2030-01-01T00:00:00Z');
+
+function fixture() {
+ return {
+ Platform: ['OSX'],
+ TeamIdentifier: ['ABCDE12345'],
+ ExpirationDate: new Date('2099-01-01'),
+ Entitlements: {
+ 'com.apple.application-identifier': appId,
+ 'keychain-access-groups': ['ABCDE12345.*'],
+ },
+ };
+}
+
+function authorize(profile) {
+ return profileEntitlements(profile, config, now);
+}
+
+for (const [name, application, groups] of [
+ ['fixture team wildcard group', appId, ['ABCDE12345.*']],
+ ['exact permissions', appId, [config.keychainAccessGroup]],
+ ['trailing wildcard permissions', 'ABCDE12345.org.example.*', ['ABCDE12345.org.example.fixture.*']],
+ ['matching group among unrelated groups', appId, ['ABCDE12345.org.example.other', config.keychainAccessGroup]],
+]) {
+ test(`authorizes ${name} and returns the concrete application identifier`, () => {
+ const profile = fixture();
+ profile.Entitlements['com.apple.application-identifier'] = application;
+ profile.Entitlements['keychain-access-groups'] = groups;
+ assert.deepEqual(authorize(profile), { 'com.apple.application-identifier': appId });
+ });
+}
+
+for (const [name, change] of [
+ ['wrong team', p => { p.TeamIdentifier = ['ZZZZZ99999']; }],
+ ['missing team', p => { delete p.TeamIdentifier; }],
+ ['wrong application', p => { p.Entitlements['com.apple.application-identifier'] = 'ABCDE12345.org.example.other'; }],
+ ['application wildcard with wrong prefix', p => { p.Entitlements['com.apple.application-identifier'] = 'ABCDE12345.org.example.other.*'; }],
+ ['missing application', p => { delete p.Entitlements['com.apple.application-identifier']; }],
+ ['wrong keychain group', p => { p.Entitlements['keychain-access-groups'] = ['ABCDE12345.org.example.other.webauthn']; }],
+ ['keychain wildcard with wrong team prefix', p => { p.Entitlements['keychain-access-groups'] = ['ZZZZZ99999.*']; }],
+ ['missing keychain groups', p => { delete p.Entitlements['keychain-access-groups']; }],
+ ['empty keychain groups', p => { p.Entitlements['keychain-access-groups'] = []; }],
+ ['missing entitlements', p => { delete p.Entitlements; }],
+ ['non-mac platform', p => { p.Platform = ['iOS']; }],
+ ['missing platform', p => { delete p.Platform; }],
+ ['expired profile', p => { p.ExpirationDate = new Date(now - 1); }],
+ ['expiration exactly now', p => { p.ExpirationDate = new Date(now); }],
+ ['invalid expiration string', p => { p.ExpirationDate = 'not-a-date'; }],
+ ['invalid Date object', p => { p.ExpirationDate = new Date(NaN); }],
+ ['missing expiration', p => { delete p.ExpirationDate; }],
+ ['interior application wildcard', p => { p.Entitlements['com.apple.application-identifier'] = 'ABCDE12345.org.*.fixture'; }],
+ ['interior and trailing application wildcards', p => { p.Entitlements['com.apple.application-identifier'] = 'ABCDE12345.*.fixture*'; }],
+ ['interior keychain wildcard', p => { p.Entitlements['keychain-access-groups'] = ['ABCDE12345.org.*.webauthn']; }],
+ ['interior and trailing keychain wildcards', p => { p.Entitlements['keychain-access-groups'] = ['ABCDE12345.*.fixture.*']; }],
+]) {
+ test(`rejects ${name}`, () => {
+ const profile = fixture();
+ change(profile);
+ assert.throws(() => authorize(profile));
+ });
+}
+
+test('accepts a profile until its expiration boundary', () => {
+ const profile = fixture();
+ profile.ExpirationDate = new Date(now + 1);
+ assert.deepEqual(authorize(profile), { 'com.apple.application-identifier': appId });
+});
+
+test('rejects missing profiles', () => {
+ for (const profile of [undefined, null, {}]) {
+ assert.throws(() => authorize(profile));
+ }
+});
+
+test('readProfile rejects a missing path without invoking security', () => {
+ for (const file of [undefined, null, '']) {
+ assert.throws(() => readProfile(file), /GRAFF_WEBAUTHN_PROFILE/);
+ }
+});
diff --git a/apps/native/electron/webauthn-signing.cjs b/apps/native/electron/webauthn-signing.cjs
new file mode 100644
index 00000000..2c8558f7
--- /dev/null
+++ b/apps/native/electron/webauthn-signing.cjs
@@ -0,0 +1,91 @@
+const { execFileSync } = require('node:child_process');
+const fs = require('node:fs/promises');
+const os = require('node:os');
+const path = require('node:path');
+const { readProfile, profileEntitlements } = require('./webauthn-profile.cjs');
+
+function signingConfig(identity, explicitTeam, bundleId) {
+ const team = explicitTeam !== undefined
+ ? explicitTeam
+ : /^Developer ID Application: [^\r\n]+ \(([A-Z0-9]{10})\)$(?![\s\S])/.exec(identity)?.[1];
+ if (typeof team !== 'string' || !/^[A-Z0-9]{10}$(?![\s\S])/.test(team)) {
+ throw new Error('A valid signing team is required; set GRAFF_SIGN_TEAM_ID for a hash identity.');
+ }
+ if (typeof bundleId !== 'string' || !/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*$(?![\s\S])/.test(bundleId)) {
+ throw new Error('The app must have a valid CFBundleIdentifier.');
+ }
+ return { keychainAccessGroup: `${team}.${bundleId}.webauthn` };
+}
+
+function optionsForFile(app, config, applicationEntitlements = {}) {
+ app = path.resolve(app);
+ return (file) => {
+ file = path.resolve(file);
+ const main = file === app;
+ const bun = file.endsWith('/Resources/bun');
+ const jit = bun || main || file.endsWith('.app') || file.includes('/Electron Framework.framework/');
+ const entitlements = {};
+ if (jit) entitlements['com.apple.security.cs.allow-jit'] = true;
+ if (bun) entitlements['com.apple.security.cs.allow-unsigned-executable-memory'] = true;
+ if (main) Object.assign(entitlements, applicationEntitlements, { 'keychain-access-groups': [config.keychainAccessGroup] });
+ return { hardenedRuntime: true, entitlements };
+ };
+}
+
+// osx-sign 2.7 accepts paths or arrays of boolean keys, not entitlement objects.
+// Serialize our dictionary to a temporary plist to retain array-valued groups.
+function entitlementsPlist(entitlements) {
+ const escape = (value) => value.replace(/[<>&"']/g, (char) => ({
+ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;',
+ })[char]);
+ const entries = Object.entries(entitlements).map(([key, value]) => {
+ const encoded = value === true ? '<true/>'
+ : typeof value === 'string' ? `<string>${escape(value)}</string>`
+ : Array.isArray(value) && value.every((item) => typeof item === 'string')
+ ? `<array>${value.map((item) => `<string>${escape(item)}</string>`).join('')}</array>`
+ : null;
+ if (encoded === null) throw new Error('Unsupported signing entitlement value.');
+ return `<key>${escape(key)}</key>${encoded}`;
+ }).join('');
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>${entries}</dict></plist>\n`;
+}
+
+async function signBundle({ app, identity, teamId, profilePath, sign, readProvisioningProfile = readProfile, readBundleId = (bundle) =>
+ execFileSync('/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', path.join(bundle, 'Contents', 'Info.plist')],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).replace(/\r?\n$/, '') }) {
+ if (!app || !identity) throw new Error('Provide an app path and GRAFF_SIGN_IDENTITY.');
+ app = path.resolve(app);
+ const config = signingConfig(identity, teamId, readBundleId(app));
+ const applicationEntitlements = profileEntitlements(readProvisioningProfile(profilePath), config);
+ const fileOptions = optionsForFile(app, config, applicationEntitlements);
+ const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-sign-entitlements-'));
+ try {
+ const paths = new Map();
+ // Precompute the four entitlement policies; optionsForFile must be synchronous.
+ for (const file of [app, `${app}/Contents/Resources/bun`, `${app}/Contents/Frameworks/Helper.app`, `${app}/Contents/Resources/other`]) {
+ const entitlements = fileOptions(file).entitlements;
+ const key = JSON.stringify(entitlements);
+ if (!paths.has(key)) {
+ const plistPath = path.join(temporary, `${paths.size}.plist`);
+ await fs.writeFile(plistPath, entitlementsPlist(entitlements));
+ paths.set(key, plistPath);
+ }
+ }
+ // osx-sign's automatic embedding keeps stale profiles; replace with the one validated above.
+ await fs.copyFile(profilePath, path.join(app, 'Contents', 'embedded.provisionprofile'));
+ await fs.writeFile(path.join(app, 'Contents', 'Resources', 'webauthn.json'), `${JSON.stringify(config)}\n`);
+ await sign({
+ app, platform: 'darwin', type: 'distribution', identity,
+ preAutoEntitlements: false, preEmbedProvisioningProfile: false,
+ provisioningProfile: path.resolve(profilePath),
+ optionsForFile(file) {
+ const options = fileOptions(file);
+ return { ...options, entitlements: paths.get(JSON.stringify(options.entitlements)) };
+ },
+ });
+ } finally {
+ await fs.rm(temporary, { recursive: true, force: true });
+ }
+}
+
+module.exports = { signingConfig, optionsForFile, entitlementsPlist, signBundle };
diff --git a/apps/native/electron/webauthn-signing.test.cjs b/apps/native/electron/webauthn-signing.test.cjs
new file mode 100644
index 00000000..f0d0805b
--- /dev/null
+++ b/apps/native/electron/webauthn-signing.test.cjs
@@ -0,0 +1,112 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs/promises');
+const os = require('node:os');
+const path = require('node:path');
+const { createRequire } = require('node:module');
+const { execFileSync } = require('node:child_process');
+const { signingConfig, optionsForFile, signBundle } = require('./webauthn-signing.cjs');
+const requireSigner = createRequire(require.resolve('@electron/osx-sign'));
+const plist = requireSigner('plist');
+const identity = 'Developer ID Application: Test Fixture (ABCDE12345)';
+const bundleId = 'org.example.fixture';
+const profile = appId => ({ Platform: ['OSX'], TeamIdentifier: ['ABCDE12345'], ExpirationDate: new Date('2099-01-01'),
+ Entitlements: { 'com.apple.application-identifier': `ABCDE12345.${appId}`, 'keychain-access-groups': ['ABCDE12345.*'] } });
+
+test('team derives only from an anchored Developer ID Application identity or explicit valid team', () => {
+ assert.deepEqual(signingConfig(identity, undefined, bundleId), { keychainAccessGroup: 'ABCDE12345.org.example.fixture.webauthn' });
+ assert.equal(signingConfig('a'.repeat(40), 'ZYXWV98765', bundleId).keychainAccessGroup, 'ZYXWV98765.org.example.fixture.webauthn');
+ for (const value of [undefined, '', 'a'.repeat(40), 'Other: Fixture (ABCDE12345)', `${identity} trailing`, `${identity}\n`, 'prefix ' + identity]) {
+ assert.throws(() => signingConfig(value, undefined, bundleId), /valid signing team/);
+ }
+ for (const team of ['', 'short', 'abcde12345', 'ABCDE12345\n', 'ABCDE1234*']) {
+ assert.throws(() => signingConfig(identity, team, bundleId), /valid signing team/);
+ }
+ for (const bundle of ['', undefined, 'org..fixture', '.fixture', 'org.fixture.', 'org_fixture', 'org.fixture\n', 'org.*', 'org/fixture']) {
+ assert.throws(() => signingConfig(identity, undefined, bundle), /CFBundleIdentifier/);
+ }
+});
+
+test('only main app gets keychain access; existing JIT and Bun policies stay exact', () => {
+ const app = path.resolve('Fixture.app');
+ const config = signingConfig(identity, undefined, bundleId);
+ const options = optionsForFile(app, config);
+ const jit = { 'com.apple.security.cs.allow-jit': true };
+ const cases = [
+ [app, { ...jit, 'keychain-access-groups': [config.keychainAccessGroup] }],
+ [app + '/', { ...jit, 'keychain-access-groups': [config.keychainAccessGroup] }],
+ [`${app}/Contents/Resources/bun`, { ...jit, 'com.apple.security.cs.allow-unsigned-executable-memory': true }],
+ [`${app}/Contents/Frameworks/Helper.app`, jit],
+ [`${app}/Contents/Frameworks/Electron Framework.framework/Versions/A/Electron Framework`, jit],
+ [`${app}/Contents/Resources/tool`, {}],
+ [`${app}/Contents/Frameworks/library.dylib`, {}],
+ ];
+ for (const [file, entitlements] of cases) assert.deepEqual(options(file), { hardenedRuntime: true, entitlements });
+});
+
+for (const fails of [false, true]) test(`sign dispatch writes matching config and plist entitlements, cleans temporary files (failure=${fails})`, async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'webauthn-sign-test-'));
+ const app = path.join(root, 'Fixture.app');
+ const resources = path.join(app, 'Contents', 'Resources');
+ const entitlementPaths = [];
+ let calls = 0;
+ try {
+ await fs.mkdir(resources, { recursive: true });
+ await fs.writeFile(path.join(resources, 'webauthn.json'), '{"stale":true}');
+ const profilePath = path.join(root, 'fixture.provisionprofile');
+ await fs.writeFile(profilePath, 'fixture CMS bytes');
+ await fs.writeFile(path.join(app, 'Contents', 'embedded.provisionprofile'), 'stale profile');
+ const applicationEntitlements = { 'com.apple.application-identifier': `ABCDE12345.${bundleId}` };
+ const work = signBundle({ app, identity, profilePath, readProvisioningProfile: () => profile(bundleId), readBundleId: (actual) => {
+ assert.equal(actual, app);
+ return bundleId;
+ }, sign: async (options) => {
+ calls++;
+ assert.equal(options.preAutoEntitlements, false);
+ assert.equal(options.preEmbedProvisioningProfile, false);
+ assert.equal(options.provisioningProfile, profilePath);
+ assert.equal(await fs.readFile(path.join(app, 'Contents', 'embedded.provisionprofile'), 'utf8'), 'fixture CMS bytes');
+ assert.equal(options.platform, 'darwin');
+ assert.equal(options.type, 'distribution');
+ const config = JSON.parse(await fs.readFile(path.join(resources, 'webauthn.json'), 'utf8'));
+ assert.deepEqual(config, signingConfig(identity, undefined, bundleId));
+ for (const file of [app, `${resources}/bun`, `${app}/Contents/Frameworks/Helper.app`, `${resources}/tool`]) {
+ const result = options.optionsForFile(file);
+ assert.equal(result.hardenedRuntime, true);
+ assert.equal(typeof result.entitlements, 'string');
+ entitlementPaths.push(result.entitlements);
+ assert.deepEqual(plist.parse(await fs.readFile(result.entitlements, 'utf8')), optionsForFile(app, config, applicationEntitlements)(file).entitlements);
+ }
+ if (fails) throw new Error('fixture failure');
+ } });
+ if (fails) await assert.rejects(work, /fixture failure/);
+ else await work;
+ assert.equal(calls, 1);
+ for (const file of entitlementPaths) await assert.rejects(fs.access(file), { code: 'ENOENT' });
+ } finally { await fs.rm(root, { recursive: true, force: true }); }
+});
+
+test('invalid metadata fails before writing config or invoking signer', async () => {
+ let called = false;
+ await assert.rejects(signBundle({ app: 'Fixture.app', identity, teamId: '', readBundleId: () => bundleId, sign: () => { called = true; } }), /valid signing team/);
+ await assert.rejects(signBundle({ app: 'Fixture.app', identity, readBundleId: () => 'bad/bundle', sign: () => { called = true; } }), /CFBundleIdentifier/);
+ await assert.rejects(signBundle({ app: 'Fixture.app', identity, readBundleId: () => bundleId, sign: () => { called = true; } }), /GRAFF_WEBAUTHN_PROFILE/);
+ assert.equal(called, false);
+});
+
+test('default reader obtains actual bundle identifier through PlistBuddy', { skip: process.platform !== 'darwin' }, async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'webauthn-plist-test-'));
+ const app = path.join(root, 'Fixture.app');
+ try {
+ await fs.mkdir(path.join(app, 'Contents', 'Resources'), { recursive: true });
+ await fs.writeFile(path.join(app, 'Contents', 'Info.plist'), plist.build({ CFBundleIdentifier: 'org.example.actual' }));
+ const profilePath = path.join(root, 'fixture.provisionprofile');
+ await fs.writeFile(profilePath, 'fixture CMS bytes');
+ await signBundle({ app, identity, profilePath, readProvisioningProfile: () => profile('org.example.actual'), sign: async (options) => {
+ const config = JSON.parse(await fs.readFile(path.join(app, 'Contents', 'Resources', 'webauthn.json'), 'utf8'));
+ assert.equal(config.keychainAccessGroup, 'ABCDE12345.org.example.actual.webauthn');
+ const group = execFileSync('/usr/libexec/PlistBuddy', ['-c', 'Print :keychain-access-groups:0', options.optionsForFile(app).entitlements], { encoding: 'utf8' }).trim();
+ assert.equal(group, config.keychainAccessGroup);
+ } });
+ } finally { await fs.rm(root, { recursive: true, force: true }); }
+});
diff --git a/apps/native/electron/webauthn.cjs b/apps/native/electron/webauthn.cjs
new file mode 100644
index 00000000..fb666293
--- /dev/null
+++ b/apps/native/electron/webauthn.cjs
@@ -0,0 +1,69 @@
+const fs = require('node:fs');
+const path = require('node:path');
+
+function configureWebAuthn(app, resources, platform = process.platform) {
+ if (platform !== 'darwin' || !app.isPackaged || typeof app.configureWebAuthn !== 'function') return false;
+ try {
+ const { keychainAccessGroup } = JSON.parse(fs.readFileSync(path.join(resources, 'webauthn.json'), 'utf8'));
+ if (typeof keychainAccessGroup !== 'string' || !/^[A-Z0-9]{10}\.[A-Za-z0-9.-]+\.webauthn$/.test(keychainAccessGroup)) return false;
+ app.configureWebAuthn({ touchID: { keychainAccessGroup, promptReason: 'sign in to $1' } });
+ return true;
+ } catch { return false; } // Development/unsigned bundles have no platform credentials.
+}
+
+const clean = text => String(text || '').replace(/[\p{Cc}\p{Cf}]/gu, '').slice(0, 160);
+
+function installAccountSelection(session, { dialog, ownerForFrame }) {
+ session.on('select-webauthn-account', (_event, details, callback) => {
+ void (async () => {
+ let selected, owner, cancel;
+ const controller = new AbortController();
+ try {
+ owner = ownerForFrame(details.frame);
+ if (!owner || owner.window.isDestroyed() || owner.contents.isDestroyed()) return;
+ const accounts = details.accounts;
+ if (!Array.isArray(accounts) || !accounts.length) return;
+ cancel = () => controller.abort();
+ owner.contents.on('did-start-navigation', cancel);
+ owner.contents.on('destroyed', cancel);
+ owner.contents.on('graff-webauthn-cancel', cancel);
+ owner.window.on('closed', cancel);
+ const { response } = await dialog.showMessageBox(owner.window, {
+ type: 'question', title: 'Choose a passkey',
+ message: `Sign in to ${clean(details.relyingPartyId)}`,
+ detail: 'Choose the account to share with this site. Cancel to use another sign-in method.',
+ buttons: ['Cancel', ...accounts.map((account, i) => `${i + 1}. ${clean(account.displayName || account.name) || 'Account'}${account.displayName && account.name ? ` (${clean(account.name)})` : ''}`)],
+ defaultId: 0, cancelId: 0, noLink: true, signal: controller.signal,
+ });
+ if (!controller.signal.aborted && ownerForFrame(details.frame)?.contents === owner.contents &&
+ Number.isInteger(response) && response > 0 && response <= accounts.length) selected = accounts[response - 1].credentialId;
+ } catch { /* Fail closed, including a dismissed or unavailable native dialog. */ }
+ finally {
+ if (cancel) {
+ owner.contents.removeListener('did-start-navigation', cancel);
+ owner.contents.removeListener('destroyed', cancel);
+ owner.contents.removeListener('graff-webauthn-cancel', cancel);
+ owner.window.removeListener('closed', cancel);
+ }
+ callback(selected);
+ }
+ })();
+ });
+}
+
+async function showPasskeyHelp({ window, browser, dialog, shell, configured }) {
+ const contents = browser.tabs.get(browser.visible)?.view?.webContents;
+ let url;
+ try {
+ const candidate = new URL(contents?.getURL());
+ if (['http:', 'https:'].includes(candidate.protocol) && !candidate.username && !candidate.password) url = candidate.href;
+ } catch { /* No active web page. */ }
+ const { response } = await dialog.showMessageBox(window, {
+ type: 'info', title: 'Browser passkeys', message: 'Having trouble signing in with a passkey?',
+ detail: `${configured ? 'This signed app is configured for device-bound Touch ID passkeys on supported Macs.' : 'Touch ID passkeys are not configured in this build. Use a signed distribution on a supported Mac.'} Existing iCloud Keychain passkeys are not available here. Use the site’s password or another sign-in method, or open the page in your default browser. Signing in there does not sign you in here.`,
+ buttons: url ? ['Close', 'Open page in default browser'] : ['Close'], defaultId: 0, cancelId: 0, noLink: true,
+ });
+ if (response === 1 && url && !window.isDestroyed()) await shell.openExternal(url);
+}
+
+module.exports = { configureWebAuthn, installAccountSelection, showPasskeyHelp };
diff --git a/apps/native/electron/webauthn.test.cjs b/apps/native/electron/webauthn.test.cjs
new file mode 100644
index 00000000..37b40fd0
--- /dev/null
+++ b/apps/native/electron/webauthn.test.cjs
@@ -0,0 +1,110 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { EventEmitter } = require('node:events');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { configureWebAuthn, installAccountSelection, showPasskeyHelp } = require('./webauthn.cjs');
+
+const group = 'ABCDEFGHIJ.dev.example.app.webauthn';
+test('startup configures only supported packaged builds from the signed resource', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'webauthn-config-'));
+ try {
+ const calls = [], app = { isPackaged: true, configureWebAuthn: options => calls.push(options) };
+ assert.equal(configureWebAuthn(app, dir, 'darwin'), false);
+ fs.writeFileSync(path.join(dir, 'webauthn.json'), JSON.stringify({ keychainAccessGroup: group }));
+ assert.equal(configureWebAuthn(app, dir, 'darwin'), true);
+ assert.deepEqual(calls, [{ touchID: { keychainAccessGroup: group, promptReason: 'sign in to $1' } }]);
+ for (const platform of ['linux', 'win32']) assert.equal(configureWebAuthn(app, dir, platform), false);
+ assert.equal(configureWebAuthn({ ...app, isPackaged: false }, dir, 'darwin'), false);
+ assert.equal(configureWebAuthn({ isPackaged: true }, dir, 'darwin'), false);
+ assert.equal(configureWebAuthn({ ...app, configureWebAuthn() { throw Error('unavailable'); } }, dir, 'darwin'), false);
+ for (const payload of ['{', '{}', 'null', '{"keychainAccessGroup":"invalid"}']) {
+ fs.writeFileSync(path.join(dir, 'webauthn.json'), payload);
+ assert.equal(configureWebAuthn(app, dir, 'darwin'), false);
+ }
+ assert.equal(calls.length, 1);
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+});
+
+function fixture(showMessageBox, owns = true) {
+ const session = new EventEmitter(), frame = {};
+ const contents = Object.assign(new EventEmitter(), { isDestroyed: () => false });
+ const window = Object.assign(new EventEmitter(), { isDestroyed: () => false });
+ const owner = { contents, window };
+ installAccountSelection(session, { dialog: { showMessageBox }, ownerForFrame: f => owns && f === frame ? owner : null });
+ const accounts = [{ credentialId: 'alice', displayName: 'Alice', name: '[email protected]' }, { credentialId: 'bob', name: 'Bob' }];
+ let count = 0;
+ const request = (details = {}) => new Promise(resolve => session.emit('select-webauthn-account', {}, {
+ frame, relyingPartyId: 'example.test', accounts, ...details,
+ }, value => { count++; resolve(value); }));
+ return { request, contents, window, get count() { return count; } };
+}
+
+test('account selection requires an explicit choice and passes the credential ID', async () => {
+ const f = fixture(async (parent, options) => {
+ assert.equal(parent, f.window);
+ assert.equal(options.message, 'Sign in to example.test');
+ assert.deepEqual(options.buttons, ['Cancel', '1. Alice ([email protected])', '2. Bob']);
+ assert.equal(options.defaultId, 0); assert.equal(options.cancelId, 0);
+ return { response: 2 };
+ });
+ assert.equal(await f.request(), 'bob');
+ assert.equal(f.count, 1);
+ assert.equal(f.contents.eventNames().length, 0);
+ assert.equal(f.window.eventNames().length, 0);
+});
+
+test('cancel, invalid choice, empty accounts, foreign frames and dialog failures fail closed', async () => {
+ for (const response of [0, -1, 3, 1.5, undefined]) {
+ const f = fixture(async () => ({ response }));
+ assert.equal(await f.request(), undefined); assert.equal(f.count, 1);
+ }
+ const f = fixture(async () => { throw Error('dialog failed'); });
+ assert.equal(await f.request(), undefined); assert.equal(f.count, 1);
+ const foreign = fixture(() => assert.fail('must not prompt'), false);
+ assert.equal(await foreign.request(), undefined);
+ const empty = fixture(() => assert.fail('must not prompt'));
+ assert.equal(await empty.request({ accounts: [] }), undefined);
+});
+
+test('navigation, tab hiding, destruction and window closure abort selection once', async () => {
+ for (const event of ['did-start-navigation', 'graff-webauthn-cancel', 'destroyed', 'closed']) {
+ const f = fixture((_parent, options) => new Promise(resolve => {
+ options.signal.addEventListener('abort', () => resolve({ response: 1 }), { once: true });
+ }));
+ const pending = f.request();
+ (event === 'closed' ? f.window : f.contents).emit(event);
+ assert.equal(await pending, undefined); assert.equal(f.count, 1);
+ assert.equal(f.contents.eventNames().length, 0);
+ assert.equal(f.window.eventNames().length, 0);
+ }
+});
+
+test('fallback explains credential limitations and opens only after explicit consent', async () => {
+ const opened = [];
+ for (const configured of [true, false]) {
+ for (const response of [0, 1]) {
+ await showPasskeyHelp({ window: { isDestroyed: () => false }, configured,
+ browser: { visible: 'tab', tabs: new Map([['tab', { view: { webContents: { getURL: () => 'https://example.test/login' } } }]]) },
+ dialog: { showMessageBox: async (_parent, options) => {
+ assert.match(options.detail, /iCloud Keychain passkeys are not available/);
+ assert.match(options.detail, /Signing in there does not sign you in here/);
+ assert.match(options.detail, configured ? /device-bound/ : /not configured/);
+ return { response };
+ } }, shell: { openExternal: async url => opened.push(url) },
+ });
+ }
+ }
+ assert.deepEqual(opened, ['https://example.test/login', 'https://example.test/login']);
+});
+
+test('fallback rejects non-web URLs and embedded credentials', async () => {
+ for (const url of ['file:///tmp/test', 'javascript:alert(1)', 'https://user:[email protected]', 'about:blank']) {
+ await showPasskeyHelp({ window: { isDestroyed: () => false }, configured: false,
+ browser: { visible: 'tab', tabs: new Map([['tab', { view: { webContents: { getURL: () => url } } }]]) },
+ dialog: { showMessageBox: async (_parent, options) => { assert.deepEqual(options.buttons, ['Close']); return { response: 1 }; } },
+ shell: { openExternal: () => assert.fail('must not open') },
+ });
+ }
+});
diff --git a/apps/native/package.json b/apps/native/package.json
index 1e642be9..38413d1e 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -13,6 +13,7 @@
"test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/prompt-queue-resume.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts components/site/harness-split.test.ts",
"electron:build": "bash electron/build.sh",
"test:electron": "bun test electron/policy.test.cjs",
+ "test:webauthn": "node scripts/test-webauthn.mjs",
"test:desktop": "bun test lib ./electron/*.test.cjs",
"test:tab-drag": "GRAFF_VISUAL_SUITE=tab-drag bun scripts/test-visual.mjs",
"test:turns": "GRAFF_VISUAL_SUITE=turns bun scripts/test-visual.mjs",
diff --git a/apps/native/scripts/test-webauthn.mjs b/apps/native/scripts/test-webauthn.mjs
new file mode 100644
index 00000000..614ee692
--- /dev/null
+++ b/apps/native/scripts/test-webauthn.mjs
@@ -0,0 +1,11 @@
+// Never allow this offline regression to display windows or activate the app.
+process.env.GRAFF_ELECTRON_FOREGROUND = '0';
+process.env.GRAFF_TEST_FOREGROUND = '0';
+process.env.GRAFF_ELECTRON_VISIBLE = '0';
+const { mkdtemp, rm } = await import('node:fs/promises');
+const { tmpdir } = await import('node:os');
+const { join } = await import('node:path');
+const { runElectron } = await import('./test-electron.mjs');
+const profile = await mkdtemp(join(tmpdir(), 'graff-webauthn-'));
+try { await runElectron('electron/webauthn-integration.cjs', [profile]); }
+finally { await rm(profile, { recursive: true, force: true }); }
diff --git a/docs/adr/0111-desktop-passkeys-use-signed-device-credentials.md b/docs/adr/0111-desktop-passkeys-use-signed-device-credentials.md
new file mode 100644
index 00000000..a6d9e563
--- /dev/null
+++ b/docs/adr/0111-desktop-passkeys-use-signed-device-credentials.md
@@ -0,0 +1,46 @@
+# 0111. Desktop passkeys use signed device credentials
+
+Status: accepted
+
+## Context
+
+The embedded browser did not configure Electron's macOS WebAuthn authenticator.
+Platform requests therefore had no Touch ID integration, and signing supplied
+no credential keychain group. The pinned Electron API supports Secure Enclave
+credentials, not access to existing iCloud Keychain passkeys. Configuring it is
+not sufficient evidence that every stalled sign-in is fixed.
+
+## Decision
+
+The distribution signer derives one credential group from the signing team and
+actual bundle identifier, puts it in the main application's keychain entitlement,
+and writes the identical value to a signed resource. Startup configures Touch ID
+from that resource before browser creation. Development builds without it leave
+the authenticator disabled rather than inventing a signing identity.
+
+The signer requires and embeds a macOS provisioning profile authorizing the
+team, application identifier, and credential group, and includes the authorized
+application identifier in the main app's entitlements. A stale embedded profile
+is replaced, not silently retained. Supplying a keychain entitlement alone can
+pass `codesign --verify` while macOS refuses launch for lack of a matching
+profile; the build must not mistake signature integrity for authorization.
+
+The persistent browser session handles account selection through a parented
+native dialog. Only the visible owned browser page can prompt; cancellation,
+navigation, hiding, and destruction fail closed. No credential is silently chosen.
+The existing sandbox and general permission denial remain unchanged.
+
+An explicit Tools menu action explains device-bound credentials and offers to
+open the active web page in the default browser. It never automatically forwards
+a failed authentication request or implies that external login transfers a
+session back to Codegraff. We do not enable a different provider API or claim
+third-party iCloud credentials are accessible.
+
+## Consequences
+
+Signing team, bundle identifier, and browser partition must remain stable to
+retain credential access. Unsupported credentials still need another sign-in
+method. Automated virtual-authenticator checks establish request dispatch and
+selection behavior, not biometric or keychain access. Release support requires
+registration, persistence, authentication, and cancellation validation in the
+Developer ID-signed application on supported hardware.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8cb1e80b..4a344bd1 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -121,6 +121,7 @@ record only when you need the evidence or the edge cases.
| [0108](0108-browser-events-outrank-pending-snapshots.md) | Browser page-info events invalidate older pending IPC snapshots; a loaded page must not revert to loading. |
| [0109](0109-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. |
| [0110](0110-project-mcp-listing-opts-in-optional-servers.md) | Project MCP entries opt in optional servers; inherited extras still require opt-in, and startup consent applies to both. |
+| [0111](0111-desktop-passkeys-use-signed-device-credentials.md) | Desktop Touch ID uses matching signed keychain configuration; account choice is explicit and existing iCloud credentials need a fallback. |
## When to write one