Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); fix(electron,ui): Don't run passkey autofill as a modal prompt by jeremy-clerk · Pull Request #9500 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-pianos-smoke.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/electron': patch
'@clerk/ui': patch
---

Stop passkey autofill from opening a passkey prompt as soon as the sign-in form renders. Autofill now runs as a real background request when the window can service one (an `https` origin matching your RP ID), and is not attempted at all when it would route to the OS passkey dialog. Signing in with the explicit "Use passkey" action is unchanged.
2 changes: 2 additions & 0 deletions packages/electron/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -212,6 +212,8 @@ Passkey support works in two modes, selected automatically per request:
- **Renderer mode**: when your window loads content over `https://` from an origin that matches your passkey RP (Relying Party) ID, the renderer's built-in Chromium WebAuthn is used. Credentials are synced by the OS/browser ecosystem (Windows Hello works out of the box; Touch ID on macOS requires Electron ≥ 42 and [`app.configureWebAuthn`](https://www.electronjs.org/docs/latest/api/app#appconfigurewebauthnoptions-macos)).
- **Native mode**: when your window loads a local bundle (e.g. `scheme://host`), WebAuthn's origin checks reject the request, so the ceremony is routed over IPC to the main process and serviced by the OS WebAuthn APIs (AuthenticationServices on macOS, `webauthn.dll` on Windows) via the optional [`@clerk/electron-passkeys`](https://github.com/clerk/javascript/tree/main/packages/electron-passkeys) native module.

Passkey autofill relies on WebAuthn conditional mediation, which only the renderer can provide. In native mode passkeys are offered through the explicit "Use passkey" action instead; the sign-in form never opens a passkey prompt on its own.

### Setup

Native mode requires the optional native module:
Expand Down
72 changes: 72 additions & 0 deletions packages/electron/src/passkeys/__tests__/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,6 +294,60 @@ describe('createPasskeys', () => {
expect(bridge.get).toHaveBeenCalled();
expect(result.error).toBeNull();
});

it('forwards conditional UI to the renderer path', async () => {
stubEnvironment({ bridge: makeBridge() });
const rendererResult = { publicKeyCredential: {} as never, error: null };
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult);

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(webAuthnGetCredential).toHaveBeenCalledWith({
publicKeyOptions: expect.anything(),
conditionalUI: true,
});
expect(result).toBe(rendererResult);
});

it('aborts a conditional request instead of prompting through the native path', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(bridge.get).not.toHaveBeenCalled();
expect(webAuthnGetCredential).not.toHaveBeenCalled();
expect(result.publicKeyCredential).toBeNull();
expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('aborts a conditional request rather than reporting it as unsupported', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });

const result = await createPasskeys().get({ publicKeyOptions: requestOptions(), conditionalUI: true });

expect(result.error).toMatchObject({ code: 'passkey_operation_aborted' });
});

it('does not retry natively when a conditional renderer request fails', async () => {
const bridge = makeBridge();
stubEnvironment({ protocol: 'http:', hostname: 'localhost', bridge });
const rendererResult = {
publicKeyCredential: null,
error: Object.assign(new Error('The user agent does not support public key credentials.'), {
name: 'NotSupportedError',
}),
};
vi.mocked(webAuthnGetCredential).mockResolvedValue(rendererResult as never);

const result = await createPasskeys().get({
publicKeyOptions: requestOptionsForRpId('localhost'),
conditionalUI: true,
});

expect(bridge.get).not.toHaveBeenCalled();
expect(result).toBe(rendererResult);
});
});

