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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- **Clearance renewal is spread across tabs.** Every tab shares one clearance cookie, so every tab used to reach the same renewal instant and could each mint a token. Each page now renews at a random point between the refresh margin and one and a half times it (120 to 180 seconds before expiry for a 30-minute token). The first tab's new cookie is usually in place before the next tab checks, and that tab defers.
- **`createClearanceFetch` reports `recovery-succeeded` when the retry passes the clearance gate**, whatever the origin then answers. Previously a cleared retry that the origin answered with a 404 or 500 was reported as `recovery-failed`. The origin's status is still reported, once, as the `enforcement-outcome` status. A retry that is challenged again is still `recovery-failed`.

## [0.23.0] - 2026-11-12

### Changed
Expand Down
5 changes: 3 additions & 2 deletions packages/client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,9 @@ different API host.
`onEvent` reports `challenge-served`, `recovery-attempted`,
`recovery-succeeded`/`recovery-failed`, and the retried `enforcement-outcome`
(status). Attempts are per waiting request; count callback invocations separately
for shared flows. Success means the retry returned an OK response, not a new
trust grade. These local observations send no telemetry automatically and must
for shared flows. Success means the retry got past the clearance gate (it was
not challenged again), whatever the origin then answered; the origin's status is
the `enforcement-outcome` status. It does not mean a new trust grade. These local observations send no telemetry automatically and must
remain distinct from the validator's verdict counts. Observation failures cannot
change the request. Interactive application flows must provide keyboard access,
focus restoration, an announced status and cancellation; the helper renders no UI.
23 changes: 23 additions & 0 deletions packages/client/src/clearance-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,29 @@ test.each(['GET', 'HEAD'])('%s retries once and preserves request options', asyn
expect(events.mock.calls.map(call => call[0].type)).toEqual(['challenge-served', 'recovery-attempted', 'enforcement-outcome', 'recovery-succeeded']);
});

test('recovery succeeds when the retry passes the gate, whatever the origin answers', async () => {
const fetcher = jest.fn().mockResolvedValueOnce(challenged()).mockResolvedValueOnce(new Response('missing', { status: 404 }));
const events = jest.fn();
const fetch = createClearanceFetch({ origin, recover: async () => true, fetch: fetcher, onEvent: events });
const result = await fetch(origin + '/data');
expect(result.status).toBe(404);
const seen = events.mock.calls.map(call => [call[0].type, call[0].status]);
expect(seen).toContainEqual(['enforcement-outcome', 404]);
expect(seen).toContainEqual(['recovery-succeeded', 404]);
expect(seen.map(e => e[0])).not.toContain('recovery-failed');
});

test('recovery fails when the retry is challenged again', async () => {
const fetcher = jest.fn().mockResolvedValueOnce(challenged()).mockResolvedValueOnce(challenged());
const events = jest.fn();
const fetch = createClearanceFetch({ origin, recover: async () => true, fetch: fetcher, onEvent: events });
const result = await fetch(origin + '/data');
expect(result.status).toBe(403);
const types = events.mock.calls.map(call => call[0].type);
expect(types).toContain('recovery-failed');
expect(types).not.toContain('recovery-succeeded');
});

