Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
9337717
feat(mosaic): run the Protect check in sign-up
austincalvelage Nov 19, 2026
9672eed
chore(repo): add an empty changeset for the sign-up Protect check
austincalvelage Nov 20, 2026
5298dfb
test(mosaic): wait for the code to send before ending sign-up Protect…
austincalvelage Nov 21, 2026
38496bb
fix(mosaic): run the sign-up Protect check through the shared runner
austincalvelage Nov 23, 2026
9a9cc34
test(mosaic): match the fake sign-up Protect check to clerk_go
austincalvelage Nov 23, 2026
545452d
fix(mosaic): reload the classic sign-up in the Protect runner
austincalvelage Nov 23, 2026
f1a057d
test(mosaic): assert the Protect continue screens, not the stored route
austincalvelage Nov 24, 2026
e387e08
refactor(mosaic): build the sign-up logo once and keep the Protect re…
austincalvelage Nov 24, 2026
87cf6a0
docs(mosaic): show the protectCheck slot in the sign-up usage
austincalvelage Nov 24, 2026
d22ad28
test(mosaic): group the sign-up Protect tests and seed their sign-up …
austincalvelage Nov 24, 2026
cdc5949
refactor(mosaic): keep the sign-up Protect reload count in the model
austincalvelage Nov 24, 2026
02db388
test(mosaic): cover Try again starting the expired Protect reload cou…
austincalvelage Nov 24, 2026
6b2b5ea
docs(swingset): describe the protectCheck slot in one sentence
austincalvelage Nov 24, 2026
cf1bf8c
refactor(mosaic): keep the sign-up Protect reload count in the flow c…
austincalvelage Nov 24, 2026
891d44f
test(mosaic): fold the expired Protect check test into the Try again …
austincalvelage Nov 24, 2026
cd19261
docs(mosaic): say the sign-up Protect screen needs the legacy Clerk U…
austincalvelage Nov 24, 2026
670052a
test(mosaic): cover a sign-up Protect check that completes the sign-up
austincalvelage Nov 24, 2026
6f00e8c
fix(mosaic): show the session activation on the sign-up Protect screen
austincalvelage Nov 24, 2026
5adeea4
test(mosaic): give the sign-up Protect check tests their own file
austincalvelage Nov 25, 2026
1864755
test(mosaic): wait for the first Protect challenge to leave before pa…
austincalvelage Nov 25, 2026
7de6146
refactor(mosaic): read the sign-up Protect pending state from the flo…
austincalvelage Nov 25, 2026
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
2 changes: 2 additions & 0 deletions .changeset/mosaic-sign-up-protect-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
6 changes: 3 additions & 3 deletions packages/mosaic/docs/internals/sign-in-sign-up-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Sign-up renders one component per screen, so the route decides what is mounted (
- A screen with work to do on arrival owns its controller. `SignUpVerify` holds the code machine and sends the code when it mounts on a step with `sent: false`. A submit, a reload and a redirect all arrive that way. A screen that runs a controller reaches the view as a slot the wrapper builds, as the profile section's `nameAction` does, so `SignUpView` renders plain props only.
- `SignUpVerify` takes the sign-up's id as its `key`, so a new sign-up never reuses the last one's screen.
- A screen another feature owns arrives as a slot. The wrapper runs the task's model once, passes it to `TaskChooseOrganizationContent` (the task without its card), and tells the controller whether the task has loaded. The view mounts the slot on the task route.
- A screen that is not a route sits on top of one. `restricted`, `waitlist` and `actionBlocked` replace `start`, and `startOver` replaces any route. A route whose screen is not built yet (`enterpriseConnections`, `protectCheck`) shows `startOver`.
- A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. A route whose screen is not built yet (`enterpriseConnections`) shows `startOver`.

## Move on after a submit

Expand All @@ -57,7 +57,7 @@ submitPassword: async (password: string) => {
- `complete`: the model's `finalize()`, then leave the flow for the after sign-up URL, which honors `redirect_url` and the redirect query params (`clerk.buildAfterSignUpUrl({ params })`). Creating the session clears the sign-up. Sign-up renders the model it left from while `finalize()` runs, and after it until a task that continues in the flow has its data loaded, so the task replaces the screen with no skeleton between them. It keeps the action pending throughout, the way the switcher holds its `frozenModel` ([Controllers → Wrapping actions](../controllers.md#wrapping-actions)). Once the hold ends with the session signed in, the flow is over: if the host keeps the component mounted, it renders nothing. In a modal, don't `close()` when the flow leaves: `finalize()`'s navigation is the last write and takes the modal with it.
- `transfer`: planned, not built. From sign-in, the model's `transfer()` will call `signUp.create({ transfer: true, unsafeMetadata })`, then `next` with the sign-up's step; a sign-in with sign-up built in holds the sign-up routes under `create/`, otherwise it leaves for the sign-up page. From sign-up, when the identifier already has an account, it will call `signIn.create({ transfer: true })`, then `next` with the sign-in's step. Until then sign-up keeps the current screen on a `transfer` step.
- `unknown`: nothing. The screen already shows "Start over".
- `blocked`: sign-up's `create` resolves with it, not a step, when FAPI answers `action_blocked`. The controller keeps the details for this mount and shows the notice in place of `start`. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does.
- `blocked`: sign-up's `create` and the Protect proof's `resolve` resolve with it, not a step, when FAPI answers `action_blocked`. The controller keeps the details for this mount and shows the notice in place of `start` or the Protect route. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does.
- Anything else: `go(routeFor(step))`.
- An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. Verifying a sign-up that is already complete skips the request and returns `complete`, so entering the code again runs `finalize()` again.

Expand All @@ -77,7 +77,7 @@ Sign-in:
Sign-up:

- `start` → `start`
- `protect` → `protectCheck`
- `protect` → `protectCheck`, or `continueProtectCheck` when reached from `continue`, where `SignUpProtect` runs the challenge through shared `runProtectCheck` when it mounts. It takes the challenge token as its `key`, so a chained or reissued challenge remounts it and runs again. The controller keeps the expired-reload count above it, so the cap holds across those remounts. A blocked proof shows `actionBlocked`. A check that completes the sign-up keeps the screen busy while `finalize()` runs. After a failed `finalize()` no challenge is left, so Try again runs `finalize()` again. The host must not load the legacy Clerk UI (`prefetchUI={false}` on the provider), because clerk-js otherwise opens its own Protect modal for the same check and this screen never renders (`__internal_openProtectCheckModal` in `clerk-js/src/core/clerk.ts`, called from `clerk-js/src/core/protectCheckGate.ts`)
- `enterprise_sso` → `enterpriseConnections`, which goes straight to the IdP unless there are several connections to pick from
- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue`
- `verify_phone` (`target`, `sent`) → `verifyPhone`, or `continueVerifyPhone` when reached from `continue`
Expand Down
123 changes: 121 additions & 2 deletions packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export interface FakeSignUpSeed {
sessionTasks?: SessionJSON['tasks'];
blocked?: Record<string, string>;
weakPasswords?: Record<string, string[]>;
protectChecks?: number;
protectCheckOn?: 'create' | 'update';
protectCheckExpired?: boolean;
protectCheckResolvedElsewhere?: boolean;
protectCheckBlocked?: Record<string, string>;
protectCheckScript?: string;
}

export interface FakeSignUpState {
Expand All @@ -29,6 +35,15 @@ export interface FakeSignUpState {
sessionTasks: SessionJSON['tasks'];
blocked?: Record<string, string>;
weakPasswords: Record<string, string[]>;
protectChecks: number;
protectCheckOn?: 'create' | 'update';
protectCheckExpired?: boolean;
protectCheckResolvedElsewhere?: boolean;
protectCheckBlocked?: Record<string, string>;
protectCheckScript?: string;
issuedProtectChecks: number;
reloads: number;
proofTokens: string[];
creations: URLSearchParams[];
updates: URLSearchParams[];
preparations: string[];
Expand All @@ -40,13 +55,41 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState {
enterpriseDomains: [],
sessionTasks: null,
weakPasswords: {},
protectChecks: 0,
issuedProtectChecks: 0,
reloads: 0,
proofTokens: [],
creations: [],
updates: [],
preparations: [],
...seed,
};
}

export const PROTECT_CHECK_SCRIPT = `
export default (container, { token, setWidgetVisible }) =>
new Promise((resolve, reject) => {
const pass = document.createElement('button');
pass.type = 'button';
pass.textContent = 'I am human';
pass.onclick = async () => {
await setWidgetVisible?.(false);
resolve('proof_' + token);
};
const fail = document.createElement('button');
fail.type = 'button';
fail.textContent = 'Fail the challenge';
fail.onclick = async () => {
await setWidgetVisible?.(false);
reject(new Error('challenge failed'));
};
container.replaceChildren(pass, fail);
void setWidgetVisible?.(true);
});
`;

let scriptIds = 0;

const STRATEGIES: Record<string, Identifier> = { email_code: 'email_address', phone_code: 'phone_number' };
const TEXT_FIELDS = ['email_address', 'phone_number', 'username', 'first_name', 'last_name'] as const;
const createdAt = Date.UTC(2026, 0, 1);
Expand All @@ -65,6 +108,33 @@ export function signUpHandlers(
) {
const settings = () => state.environment.user_settings;
const current = (id: unknown) => (state.client.sign_up?.id === id ? state.client.sign_up : undefined);
const scriptId = (scriptIds += 1);
const protectCheck = (expired: boolean): NonNullable<SignUpJSON['protect_check']> => {
state.signUp.issuedProtectChecks += 1;
return {
status: 'pending',
token: `ptk_${state.signUp.issuedProtectChecks}`,
sdk_url: fapiUrl(`/protect-check/challenge.js?round=${state.signUp.issuedProtectChecks}&script=${scriptId}`),
...(expired ? { expires_at: 1 } : {}),
};
};
const issueProtectCheck = (signUp: SignUpJSON, on: 'create' | 'update' = 'create'): SignUpJSON => {
if (
(state.signUp.protectCheckOn ?? 'create') !== on ||
state.signUp.issuedProtectChecks >= state.signUp.protectChecks
) {
return { ...signUp, protect_check: null };
}
return { ...signUp, protect_check: protectCheck(Boolean(state.signUp.protectCheckExpired)) };
};
const isExpired = (check: NonNullable<SignUpJSON['protect_check']>) =>
check.expires_at !== undefined && check.expires_at < Date.now();

const clientError = async (response: Response) => {
const body = (await response.json()) as object;
return HttpResponse.json({ ...body, meta: { client: state.client } }, { status: response.status });
};

const store = (signUp: SignUpJSON) => {
state.client = { ...state.client, sign_up: signUp.status === 'complete' ? null : signUp };
return envelope(signUp, state.client);
Expand Down Expand Up @@ -135,6 +205,7 @@ export function signUpHandlers(
...required_fields.filter(field => !provided(field)),
...(anyIdentifierMissing ? identifierNames : []),
...(enterprise ? (['enterprise_sso'] as const) : []),
...(signUp.protect_check ? (['protect_check'] as const) : []),
];
const settled: SignUpJSON = {
...signUp,
Expand Down Expand Up @@ -271,7 +342,51 @@ export function signUpHandlers(
}
const blank = fapiSignUp({ id: `sua_${state.signUp.creations.length}` });
const applied = apply(blank, body);
return applied instanceof HttpResponse ? applied : store(settle(applied));
return applied instanceof HttpResponse ? applied : store(settle(issueProtectCheck(applied)));
}),
http.get(fapiUrl('/protect-check/challenge.js'), () =>
HttpResponse.text(state.signUp.protectCheckScript ?? PROTECT_CHECK_SCRIPT, {
headers: { 'Content-Type': 'text/javascript', 'Access-Control-Allow-Origin': '*' },
}),
),
http.post(fapiUrl('/v1/client/sign_ups/:id/protect_check'), async ({ params, request }) => {
if (new URL(request.url).searchParams.get('_method') !== 'PATCH') {
return undefined;
}
const signUp = current(params.id);
if (!signUp) {
return missing();
}
const proofToken = new URLSearchParams(await request.text()).get('proof_token');
if (!proofToken) {
return rejected('form_param_missing', 'proof_token must be included.', 'proof_token');
}
if (state.signUp.protectCheckBlocked) {
return rejected(
'action_blocked',
'This request was blocked.',
undefined,
403,
state.signUp.protectCheckBlocked,
);
}
if (state.signUp.protectCheckResolvedElsewhere || !signUp.protect_check) {
store(settle({ ...signUp, protect_check: null }));
return clientError(missing());
}
state.signUp.proofTokens.push(proofToken);
if (proofToken !== `proof_${signUp.protect_check.token}`) {
return store(settle({ ...signUp, protect_check: protectCheck(false) }));
}
return store(settle(issueProtectCheck({ ...signUp, protect_check: null }, state.signUp.protectCheckOn)));
}),
http.get(fapiUrl('/v1/client/sign_ups/:id'), ({ params }) => {
const signUp = current(params.id);
if (!signUp) {
return missing();
}
state.signUp.reloads += 1;
return store(signUp);
}),
http.post(fapiUrl('/v1/client/sign_ups/:id'), async ({ params, request }) => {
if (new URL(request.url).searchParams.get('_method') !== 'PATCH') {
Expand All @@ -284,7 +399,11 @@ export function signUpHandlers(
const body = new URLSearchParams(await request.text());
state.signUp.updates.push(body);
const applied = apply(signUp, body);
return applied instanceof HttpResponse ? applied : store(settle(applied));
if (applied instanceof HttpResponse) {
return applied;
}
const pending = applied.protect_check && !isExpired(applied.protect_check);
return store(settle(pending ? applied : issueProtectCheck(applied, 'update')));
}),
http.post(fapiUrl('/v1/client/sign_ups/:id/prepare_verification'), async ({ params, request }) => {
const signUp = current(params.id);
Expand Down
Loading
Loading