describe('capability checks', () => {
Expand All@@ -308,6 +362,14 @@ describe('createPasskeys', () => {
expect(createPasskeys().isSupported()).toBe(true);
});

it('isSupported is false when every request would resolve to unsupported', () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app' });
expect(createPasskeys().isSupported()).toBe(false);

stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
expect(createPasskeys().isSupported()).toBe(true);
});

it('isAutoFillSupported is false in native mode', async () => {
stubEnvironment({ bridge: makeBridge() });

Expand All@@ -316,6 +378,16 @@ describe('createPasskeys', () => {
expect(isWebAuthnAutofillSupported).toHaveBeenCalledTimes(1);
});

it('isAutoFillSupported is false when requests cannot take the renderer path', async () => {
stubEnvironment({ protocol: 'clerk:', hostname: 'app', bridge: makeBridge() });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

stubEnvironment({ bridge: makeBridge({ electronMajor: 39 }) });
await expect(createPasskeys().isAutoFillSupported()).resolves.toBe(false);

expect(isWebAuthnAutofillSupported).not.toHaveBeenCalled();
});

it('isPlatformAuthenticatorSupported prefers native capabilities when available', async () => {
const bridge = makeBridge();
stubEnvironment({ bridge });
Expand Down
44 changes: 43 additions & 1 deletion packages/electron/src/passkeys/__tests__/strategy.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';

import type { StrategyEnv } from '../renderer/strategy';
import { decidePath, originSatisfiesRpId } from '../renderer/strategy';
import { canUseRendererPath, decidePath, originSatisfiesRpId } from '../renderer/strategy';

const RP_ID = 'example.com';

Expand DownExpand Up@@ -117,3 +117,45 @@ describe('decidePath', () => {
});
});
});

describe('canUseRendererPath', () => {
it('is false without renderer WebAuthn', () => {
expect(canUseRendererPath('auto', env({ hasWebAuthn: false }))).toBe(false);
expect(canUseRendererPath('renderer', env({ hasWebAuthn: false }))).toBe(false);
});

it('is false in native mode', () => {
expect(canUseRendererPath('native', env())).toBe(false);
});

it('is true in renderer mode regardless of origin', () => {
expect(canUseRendererPath('renderer', env({ protocol: 'app:', hostname: 'bundle' }))).toBe(true);
});

describe('auto mode', () => {
it.each([
['https:', 'example.com', true],
['http:', 'localhost', true],
['http:', '127.0.0.1', true],
['http:', '[::1]', true],
['http:', 'example.com', false],
['file:', '', false],
['app:', 'bundle', false],
['clerk:', 'app', false],
])('%s//%s -> %s', (protocol, hostname, expected) => {
expect(canUseRendererPath('auto', env({ protocol, hostname }))).toBe(expected);
});

it('is true for an https origin that does not match any particular RP ID', () => {
expect(canUseRendererPath('auto', env({ hostname: 'other.com' }))).toBe(true);
});

it('is false on macOS before Electron 42, where the request routes native', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39 }))).toBe(false);
});

it('is true on macOS before Electron 42 when native is unavailable', () => {
expect(canUseRendererPath('auto', env({ electronMajor: 39, nativeAvailable: false }))).toBe(true);
});
});
});
34 changes: 27 additions & 7 deletions packages/electron/src/passkeys/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ import { isWebAuthnAutofillSupported, isWebAuthnPlatformAuthenticatorSupported }

import { getPasskeyBridge, nativeCreateCredential, nativeGetCredential } from './renderer/native-bridge';
import type { PasskeyMode, StrategyEnv } from './renderer/strategy';
import { decidePath } from './renderer/strategy';
import { canUseRendererPath, decidePath } from './renderer/strategy';

export type { PasskeyMode, PasskeyPath, StrategyEnv } from './renderer/strategy';

Expand All@@ -29,6 +29,7 @@ export type PasskeySupport = {
) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAttestationResponse>>;
get: (args: {
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
conditionalUI?: boolean;
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>;
isSupported: () => boolean;
isAutoFillSupported: () => Promise<boolean>;
Expand DownExpand Up@@ -67,6 +68,14 @@ const unsupportedReturn = <T>(): CredentialReturn<T> =>
),
}) as CredentialReturn<T>;

const abortedReturn = <T>(): CredentialReturn<T> =>
({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Clerk: Conditional passkey requests require the renderer WebAuthn path.', {
code: 'passkey_operation_aborted',
}),
}) as CredentialReturn<T>;

