-
Notifications
You must be signed in to change notification settings - Fork 465
feat(shared,ui): promote the Protect check runner to a public @clerk/shared/protect-check entry #9391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mwickett
wants to merge
1
commit into
main
Choose a base branch
from
mwickett/prot-855-extract-protect-check-runner
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+645
−226
Open
feat(shared,ui): promote the Protect check runner to a public @clerk/shared/protect-check entry #9391
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| export { executeProtectCheck } from '../../protect-check/executeProtectCheck'; | ||
| export type { ExecuteProtectCheckOptions } from '../../protect-check/executeProtectCheck'; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 👍 / 👎.