Skip to content
Draft
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
12 changes: 12 additions & 0 deletions .changeset/lucky-pandas-observe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@clerk/clerk-js': minor
'@clerk/shared': minor
---

Acquire an optional Protect session token and attach it to sign-in and sign-up requests.

On instances whose loader config references the new `{cid}` / `{pid}` / `{rid}` / `{instance_id}` / `{sdkver}` placeholders, Clerk mints an opaque, random correlation id and substitutes it into the loader's attributes and `textContent`. The loader is served with a signed session token, which is taken up once per browser session — shared across tabs under a lock rather than acquired once per tab — and travels alongside the correlation id and an acquisition status in the form-encoded body of sign-in and sign-up requests.

Acquisition can never block or fail a sign-in: it is bounded by a deadline, and when no token can be obtained a status (`no_token`, `timeout`, `script_error`, `fetch_error`, `unsupported`, `http_<n>`) travels in its place and the request proceeds unchanged. Only the loader carrying the correlation id is governed by the shared token; any other configured loader is still applied on every page load. Nothing is stored in the browser unless a loader references `{cid}`, `{pid}` or `{rid}`.

`ProtectLoader` gains two optional fields: `tokenTimeoutMs`, and `tokenUrl` for instances that opt into fetching the token from a dedicated endpoint instead of taking the one served with the loader.
10 changes: 5 additions & 5 deletions packages/clerk-js/bundlewatch.config.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"files": [
{ "path": "./dist/clerk.js", "maxSize": "549KB" },
{ "path": "./dist/clerk.browser.js", "maxSize": "75KB" },
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "117KB" },
{ "path": "./dist/clerk.no-rhc.js", "maxSize": "316KB" },
{ "path": "./dist/clerk.native.js", "maxSize": "74KB" },
{ "path": "./dist/clerk.js", "maxSize": "552KB" },
{ "path": "./dist/clerk.browser.js", "maxSize": "77KB" },
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "120KB" },
{ "path": "./dist/clerk.no-rhc.js", "maxSize": "318KB" },
{ "path": "./dist/clerk.native.js", "maxSize": "77KB" },
{ "path": "./dist/vendors*.js", "maxSize": "7KB" },
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
{ "path": "./dist/base-account-sdk*.js", "maxSize": "207KB" },
Expand Down
100 changes: 100 additions & 0 deletions packages/clerk-js/src/core/__tests__/fapiClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,106 @@ describe('request', () => {
});
});

