diff --git a/CHANGELOG.md b/CHANGELOG.md index 381eeaf..6763c94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/packages/client/README.md b/packages/client/README.md index 215db39..475bb89 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -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. diff --git a/packages/client/src/clearance-fetch.test.ts b/packages/client/src/clearance-fetch.test.ts index 8c68a5b..87754a4 100644 --- a/packages/client/src/clearance-fetch.test.ts +++ b/packages/client/src/clearance-fetch.test.ts @@ -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(); const recover = jest.fn(() => pending.promise); diff --git a/packages/client/src/clearance-fetch.ts b/packages/client/src/clearance-fetch.ts index 217f355..fa0b70f 100644 --- a/packages/client/src/clearance-fetch.ts +++ b/packages/client/src/clearance-fetch.ts @@ -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); diff --git a/packages/client/src/clearance-renewal.test.ts b/packages/client/src/clearance-renewal.test.ts index edd57d6..831861a 100644 --- a/packages/client/src/clearance-renewal.test.ts +++ b/packages/client/src/clearance-renewal.test.ts @@ -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); @@ -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); diff --git a/packages/client/src/clearance.ts b/packages/client/src/clearance.ts index ac8a250..45880cc 100644 --- a/packages/client/src/clearance.ts +++ b/packages/client/src/clearance.ts @@ -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; @@ -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; behavior?: BehaviorAggregate; lastBehavior?: BehaviorAggregate; @@ -233,7 +249,7 @@ async function maintain(s: ClearanceSession): Promise { 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()); @@ -260,7 +276,7 @@ async function maintain(s: ClearanceSession): Promise { 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; @@ -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;