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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
81 changes: 81 additions & 0 deletions packages/client/src/clearance-renewal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
52 changes: 42 additions & 10 deletions packages/client/src/clearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,47 @@ 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<string>;
behavior?: BehaviorAggregate;
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
Expand Down Expand Up @@ -278,6 +312,7 @@ async function maintain(s: ClearanceSession): Promise<void> {
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()));
Expand All @@ -287,17 +322,11 @@ async function maintain(s: ClearanceSession): Promise<void> {
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);
Expand Down Expand Up @@ -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); });
}

Expand All @@ -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;
Expand Down
Loading