const shouldRetryNativeAfterRendererError = (error: unknown): boolean => {
if (!error || typeof error !== 'object') {
return false;
Expand DownExpand Up@@ -102,19 +111,30 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
return result;
};

const get: PasskeySupport['get'] = async ({ publicKeyOptions }) => {
const get: PasskeySupport['get'] = async ({ publicKeyOptions, conditionalUI = false }) => {
const env = getEnv();
const path = decidePath(publicKeyOptions.rpId ?? '', mode, env);

// Conditional runs without user intent, don't fall through to opening a prompt.
if (conditionalUI && path !== 'renderer') {
return abortedReturn();
}

if (path === 'unsupported') {
return unsupportedReturn();
}
if (path === 'native') {
return nativeGetCredential(publicKeyOptions);
}

const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI: false });
if (result.error && shouldRetryNativeAfterRendererError(result.error) && mode === 'auto' && env.nativeAvailable) {
const result = await webAuthnGetCredential({ publicKeyOptions, conditionalUI });
if (
!conditionalUI &&
result.error &&
shouldRetryNativeAfterRendererError(result.error) &&
mode === 'auto' &&
env.nativeAvailable
) {
return nativeGetCredential(publicKeyOptions);
}
return result;
Expand All@@ -128,11 +148,11 @@ export function createPasskeys(options?: CreatePasskeysOptions): PasskeySupport
if (mode === 'native') {
return env.nativeAvailable;
}
return env.hasWebAuthn || env.nativeAvailable;
return canUseRendererPath(mode, env) || env.nativeAvailable;
};

const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = () => {
return mode === 'native' ? Promise.resolve(false) : isWebAuthnAutofillSupported();
const isAutoFillSupported: PasskeySupport['isAutoFillSupported'] = async () => {
return canUseRendererPath(mode, getEnv()) && isWebAuthnAutofillSupported();
};

const isPlatformAuthenticatorSupported: PasskeySupport['isPlatformAuthenticatorSupported'] = async () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/electron/src/passkeys/renderer/strategy.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,15 @@ export function originSatisfiesRpId(env: Pick<StrategyEnv, 'protocol' | 'hostnam
return env.hostname === rpId || env.hostname.endsWith(`.${rpId}`);
}

/** Whether the origin could satisfy some RP ID, without knowing which one is requested. */
function originCanSatisfyRpId(env: Pick<StrategyEnv, 'protocol' | 'hostname'>): boolean {
return env.protocol === 'https:' || (env.protocol === 'http:' && isLoopbackHostname(env.hostname));
}

function prefersNativeOnLegacyDarwin(env: StrategyEnv): boolean {
return env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable;
}

/**
* Prefer Chromium WebAuthn when the page origin can satisfy the RP ID.
* Local bundles and older macOS Electron builds use the native bridge when available.
Expand All@@ -44,11 +53,23 @@ export function decidePath(rpId: string, mode: PasskeyMode, env: StrategyEnv): P
}

if (env.hasWebAuthn && originSatisfiesRpId(env, rpId)) {
if (env.platform === 'darwin' && env.electronMajor > 0 && env.electronMajor < 42 && env.nativeAvailable) {
return 'native';
}
return 'renderer';
return prefersNativeOnLegacyDarwin(env) ? 'native' : 'renderer';
}

return env.nativeAvailable ? 'native' : 'unsupported';
}

/**
* Whether a request can take the renderer path, evaluated without RP ID.
* More loose than originSatisfiesRpId as we don't have an RP ID yet.
* This informs if Chromium *can* service a request rather than *will service*
*/
export function canUseRendererPath(mode: PasskeyMode, env: StrategyEnv): boolean {
if (!env.hasWebAuthn || mode === 'native') {
return false;
}
if (mode === 'renderer') {
return true;
}
return originCanSatisfyRpId(env) && !prefersNativeOnLegacyDarwin(env);
}
8 changes: 6 additions & 2 deletions packages/ui/src/components/SignIn/SignInStart.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,10 +60,12 @@ const useAutoFillPasskey = () => {
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const { userSettings } = useEnvironment();
const { passkeySettings, attributes } = userSettings;
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnAutofillSupported } = useClerk();

useEffect(() => {
async function runAutofillPasskey() {
const _isSupported = await isWebAuthnAutofillSupported();
const _isSupported = await (__internal_isWebAuthnAutofillSupported ?? isWebAuthnAutofillSupported)();
setIsSupported(_isSupported);
if (!_isSupported) {
return;
Expand DownExpand Up@@ -105,7 +107,9 @@ function SignInStartInternal(): JSX.Element {
const { isWebAuthnAutofillSupported } = useAutoFillPasskey();
const onSecondFactor = () => navigate('factor-two');
const authenticateWithPasskey = useHandleAuthenticateWithPasskey(onSecondFactor, 'protect-check');
const isWebSupported = isWebAuthnSupported();
// @ts-expect-error - This is not a public API
const { __internal_isWebAuthnSupported } = clerk;
const isWebSupported = (__internal_isWebAuthnSupported ?? isWebAuthnSupported)();

const onlyPhoneNumberInitialValueExists =
!!ctx.initialValues?.phoneNumber && !(ctx.initialValues.emailAddress || ctx.initialValues.username);
Expand Down
Loading
Loading