describe('protect params', () => {
const protectParams = {
__clerk_protect_token: 'v1.payload.mac',
__clerk_protect_status: 'ok',
__clerk_protect_cid: `1-${'a'.repeat(26)}-${'b'.repeat(26)}`,
};

let getProtectParams: Mock;
let clientWithProtect: ReturnType<typeof createFapiClient>;

beforeEach(() => {
getProtectParams = vi.fn().mockResolvedValue(protectParams);
clientWithProtect = createFapiClient({ ...baseFapiClientOptions, getProtectParams });
});

const bodyOf = () => (fetch as Mock).mock.calls[0][1].body as string;

it.each(['/client/sign_ins', '/client/sign_ups', '/client/sign_ins/sia_123/attempt_first_factor'])(
'merges them into the form-encoded body of %s',
async path => {
await clientWithProtect.request({ path, method: 'POST', body: { identifier: 'nick@clerk.dev' } as any });

expect(bodyOf()).toBe(
`identifier=nick%40clerk.dev&__clerk_protect_token=v1.payload.mac&__clerk_protect_status=ok&__clerk_protect_cid=${protectParams.__clerk_protect_cid}`,
);
// A signed credential must never land in the URL, which is logged all along the path.
expect((fetch as Mock).mock.calls[0][0].toString()).not.toContain('__clerk_protect');
},
);

it('adds no request headers', async () => {
await clientWithProtect.request({ path: '/client/sign_ins', method: 'POST', body: {} as any });

const headers = (fetch as Mock).mock.calls[0][1].headers as Headers;
expect([...headers.keys()]).toEqual(['content-type']);
});

it('populates the body even when the request had none', async () => {
await clientWithProtect.request({ path: '/client/sign_ups', method: 'POST' });

expect(bodyOf()).toContain('__clerk_protect_status=ok');
});

it.each(['/client', '/client/sessions', '/environment', '/client/sign_insomething'])(
'leaves %s alone',
async path => {
await clientWithProtect.request({ path, method: 'POST', body: { foo: 'bar' } as any });

expect(bodyOf()).toBe('foo=bar');
expect(getProtectParams).not.toHaveBeenCalled();
},
);

it('leaves GET requests alone', async () => {
await clientWithProtect.request({ path: '/client/sign_ins', method: 'GET' });

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

it('leaves a FormData body alone', async () => {
const formData = new FormData();
formData.append('identifier', 'nick@clerk.dev');

await clientWithProtect.request({ path: '/client/sign_ins', method: 'POST', body: formData });

expect((fetch as Mock).mock.calls[0][1].body).toBe(formData);
expect(getProtectParams).not.toHaveBeenCalled();
});

it('sends nothing extra when the instance does not participate', async () => {
getProtectParams.mockResolvedValue(undefined);

await clientWithProtect.request({ path: '/client/sign_ins', method: 'POST', body: { foo: 'bar' } as any });

expect(bodyOf()).toBe('foo=bar');
});

// Merging into any of these would spread away the caller's payload rather than add to it.
it.each([
['a Blob', () => new Blob(['payload'])],
['an array', () => [1, 2, 3]],
['a URLSearchParams', () => new URLSearchParams({ identifier: 'nick@clerk.dev' })],
])('leaves %s body alone', async (_label, makeBody) => {
await clientWithProtect.request({ path: '/client/sign_ins', method: 'POST', body: makeBody() as any });

expect(getProtectParams).not.toHaveBeenCalled();
expect(String((fetch as Mock).mock.calls[0][1].body)).not.toContain('__clerk_protect');
});

it('still sends the request when resolving the params rejects', async () => {
getProtectParams.mockRejectedValue(new DOMException('storage is blocked', 'SecurityError'));

// Protect can degrade a sign-in but must never fail one before it is even sent.
await expect(
clientWithProtect.request({ path: '/client/sign_ins', method: 'POST', body: { foo: 'bar' } as any }),
).resolves.toBeDefined();
expect(bodyOf()).toBe('foo=bar');
});
});

describe('retry logic', () => {
it('does not send retry query parameter on initial request', async () => {
await fapiClient.request({
Expand Down
194 changes: 194 additions & 0 deletions packages/clerk-js/src/core/__tests__/protect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import type { ProtectLoader } from '@clerk/shared/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { Protect } from '../protect';
import { __internal_resetProtectStorage } from '../protectSession';
import type { Environment } from '../resources';

const environment = (loaders: unknown[], id = ''): Environment =>
({ protectConfig: { id, loaders } }) as unknown as Environment;

/** No `src`: jsdom fetches real URLs, which fires `error` and races the events we drive here. */
const loader = (overrides: Partial<ProtectLoader> = {}): ProtectLoader => ({
target: 'head',
type: 'script',
attributes: { 'data-cid': '{cid}' },
tokenTimeoutMs: 200,
...overrides,
});

const nowSeconds = () => Math.floor(Date.now() / 1_000);

/** The token loader is injected under the acquisition lock, so it appears a few ticks in. */
const injected = async (selector: string): Promise<Element> => {
for (let i = 0; i < 100; i++) {
const element = document.head.querySelector(selector);
if (element) {
return element;
}
await new Promise(resolve => setTimeout(resolve, 0));
}
throw new Error(`nothing matched ${selector}`);
};

const serveInline = (element: Element, overrides: Record<string, unknown> = {}) => {
(globalThis as unknown as Record<string, unknown>).__clerk_specter = {
v: 3,
id: '11111111-2222-3333-4444-555555555555',
cid: element.getAttribute('data-cid'),
ready: Promise.resolve({ token: 'v1.payload.mac', exp: nowSeconds() + 43_200 }),
...overrides,
};
element.dispatchEvent(new Event('load'));
};

beforeEach(() => {
localStorage.clear();
__internal_resetProtectStorage();
document.head.innerHTML = '';
document.body.innerHTML = '';
delete (globalThis as unknown as Record<string, unknown>).__clerk_specter;
});

afterEach(() => {
vi.restoreAllMocks();
localStorage.clear();
__internal_resetProtectStorage();
delete (globalThis as unknown as Record<string, unknown>).__clerk_specter;
});

describe('Protect.load', () => {
it('does nothing without a protect config', () => {
new Protect().load(environment([]));
expect(document.head.querySelector('script')).toBeNull();
expect(localStorage.getItem('__clerk_protect_pid')).toBeNull();
});

it('applies an untemplated loader unchanged and reports no params', async () => {
const protect = new Protect();
protect.load(
environment([
{ target: 'head', type: 'script', attributes: { 'data-loader': 'https://loader.example.com/ins_2abc.js' } },
]),
);

expect(document.head.querySelector('script')?.getAttribute('data-loader')).toBe(
'https://loader.example.com/ins_2abc.js',
);
await expect(protect.getRequestParams()).resolves.toBeUndefined();
expect(localStorage.getItem('__clerk_protect_pid')).toBeNull();
});

it('substitutes the placeholders it recognises and leaves the rest verbatim', async () => {
const protect = new Protect();
protect.load(
environment(
[
loader({
attributes: {
'data-src': 'https://loader.example.com/{instance_id}/{cid}/loader.js',
'data-pid': '{pid}',
'data-rid': '{rid}',
'data-unknown': '{whatever}',
'data-count': 3,
},
}),
],
'ins_2abc',
),
);

const element = await injected('script');
const pid = element.getAttribute('data-pid') as string;
const rid = element.getAttribute('data-rid') as string;

expect(pid).toMatch(/^[a-z2-7]{26}$/);
expect(rid).toMatch(/^[a-z2-7]{26}$/);
expect(element.getAttribute('data-src')).toBe(`https://loader.example.com/ins_2abc/1-${pid}-${rid}/loader.js`);
expect(element.getAttribute('data-unknown')).toBe('{whatever}');
expect(element.getAttribute('data-count')).toBe('3');
});

it('substitutes placeholders in textContent as well as attributes', async () => {
const protect = new Protect();
protect.load(environment([loader({ textContent: 'window.__vendor_cid = "{cid}";' })], 'ins_2abc'));

const element = await injected('script');
expect(element.textContent).toBe(`window.__vendor_cid = "${element.getAttribute('data-cid')}";`);
expect(element.textContent).not.toContain('{cid}');
});

it('leaves {instance_id} verbatim when the environment does not carry one', async () => {
const protect = new Protect();
protect.load(environment([loader({ attributes: { 'data-src': '{instance_id}/{cid}.js' } })]));

expect((await injected('script')).getAttribute('data-src')).toContain('{instance_id}');
});

it('attaches the token once it has been acquired', async () => {
const protect = new Protect();
protect.load(environment([loader()]));

serveInline(await injected('script'));

await expect(protect.getRequestParams()).resolves.toMatchObject({
__clerk_protect_token: 'v1.payload.mac',
__clerk_protect_status: 'ok',
});
});

it('still applies the other loaders when a token for this browser session is shared', async () => {
localStorage.setItem(
'__clerk_protect_st',
JSON.stringify({ token: 'v1.cached.mac', exp: nowSeconds() + 43_200, rid: 'b'.repeat(26) }),
);

const protect = new Protect();
protect.load(
environment([
loader({ attributes: { 'data-role': 'detection' } }),
loader({ attributes: { 'data-cid': '{cid}', 'data-role': 'token' } }),
]),
);

// Acquisition happens once per browser session, so the token loader is skipped…
expect(document.head.querySelector('[data-role="token"]')).toBeNull();
// …but the detection loader has its own job and runs on every page load regardless.
expect(document.head.querySelector('[data-role="detection"]')).not.toBeNull();
await expect(protect.getRequestParams()).resolves.toMatchObject({ __clerk_protect_token: 'v1.cached.mac' });
});

it('does not apply a loader that is outside its rollout', async () => {
vi.spyOn(Math, 'random').mockReturnValue(0.9);

const protect = new Protect();
protect.load(environment([loader({ rollout: 0.1 })]));

expect(document.head.querySelector('script')).toBeNull();
// Out of rollout means Protect is off for this browser, so there is nothing to report either.
await expect(protect.getRequestParams()).resolves.toBeUndefined();
});

it('reports script_error when the loader element fails to load', async () => {
const protect = new Protect();
protect.load(environment([loader({ tokenTimeoutMs: 5_000 })]));

(await injected('script')).dispatchEvent(new Event('error'));

await expect(protect.getRequestParams()).resolves.toMatchObject({ __clerk_protect_status: 'script_error' });
});

it('drops a malformed loader entry without failing the rest of the load', async () => {
const protect = new Protect();

// The config is server-controlled and cached; a bad entry must not take Clerk.load() down.
expect(() => protect.load(environment([null, loader({ attributes: { 'data-role': 'good' } })]))).not.toThrow();

expect(document.head.querySelector('[data-role="good"]')).not.toBeNull();
});

it('survives a loader config that is not an array of objects at all', () => {
const protect = new Protect();
expect(() => protect.load(environment(['nope', 42, undefined]))).not.toThrow();
});
});
Loading
Loading