Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/protect-check-public-entry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/shared': minor
---

Add a public `@clerk/shared/protect-check` entry point for running Clerk Protect challenges outside the prebuilt components. It exposes `executeProtectCheck` (previously only reachable via the internal `@clerk/shared/internal/clerk-js/protectCheck` subpath, which remains as an alias) together with the lifecycle helpers the prebuilt components use: `executeProtectCheckWithTimeout`, `submitProtectCheckProof`, `isProtectCheckExpired`, and the `PROTECT_CHECK_ERROR_CODES` map.
5 changes: 5 additions & 0 deletions .changeset/protect-check-ui-refactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': patch
---

The Protect check cards now drive their challenge lifecycle through the shared helpers in `@clerk/shared/protect-check`. No behavioral changes.
10 changes: 10 additions & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@
"default": "./dist/keyless/index.js"
}
},
"./protect-check": {
"import": {
"types": "./dist/protect-check/index.d.mts",
"default": "./dist/protect-check/index.mjs"
},
"require": {
"types": "./dist/protect-check/index.d.ts",
"default": "./dist/protect-check/index.js"
}
},
"./utils": {
"import": {
"types": "./dist/utils/index.d.mts",
Expand Down
163 changes: 4 additions & 159 deletions packages/shared/src/internal/clerk-js/protectCheck.ts
Original file line number Diff line number Diff line change
@@ -1,159 +1,4 @@
import { ClerkRuntimeError } from '../../error';
import type { ProtectCheckResource } from '../../types';

export interface ExecuteProtectCheckOptions {
/**
* Host-provided visibility handshake, forwarded to the script verbatim as
* `setWidgetVisible` in the init payload. The script calls it right before revealing UI in
* the container (and with `false` once its widget is done); the returned promise resolves
* only after the host has applied the change to the DOM (e.g. removed its own loading
* spinner), so the script can sequence its reveal without a frame of overlap. A script that
* knows its widget is imminent may call it immediately to avoid a spinner flash. Scripts
* must treat the field as optional — older hosts don't provide it.
*/
setWidgetVisible?: (visible: boolean) => Promise<void>;
/**
* Signals that the caller no longer needs the proof token (component unmounted, user
* navigated away, etc.). When the signal aborts:
* - If the script has not yet been imported, `executeProtectCheck` rejects with
* `protect_check_aborted` without loading the script.
* - The signal is forwarded to the script as `{ signal }` in the second argument so
* cooperating SDKs can cancel any in-flight UI / network work.
* - Even if the script ignores the signal and resolves with a token, the helper
* re-checks `signal.aborted` after the await and rejects with `protect_check_aborted`
* so the caller never observes a "successful" abort.
*
* Scripts that don't honor the signal will continue to run; this is best-effort by design.
*/
signal?: AbortSignal;
}

interface ScriptInitOptions {
token: string;
uiHints?: Record<string, string>;
signal?: AbortSignal;
setWidgetVisible?: (visible: boolean) => Promise<void>;
}

type ScriptDefault = (container: HTMLDivElement, init: ScriptInitOptions) => Promise<string>;

/**
* Validates the `sdk_url` returned by the server before passing it to dynamic `import()`.
*
* Rejects:
* - Anything that fails URL parsing (relative paths, garbage strings)
* - Non-`https:` schemes — including `http:`, `data:`, `blob:`, `javascript:`. The server
* always returns an HTTPS URL, but the dynamic-import primitive accepts `data:`/`blob:`
* modules which would let a tampered response inject arbitrary code into the host page.
* - URLs containing credentials (`user:pass@host`) — phishing surface, no legitimate use.
*
* Throws `ClerkRuntimeError` with code `protect_check_invalid_sdk_url`. We deliberately do
* NOT silently strip an invalid `protect_check` from the resource: the gate must remain
* present so the user can't bypass it by manipulating the response. Fail-closed.
*/
function assertValidSdkUrl(sdkUrl: string): URL {
let parsed: URL;
try {
parsed = new URL(sdkUrl);
} catch {
throw new ClerkRuntimeError('Protect check sdk_url is not a valid URL', {
code: 'protect_check_invalid_sdk_url',
});
}
if (parsed.protocol !== 'https:') {
throw new ClerkRuntimeError('Protect check sdk_url must use HTTPS', {
code: 'protect_check_invalid_sdk_url',
});
}
if (parsed.username || parsed.password) {
throw new ClerkRuntimeError('Protect check sdk_url must not contain credentials', {
code: 'protect_check_invalid_sdk_url',
});
}
return parsed;
}

/**
* Loads the Protect challenge SDK from `protectCheck.sdkUrl`, hands it the container element
* and the spec-defined init payload (`token`, `uiHints`, `signal`), and returns the proof
* token the SDK produces.
*
* The SDK script must:
* - Be a valid ES module served over HTTPS
* - Have a default export of the shape `(container, { token, uiHints, signal }) => Promise<string>`
* - Honor the `signal` to abort any pending work (best-effort)
*
* Only the minimal fields (`token`, optional `ui_hints`) are surfaced to the script — the
* full sign-up/sign-in resource is intentionally NOT passed, to minimize the trust surface
* granted to third-party Protect scripts.
*
* Failure modes are surfaced as `ClerkRuntimeError` with one of:
* - `protect_check_invalid_sdk_url` — URL fails the safety checks above
* - `protect_check_aborted` — caller aborted before or during execution
* - `protect_check_script_load_failed` — network error, CSP block, or invalid module
* - `protect_check_invalid_script` — module loaded but no callable default export
* - `protect_check_execution_failed` — the script's default export threw
*/
export async function executeProtectCheck(
protectCheck: Pick<ProtectCheckResource, 'sdkUrl' | 'token' | 'uiHints'>,
container: HTMLDivElement,
options: ExecuteProtectCheckOptions = {},
): Promise<string> {
const { signal, setWidgetVisible } = options;
const { sdkUrl, token, uiHints } = protectCheck;

const validated = assertValidSdkUrl(sdkUrl);

if (signal?.aborted) {
throw new ClerkRuntimeError('Protect check aborted by caller', { code: 'protect_check_aborted' });
}

let mod: Record<string, unknown>;
try {
mod = await import(/* webpackIgnore: true */ validated.toString());
} catch {
// Surface a generic message and deliberately omit the original error: Chromium/Firefox embed
// the sdk_url in the dynamic-import failure text, which a tampered response could plant in the UI.
throw new ClerkRuntimeError(
'Protect check script failed to load. This is commonly caused by a Content Security ' +
'Policy that blocks the script origin (add it to your script-src directive), a ' +
'network error, or an invalid module.',
{ code: 'protect_check_script_load_failed' },
);
}

if (signal?.aborted) {
throw new ClerkRuntimeError('Protect check aborted by caller', { code: 'protect_check_aborted' });
}

if (typeof mod.default !== 'function') {
throw new ClerkRuntimeError('Protect check script does not export a default function', {
code: 'protect_check_invalid_script',
});
}

let proofToken: string;
try {
proofToken = await (mod.default as ScriptDefault)(container, { token, uiHints, signal, setWidgetVisible });
} catch (err) {
// Distinguish abort-induced rejections from genuine script errors: only relabel as
// `protect_check_aborted` when the error looks like an abort (`AbortError`), otherwise
// surface the script's actual failure so production diagnostics aren't masked.
const looksLikeAbort = err instanceof Error && err.name === 'AbortError';
if (signal?.aborted && looksLikeAbort) {
throw new ClerkRuntimeError('Protect check aborted by caller', { code: 'protect_check_aborted' });
}
const original = err instanceof Error ? err.message : String(err);
throw new ClerkRuntimeError(`Protect check script execution failed: ${original}`, {
code: 'protect_check_execution_failed',
});
}

// The script may have ignored the signal and resolved with a token after the abort fired.
// Re-check here so callers get a consistent contract: if you aborted, you never see a token.
if (signal?.aborted) {
throw new ClerkRuntimeError('Protect check aborted by caller', { code: 'protect_check_aborted' });
}

return proofToken;
}
// Moved to the public `@clerk/shared/protect-check` entry; this subpath is kept as an alias so
// existing imports keep resolving.
Comment on lines +1 to +2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove the comment that restates the alias

This comment only narrates that the following re-export preserves the existing subpath, which is already evident from the code. Remove it rather than adding a multi-line restatement; repository guidance permits comments only for critical, non-obvious rationale and requires them to be terse.

AGENTS.md reference: AGENTS.md:L13-L13

Useful? React with 👍 / 👎.

export { executeProtectCheck } from '../../protect-check/executeProtectCheck';
export type { ExecuteProtectCheckOptions } from '../../protect-check/executeProtectCheck';
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';

import type { ProtectCheckResource } from '@/types';

import { executeProtectCheck } from '../protectCheck';
import { executeProtectCheck } from '../executeProtectCheck';

const fakeContainer = (): HTMLDivElement => ({}) as HTMLDivElement;

Expand Down
Loading
Loading