test('concurrent challenges coalesce and retry each read only once', async () => {
const pending = deferred<boolean>();
const recover = jest.fn(() => pending.promise);
Expand Down
8 changes: 6 additions & 2 deletions packages/client/src/clearance-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,12 @@ export function createClearanceFetch(options: ClearanceFetchOptions): typeof fet
// we return the headers and remove the recovery listener below.
const retrySignal = AbortSignal.any([request.signal, controller.signal]);
const retried = await abortable(nativeFetch(new Request(request, { signal: retrySignal })), controller.signal);
observe('enforcement-outcome', method, readClearanceChallenge(retried) ?? challenge, retried.status);
observe(retried.ok ? 'recovery-succeeded' : 'recovery-failed', method, challenge, retried.status);
// Recovery succeeded when the retry got past the clearance gate. What the
// origin then answered (404, 500, ...) is the application's business and
// is reported once, as the enforcement-outcome status.
const rechallenged = readClearanceChallenge(retried);
observe('enforcement-outcome', method, rechallenged ?? challenge, retried.status);
observe(rechallenged ? 'recovery-failed' : 'recovery-succeeded', method, challenge, retried.status);
return retried;
} catch (error) {
observe('recovery-failed', method, challenge);
Expand Down
35 changes: 34 additions & 1 deletion packages/client/src/clearance-renewal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ beforeEach(() => {
fetchMock = jest.fn(async () => response());
globalThis.fetch = fetchMock;
jest.clearAllMocks();
// Renewal spread pinned to zero so the timings below are exact; the spread
// has its own tests.
jest.spyOn(Math, 'random').mockReturnValue(0);
});
afterEach(() => { _resetClearanceForTests(); jest.useRealTimers(); });
afterEach(() => { _resetClearanceForTests(); jest.useRealTimers(); jest.restoreAllMocks(); });
test('active clearance renews through two lifetimes and reuses collected fingerprint', async () => {
startClearance(opts);
await advance(1200);
Expand Down Expand Up @@ -85,6 +88,36 @@ test('short server TTLs do not create a rapid renewal loop', async () => {
await advance(1);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
test('the renewal spread moves renewal earlier, by at most half the margin', async () => {
(Math.random as jest.Mock).mockReturnValue(0.999);
cookie = 'wd_clearance=' + token();
startClearance(opts);
await advance(1200);
// 1800 s token, 120 s margin, spread just under 1: renews ~180 s before expiry.
await advance(1_620_000 - 1200 - 1000);
expect(fetchMock).not.toHaveBeenCalled();
await advance(2000);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
test('two pages with different spreads renew at different times', async () => {
// A tab is one page and one session; model the second tab by restarting
// with a different spread and the same shared cookie.
const firstRenewal = async (spread: number) => {
_resetClearanceForTests();
fetchMock.mockClear();
(Math.random as jest.Mock).mockReturnValue(spread);
jest.setSystemTime(new Date('2026-10-12T00:00:00Z'));
cookie = 'wd_clearance=' + token();
startClearance(opts);
await advance(1200);
let elapsed = 1200;
while (fetchMock.mock.calls.length === 0 && elapsed < 1_800_000) { await advance(1000); elapsed += 1000; }
return elapsed;
};
const a = await firstRenewal(0.1);
const b = await firstRenewal(0.9);
expect(a - b).toBeGreaterThanOrEqual(45_000);
});
test('a cookie renewed by another tab postpones local minting', async () => {
cookie = 'wd_clearance=' + token();
startClearance(opts);
Expand Down
22 changes: 19 additions & 3 deletions packages/client/src/clearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,20 @@ interface MintResponse {
type MintResult = { token: string; expiresIn: number } | { denied: true } | null;
const REFRESH_MARGIN_MS = 120_000;
const COOKIE_CHECK_MS = 60_000;

/**
* When to renew a token that expires at `expiresAt` and lives `lifetimeMs`.
*
* The lead time is the refresh margin (a third of the lifetime for short
* tokens) plus up to half of it again, chosen once per page. Tabs share one
* cookie, so without the spread every tab reaches the same renewal instant and
* each mints its own token. Spread out, the first tab's new cookie is usually
* in place before the next tab checks, and that tab defers instead.
*/
function renewalTime(expiresAt: number, lifetimeMs: number, spread: number): number {
const margin = Math.min(REFRESH_MARGIN_MS, Math.max(0, lifetimeMs) / 3);
return expiresAt - margin * (1 + spread / 2);
}
const MAX_TOKEN_AGE_MS = 1_800_000;
const MINT_TIMEOUT_MS = 10_000;

Expand Down Expand Up @@ -198,6 +212,8 @@ interface ClearanceSession {
running: boolean;
stopped: boolean;
failures: number;
/** Per-page renewal spread in [0, 1); see renewalTime. */
spread: number;
fingerprint?: Promise<string>;
behavior?: BehaviorAggregate;
lastBehavior?: BehaviorAggregate;
Expand Down Expand Up @@ -233,7 +249,7 @@ async function maintain(s: ClearanceSession): Promise<void> {
if (token !== s.token) {
s.token = token;
s.expiresAt = token ? expiryHint(token) : 0;
s.renewAt = s.expiresAt - Math.min(REFRESH_MARGIN_MS, Math.max(0, s.expiresAt - Date.now()) / 3);
s.renewAt = renewalTime(s.expiresAt, s.expiresAt - Date.now(), s.spread);
}
if (s.retryAt > Date.now()) {
schedule(s, s.retryAt - Date.now());
Expand All @@ -260,7 +276,7 @@ async function maintain(s: ClearanceSession): Promise<void> {
setClearanceCookie(result.token, result.expiresIn);
s.token = readCookie(CLEARANCE_COOKIE);
s.expiresAt = Date.now() + result.expiresIn * 1000;
s.renewAt = s.expiresAt - Math.min(REFRESH_MARGIN_MS, result.expiresIn * 1000 / 3);
s.renewAt = renewalTime(s.expiresAt, result.expiresIn * 1000, s.spread);
s.failures = 0;
if (behavior) s.lastBehavior = behavior;
s.retryAt = 0;
Expand Down Expand Up @@ -323,7 +339,7 @@ export function startClearance(opts: ClearanceOptions): void {
}
upgradeStarted = false;
const s: ClearanceSession = {
key, opts: { ...opts }, token: null, expiresAt: 0, renewAt: 0, retryAt: 0, running: false, stopped: false, failures: 0,
key, opts: { ...opts }, token: null, expiresAt: 0, renewAt: 0, retryAt: 0, running: false, stopped: false, failures: 0, spread: Math.random(),
wake: () => { if (document.visibilityState === 'visible') void maintain(s); },
};
session = s;
Expand Down
Loading