From 8e3d02ee5621aeaed5b7ecb687396ea17855d807 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sat, 14 Nov 2026 16:22:03 -0600 Subject: [PATCH] fix(client): retry clearance as soon as a page returns from sleep A renewal that failed while the page was hidden or offline no longer holds its backoff once the page is visible and online again. After a long sleep the token has expired, so waiting out that backoff left every protected request refused for minutes. One early retry per absence; a failure while the page is in view keeps its delay. --- CHANGELOG.md | 1 + packages/client/src/clearance-renewal.test.ts | 81 +++++++++++++++++++ packages/client/src/clearance.ts | 52 +++++++++--- 3 files changed, 124 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e889a8..dbd9514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **The checkbox widget works with screen readers.** The checkbox now has an accessible name ("I'm not a robot"). "Verifying", "Verified" and failure messages are announced through a polite status region, and the checkbox reports busy while it verifies. It shows a visible focus ring for keyboard users. - **A failure message stays on screen until the next attempt.** It used to disappear after three seconds, which could be before a person had read it. +- **Clearance recovers as soon as a page comes back from sleep.** When a computer sleeps longer than the token lasts, the browser can wake briefly in the background, try to renew while it has no network, fail and back off. After the real wake the page then waited out that backoff, up to several minutes, while protected requests were refused. A renewal that failed while the page was hidden or offline is now retried as soon as the page is visible and online again. This happens once per absence; a renewal that fails while the page is in view keeps its delay. ## [0.24.0] - 2026-11-13 diff --git a/packages/client/src/clearance-renewal.test.ts b/packages/client/src/clearance-renewal.test.ts index 831861a..3cc5997 100644 --- a/packages/client/src/clearance-renewal.test.ts +++ b/packages/client/src/clearance-renewal.test.ts @@ -177,3 +177,84 @@ test('native idle scheduling is bound to the window and has a deadline', async ( expect(fetchMock).toHaveBeenCalledTimes(1); } finally { delete (window as unknown as { requestIdleCallback?: unknown }).requestIdleCallback; } }); +describe('returning after a failure while away', () => { + const setVisibility = (value: 'visible' | 'hidden') => { + Object.defineProperty(document, 'visibilityState', { configurable: true, value }); + document.dispatchEvent(new Event('visibilitychange')); + }; + const setOnline = (value: boolean) => Object.defineProperty(navigator, 'onLine', { configurable: true, value }); + afterEach(() => { + Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' }); + setOnline(true); + }); + + test('a renewal that failed while hidden is retried as soon as the page is visible', async () => { + // A computer asleep: the token expires, the page wakes briefly, its + // renewal fails, and the backoff would otherwise outlast the wake. + cookie = 'wd_clearance=' + token(60); + startClearance(opts); + setVisibility('hidden'); + fetchMock.mockRejectedValue(new Error('offline')); + await advance(61_000); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(jest.getTimerCount()).toBe(1); + fetchMock.mockResolvedValue(response()); + setVisibility('visible'); + await advance(0); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(cookie).toMatch(/^wd_clearance=/); + expect(jest.getTimerCount()).toBe(1); + }); + + test('the early retry happens once; a failure while visible keeps its delay', async () => { + setVisibility('hidden'); + fetchMock.mockRejectedValue(new Error('offline')); + startClearance(opts); + await advance(1200); + expect(fetchMock).toHaveBeenCalledTimes(1); + setVisibility('visible'); + await advance(0); + expect(fetchMock).toHaveBeenCalledTimes(2); + for (let i = 0; i < 5; i++) setVisibility('visible'); + await advance(119_999); + expect(fetchMock).toHaveBeenCalledTimes(2); + await advance(1); + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + test('hide and show while the last failure was visible does not skip the delay', async () => { + fetchMock.mockRejectedValue(new Error('offline')); + startClearance(opts); + await advance(1200); + expect(fetchMock).toHaveBeenCalledTimes(1); + for (let i = 0; i < 3; i++) { setVisibility('hidden'); setVisibility('visible'); } + await advance(59_999); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + test('a renewal that failed while offline is retried when the network returns', async () => { + setOnline(false); + fetchMock.mockRejectedValue(new Error('offline')); + startClearance(opts); + await advance(1200); + expect(fetchMock).toHaveBeenCalledTimes(1); + fetchMock.mockResolvedValue(response()); + setOnline(true); + window.dispatchEvent(new Event('online')); + await advance(0); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(cookie).toMatch(/^wd_clearance=/); + }); + + test('stopping the session removes the online listener', async () => { + setOnline(false); + fetchMock.mockRejectedValue(new Error('offline')); + startClearance(opts); + await advance(1200); + _resetClearanceForTests(); + setOnline(true); + window.dispatchEvent(new Event('online')); + await advance(0); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/client/src/clearance.ts b/packages/client/src/clearance.ts index 45880cc..3c1e11e 100644 --- a/packages/client/src/clearance.ts +++ b/packages/client/src/clearance.ts @@ -212,6 +212,12 @@ interface ClearanceSession { running: boolean; stopped: boolean; failures: number; + /** + * The last failure happened while the page was hidden or offline, for + * example while the computer slept. That failure says nothing about whether + * a retry will work once the page is back, so it earns one early retry. + */ + failedAway: boolean; /** Per-page renewal spread in [0, 1); see renewalTime. */ spread: number; fingerprint?: Promise; @@ -219,6 +225,34 @@ interface ClearanceSession { lastBehavior?: BehaviorAggregate; wake: () => void; } + +function isAway(): boolean { + return document.visibilityState === 'hidden' || (typeof navigator !== 'undefined' && navigator.onLine === false); +} + +function backOff(s: ClearanceSession): void { + s.failures++; + s.failedAway = isAway(); + const delay = Math.min(300_000, COOKIE_CHECK_MS * Math.pow(2, Math.min(s.failures - 1, 3))); + s.retryAt = Date.now() + delay; + schedule(s, delay); +} + +/** + * The page is visible and online again. If the last attempt failed while it + * was away, retry now rather than waiting out the delay: after a long sleep the + * token has usually expired and every protected request is refused until the + * next mint. One early retry per absence; a failure while present keeps its + * delay, so repeated events cannot drive repeated requests. + */ +function returned(s: ClearanceSession): void { + if (isAway()) return; + if (s.failedAway) { + s.failedAway = false; + s.retryAt = 0; + } + void maintain(s); +} let session: ClearanceSession | undefined; // The unsigned payload is ONLY a scheduling hint. Server and edge verification @@ -278,6 +312,7 @@ async function maintain(s: ClearanceSession): Promise { s.expiresAt = Date.now() + result.expiresIn * 1000; s.renewAt = renewalTime(s.expiresAt, result.expiresIn * 1000, s.spread); s.failures = 0; + s.failedAway = false; if (behavior) s.lastBehavior = behavior; s.retryAt = 0; schedule(s, Math.min(COOKIE_CHECK_MS, s.renewAt - Date.now())); @@ -287,17 +322,11 @@ async function maintain(s: ClearanceSession): Promise { s.stopped = true; if (s.timer !== undefined) clearTimeout(s.timer); } else { - s.failures++; - const delay = Math.min(300_000, COOKIE_CHECK_MS * Math.pow(2, Math.min(s.failures - 1, 3))); - s.retryAt = Date.now() + delay; - schedule(s, delay); + backOff(s); } } catch { s.fingerprint = undefined; - s.failures++; - const delay = Math.min(300_000, COOKIE_CHECK_MS * Math.pow(2, Math.min(s.failures - 1, 3))); - s.retryAt = Date.now() + delay; - schedule(s, delay); + backOff(s); } finally { s.running = false; if (s.behavior && !s.stopped && s === session) schedule(s, 1000); @@ -336,14 +365,16 @@ export function startClearance(opts: ClearanceOptions): void { if (session) { if (session.timer !== undefined) clearTimeout(session.timer); document.removeEventListener('visibilitychange', session.wake); + if (typeof window !== 'undefined') window.removeEventListener('online', session.wake); } upgradeStarted = false; const s: ClearanceSession = { - 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); }, + key, opts: { ...opts }, token: null, expiresAt: 0, renewAt: 0, retryAt: 0, running: false, stopped: false, failures: 0, failedAway: false, spread: Math.random(), + wake: () => returned(s), }; session = s; document.addEventListener('visibilitychange', s.wake); + if (typeof window !== 'undefined') window.addEventListener('online', s.wake); whenIdle(() => { void maintain(s); }); } @@ -365,6 +396,7 @@ export function _resetClearanceForTests(): void { if (session) { if (session.timer !== undefined) clearTimeout(session.timer); document.removeEventListener('visibilitychange', session.wake); + if (typeof window !== 'undefined') window.removeEventListener('online', session.wake); } session = undefined; upgradeStarted = false;