@webdecoy/client 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,6 +65,31 @@ const result = await WebDecoyCaptcha.execute('pk_live_...', { action: 'login' })
65
65
  if (result.success) { /* result.token */ }
66
66
  ```
67
67
 
68
+ ## Session clearance
69
+
70
+ ```js
71
+ import { startClearance } from '@webdecoy/client';
72
+
73
+ startClearance({ siteKey: 'YOUR_PUBLISHABLE_ORGANIZATION_ID' });
74
+ ```
75
+
76
+ With version **0.18.5 or later**, the client defers initial minting to browser
77
+ idle, reuses fresh `wd_clearance` cookies, and renews before expiry throughout
78
+ long sessions. Repeated startup shares one lifecycle and collected fingerprint
79
+ per page. Cookie changes from another tab are noticed during periodic checks;
80
+ returning to a visible page checks clearance again.
81
+
82
+ Mint requests time out after 10 seconds. Transient failures retry with backoff
83
+ from one minute to five minutes; explicit server refusal stops automatic
84
+ attempts on that page. Unsigned expiry is only a scheduling hint. The server and
85
+ edge validator continue to verify every token and enforce revocation.
86
+
87
+ The cookie is Secure, SameSite Lax and host-only. Accepted interaction aggregates
88
+ remain on renewal requests, and the server evaluates them again; pass
89
+ `behavior: false` to disable the behavioral upgrade. The client does not intercept
90
+ or retry application fetch/XHR requests globally. An edge API challenge is a JSON
91
+ 403; the opt-in helper below handles safe reads through your application’s flow.
92
+
68
93
  ## What it collects
69
94
 
70
95
  | Group | Signals |
@@ -106,3 +131,74 @@ and Next.js adapters and the full detection/scoring reference.
106
131
  ## License
107
132
 
108
133
  MIT
134
+
135
+ ## API challenge recovery
136
+
137
+ With `@webdecoy/client` **0.19.0 or later** and an updated edge validator, opt in
138
+ for the API reads your application wants to recover:
139
+
140
+ ```ts
141
+ import { createClearanceFetch } from '@webdecoy/client';
142
+ import { earnClearance } from './clearance-flow'; // your application's flow
143
+
144
+ const fetchProtected = createClearanceFetch({
145
+ origin: location.origin,
146
+ timeoutMs: 10_000,
147
+ recover: ({ origin, challenge, signal }) =>
148
+ earnClearance({ origin, reason: challenge.reason, signal }),
149
+ onEvent: event => console.debug(event.type, event.status),
150
+ });
151
+
152
+ const controller = new AbortController();
153
+ const response = await fetchProtected('/api/catalog', {
154
+ credentials: 'same-origin',
155
+ signal: controller.signal, // your application's AbortController
156
+ });
157
+ // Handle response.ok/status/body just as with native fetch.
158
+ ```
159
+
160
+ `earnClearance` is application code, not an SDK export. It must earn and install
161
+ the host's `wd_clearance` cookie through your configured issuance/verification
162
+ flow and return `true` only when ready to retry. `startClearance()` returns
163
+ `void`; awaiting it does not wait for a token. A self-hosted captcha widget token
164
+ is not a clearance cookie. A stronger-grade response needs a flow that earns the
165
+ route's required grade; simply replacing a token cannot grant that grade.
166
+
167
+ The helper retries **GET/HEAD once** after a recognized recoverable challenge.
168
+ Concurrent calls through one adapter share one recovery callback for its
169
+ configured origin; that callback receives the first challenge's reason. Use one
170
+ adapter for each origin/recovery flow. The edge evaluates every retry again.
171
+ POST/PATCH/PUT/DELETE and other methods pass through once with their original
172
+ body. There is no mutation replay opt-in and no XHR interception. The standalone
173
+ script exposes the same helpers at `window.WebDecoyClearance`.
174
+
175
+ Recovery and the retry share a deadline after the first challenge: 10 seconds by
176
+ default, configurable from 1 ms to 60 seconds. Refusal, resolver rejection,
177
+ offline state, or deadline expiry returns the original readable challenge
178
+ response. Caller cancellation and fetch network errors reject as native fetch
179
+ does. One cancelled caller does not cancel other callers waiting for the shared
180
+ flow; when none remain, the recovery signal aborts. Your flow must stop network
181
+ work and close its UI on that signal. If it ignores cancellation, later calls
182
+ remain attached to that stopped attempt until it settles, rather than opening
183
+ overlapping recovery dialogs. Browsers without `AbortSignal.any()` return the
184
+ challenge without attempting recovery.
185
+
186
+ Only version-1 responses with the exact WebDecoy challenge headers qualify.
187
+ Ordinary application 403s, unsupported/malformed contracts, revoked sessions,
188
+ crawler-policy refusals and agent impersonation do not trigger recovery.
189
+ Redirected responses, different origins and `credentials: 'omit'` also do not.
190
+ The helper preserves request options and leaves response bodies/streams unread.
191
+ It adds no request headers or CORS permission. Cross-origin calls need
192
+ `credentials: 'include'`, the protected host's cookie, and an application-approved
193
+ CORS policy that exposes the four challenge headers; otherwise the browser
194
+ cannot identify the response. A cookie set on the page's host does not clear a
195
+ different API host.
196
+
197
+ `onEvent` reports `challenge-served`, `recovery-attempted`,
198
+ `recovery-succeeded`/`recovery-failed`, and the retried `enforcement-outcome`
199
+ (status). Attempts are per waiting request; count callback invocations separately
200
+ for shared flows. Success means the retry returned an OK response, not a new
201
+ trust grade. These local observations send no telemetry automatically and must
202
+ remain distinct from the validator's verdict counts. Observation failures cannot
203
+ change the request. Interactive application flows must provide keyboard access,
204
+ focus restoration, an announced status and cancellation; the helper renders no UI.
package/dist/index.d.mts CHANGED
@@ -485,8 +485,8 @@ declare function sha256(message: string): Promise<string>;
485
485
  * normal browsing so the loop covers monitor mode, not just the enforce-mode
486
486
  * challenge interstitial.
487
487
  *
488
- * PERFORMANCE: the mint is deferred to idle, runs at most once per session (skips
489
- * when a fresh cookie already exists), and never solves a proof-of-work. The only
488
+ * PERFORMANCE: the initial mint is deferred to idle, fresh cookies are reused,
489
+ * renewal is bounded, and minting never solves a proof-of-work. The only
490
490
  * device-tier work — one canvas + one WebGL read — is done by the collector, once.
491
491
  * computeDeviceFP itself does NO canvas/WebGL: it consumes the collector's output.
492
492
  */
@@ -553,13 +553,53 @@ interface ClearanceOptions {
553
553
  behavior?: boolean;
554
554
  }
555
555
  /**
556
- * Start silent clearance minting. Idempotent guard, deferred to idle, at most once
557
- * per session: if a fresh cookie already exists it only schedules a refresh; only
558
- * an absent/near-expiry cookie triggers a collect + mint. Never blocks paint or
559
- * interaction; failures are swallowed (the edge validator fails open regardless).
556
+ * Start one silent clearance lifecycle. Initial work is deferred to idle; fresh
557
+ * cookies schedule renewal and only absent/near-expiry cookies trigger minting.
558
+ * Transient failures back off; server refusals stop automatic attempts. The edge
559
+ * remains authoritative, including when the browser cannot obtain clearance.
560
560
  */
561
561
  declare function startClearance(opts: ClearanceOptions): void;
562
562
 
563
+ /** An explicit fetch adapter. Does not replace window.fetch or intercept XHR. */
564
+ type ClearanceChallengeReason = 'missing' | 'invalid' | 'insufficient-trust' | 'revoked' | 'crawler-refused' | 'agent-impersonation' | 'denied';
565
+ interface ClearanceChallenge {
566
+ version: 1;
567
+ reason: ClearanceChallengeReason;
568
+ recoverable: boolean;
569
+ }
570
+ interface ClearanceRecoveryContext {
571
+ origin: string;
572
+ challenge: ClearanceChallenge;
573
+ /** Recovery UI/network work must stop when this signal aborts. */
574
+ signal: AbortSignal;
575
+ }
576
+ interface ClearanceFetchEvent {
577
+ type: 'challenge-served' | 'recovery-attempted' | 'recovery-succeeded' | 'recovery-failed' | 'enforcement-outcome';
578
+ origin: string;
579
+ method: string;
580
+ challenge: ClearanceChallenge;
581
+ status?: number;
582
+ }
583
+ interface ClearanceFetchOptions {
584
+ /** One explicitly trusted protected origin. Use one adapter per origin/recovery flow. */
585
+ origin: string;
586
+ /** Earn and install clearance for this origin; true permits one safe-read retry. */
587
+ recover(context: ClearanceRecoveryContext): Promise<boolean>;
588
+ /** Recovery and retry deadline after the challenge; default 10s, maximum 60s. */
589
+ timeoutMs?: number;
590
+ fetch?: typeof fetch;
591
+ /** Local observation hook; no telemetry is sent automatically. */
592
+ onEvent?(event: ClearanceFetchEvent): void;
593
+ }
594
+ /** Header-only recognition keeps the application response body/stream untouched. */
595
+ declare function readClearanceChallenge(response: Response): ClearanceChallenge | null;
596
+ /**
597
+ * GET/HEAD only, at most one retry per call. A callback's success is not trust:
598
+ * the validator re-evaluates the retried request. Refusal/timeout returns the
599
+ * original challenge response; caller cancellation and fetch errors reject.
600
+ */
601
+ declare function createClearanceFetch(options: ClearanceFetchOptions): typeof fetch;
602
+
563
603
  /**
564
604
  * Behavioral human-likelihood for clearance minting .
565
605
  *
@@ -626,4 +666,4 @@ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggr
626
666
  */
627
667
  declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
628
668
 
629
- export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceOptions, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, getFormAnalyzer, getPoWManager, hasEnoughInteraction, sha256, startClearance, summarizeBehavior, watchInteraction };
669
+ export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceChallenge, type ClearanceChallengeReason, type ClearanceFetchEvent, type ClearanceFetchOptions, type ClearanceOptions, type ClearanceRecoveryContext, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, createClearanceFetch, getFormAnalyzer, getPoWManager, hasEnoughInteraction, readClearanceChallenge, sha256, startClearance, summarizeBehavior, watchInteraction };
package/dist/index.d.ts CHANGED
@@ -485,8 +485,8 @@ declare function sha256(message: string): Promise<string>;
485
485
  * normal browsing so the loop covers monitor mode, not just the enforce-mode
486
486
  * challenge interstitial.
487
487
  *
488
- * PERFORMANCE: the mint is deferred to idle, runs at most once per session (skips
489
- * when a fresh cookie already exists), and never solves a proof-of-work. The only
488
+ * PERFORMANCE: the initial mint is deferred to idle, fresh cookies are reused,
489
+ * renewal is bounded, and minting never solves a proof-of-work. The only
490
490
  * device-tier work — one canvas + one WebGL read — is done by the collector, once.
491
491
  * computeDeviceFP itself does NO canvas/WebGL: it consumes the collector's output.
492
492
  */
@@ -553,13 +553,53 @@ interface ClearanceOptions {
553
553
  behavior?: boolean;
554
554
  }
555
555
  /**
556
- * Start silent clearance minting. Idempotent guard, deferred to idle, at most once
557
- * per session: if a fresh cookie already exists it only schedules a refresh; only
558
- * an absent/near-expiry cookie triggers a collect + mint. Never blocks paint or
559
- * interaction; failures are swallowed (the edge validator fails open regardless).
556
+ * Start one silent clearance lifecycle. Initial work is deferred to idle; fresh
557
+ * cookies schedule renewal and only absent/near-expiry cookies trigger minting.
558
+ * Transient failures back off; server refusals stop automatic attempts. The edge
559
+ * remains authoritative, including when the browser cannot obtain clearance.
560
560
  */
561
561
  declare function startClearance(opts: ClearanceOptions): void;
562
562
 
563
+ /** An explicit fetch adapter. Does not replace window.fetch or intercept XHR. */
564
+ type ClearanceChallengeReason = 'missing' | 'invalid' | 'insufficient-trust' | 'revoked' | 'crawler-refused' | 'agent-impersonation' | 'denied';
565
+ interface ClearanceChallenge {
566
+ version: 1;
567
+ reason: ClearanceChallengeReason;
568
+ recoverable: boolean;
569
+ }
570
+ interface ClearanceRecoveryContext {
571
+ origin: string;
572
+ challenge: ClearanceChallenge;
573
+ /** Recovery UI/network work must stop when this signal aborts. */
574
+ signal: AbortSignal;
575
+ }
576
+ interface ClearanceFetchEvent {
577
+ type: 'challenge-served' | 'recovery-attempted' | 'recovery-succeeded' | 'recovery-failed' | 'enforcement-outcome';
578
+ origin: string;
579
+ method: string;
580
+ challenge: ClearanceChallenge;
581
+ status?: number;
582
+ }
583
+ interface ClearanceFetchOptions {
584
+ /** One explicitly trusted protected origin. Use one adapter per origin/recovery flow. */
585
+ origin: string;
586
+ /** Earn and install clearance for this origin; true permits one safe-read retry. */
587
+ recover(context: ClearanceRecoveryContext): Promise<boolean>;
588
+ /** Recovery and retry deadline after the challenge; default 10s, maximum 60s. */
589
+ timeoutMs?: number;
590
+ fetch?: typeof fetch;
591
+ /** Local observation hook; no telemetry is sent automatically. */
592
+ onEvent?(event: ClearanceFetchEvent): void;
593
+ }
594
+ /** Header-only recognition keeps the application response body/stream untouched. */
595
+ declare function readClearanceChallenge(response: Response): ClearanceChallenge | null;
596
+ /**
597
+ * GET/HEAD only, at most one retry per call. A callback's success is not trust:
598
+ * the validator re-evaluates the retried request. Refusal/timeout returns the
599
+ * original challenge response; caller cancellation and fetch errors reject.
600
+ */
601
+ declare function createClearanceFetch(options: ClearanceFetchOptions): typeof fetch;
602
+
563
603
  /**
564
604
  * Behavioral human-likelihood for clearance minting .
565
605
  *
@@ -626,4 +666,4 @@ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggr
626
666
  */
627
667
  declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
628
668
 
629
- export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceOptions, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, getFormAnalyzer, getPoWManager, hasEnoughInteraction, sha256, startClearance, summarizeBehavior, watchInteraction };
669
+ export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceChallenge, type ClearanceChallengeReason, type ClearanceFetchEvent, type ClearanceFetchOptions, type ClearanceOptions, type ClearanceRecoveryContext, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, createClearanceFetch, getFormAnalyzer, getPoWManager, hasEnoughInteraction, readClearanceChallenge, sha256, startClearance, summarizeBehavior, watchInteraction };
package/dist/index.js CHANGED
@@ -33,9 +33,11 @@ __export(src_exports, {
33
33
  TemporalCollector: () => TemporalCollector,
34
34
  WebDecoyCaptcha: () => WebDecoyCaptcha,
35
35
  computeDeviceFP: () => computeDeviceFP,
36
+ createClearanceFetch: () => createClearanceFetch,
36
37
  getFormAnalyzer: () => getFormAnalyzer,
37
38
  getPoWManager: () => getPoWManager,
38
39
  hasEnoughInteraction: () => hasEnoughInteraction,
40
+ readClearanceChallenge: () => readClearanceChallenge,
39
41
  sha256: () => sha256,
40
42
  startClearance: () => startClearance,
41
43
  summarizeBehavior: () => summarizeBehavior,
@@ -2352,20 +2354,20 @@ var WebDecoyCaptcha = {
2352
2354
  if (widget instanceof CaptchaWidget) widget.reset();
2353
2355
  },
2354
2356
  invisible(options) {
2355
- const session = new InvisibleSession(options);
2356
- this.widgets.set(session.id, session);
2357
- return session;
2357
+ const session2 = new InvisibleSession(options);
2358
+ this.widgets.set(session2.id, session2);
2359
+ return session2;
2358
2360
  },
2359
2361
  async execute(siteKey, options = {}) {
2360
- const session = new InvisibleSession({
2362
+ const session2 = new InvisibleSession({
2361
2363
  siteKey,
2362
2364
  serverUrl: getServerUrl(),
2363
2365
  minCollectionTime: options.minTime || 1e3,
2364
2366
  autoScore: false,
2365
2367
  powDifficulty: options.powDifficulty || 3
2366
2368
  });
2367
- const result = await session.execute(options.action || "");
2368
- session.destroy();
2369
+ const result = await session2.execute(options.action || "");
2370
+ session2.destroy();
2369
2371
  return result;
2370
2372
  },
2371
2373
  getSignals() {
@@ -2488,7 +2490,13 @@ async function computeDeviceFP(env) {
2488
2490
  const lang = navigator.language || "na";
2489
2491
  return sha256([FP_VERSION, canvas, webgl, scr, tz, plat, lang].join("|"));
2490
2492
  }
2493
+ var REFRESH_MARGIN_MS = 12e4;
2494
+ var COOKIE_CHECK_MS = 6e4;
2495
+ var MAX_TOKEN_AGE_MS = 18e5;
2496
+ var MINT_TIMEOUT_MS = 1e4;
2491
2497
  async function mint(ingestUrl, siteKey, fp, scope, behavior) {
2498
+ const abort = new AbortController();
2499
+ const timeout = setTimeout(() => abort.abort(), MINT_TIMEOUT_MS);
2492
2500
  try {
2493
2501
  const res = await fetch(ingestUrl.replace(/\/$/, "") + "/api/v1/clearance", {
2494
2502
  method: "POST",
@@ -2501,13 +2509,19 @@ async function mint(ingestUrl, siteKey, fp, scope, behavior) {
2501
2509
  webdriver: navigator.webdriver === true,
2502
2510
  headless: /HeadlessChrome/.test(navigator.userAgent),
2503
2511
  ...behavior ? { behavior } : {}
2504
- })
2512
+ }),
2513
+ signal: abort.signal
2505
2514
  });
2515
+ if (!res.ok) return null;
2506
2516
  const out = await res.json();
2507
2517
  if (out.granted && out.token) {
2508
- return { token: out.token, expiresIn: out.expires_in || 1800 };
2518
+ const ttl = out.expires_in;
2519
+ return { token: out.token, expiresIn: typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0 ? Math.min(ttl, 1800) : 1800 };
2509
2520
  }
2521
+ if (out.granted === false) return { denied: true };
2510
2522
  } catch {
2523
+ } finally {
2524
+ clearTimeout(timeout);
2511
2525
  }
2512
2526
  return null;
2513
2527
  }
@@ -2525,54 +2539,252 @@ function setClearanceCookie(token, maxAgeSec) {
2525
2539
  function whenIdle(fn) {
2526
2540
  const ric = window.requestIdleCallback;
2527
2541
  if (typeof ric === "function") {
2528
- ric(fn);
2542
+ ric.call(window, fn, { timeout: 1200 });
2529
2543
  } else {
2530
2544
  setTimeout(fn, 1200);
2531
2545
  }
2532
2546
  }
2533
2547
  var upgradeStarted = false;
2534
- function startBehavioralUpgrade(ingestUrl, siteKey, scope) {
2548
+ var session;
2549
+ function expiryHint(token) {
2550
+ try {
2551
+ const encoded = token.split(".")[0];
2552
+ if (encoded.length > 8192) return Date.now() + COOKIE_CHECK_MS + REFRESH_MARGIN_MS;
2553
+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
2554
+ const exp = JSON.parse(atob(base64)).exp;
2555
+ if (typeof exp === "number" && Number.isFinite(exp) && exp > 0) {
2556
+ return Math.min(exp * 1e3, Date.now() + MAX_TOKEN_AGE_MS);
2557
+ }
2558
+ } catch {
2559
+ }
2560
+ return Date.now() + COOKIE_CHECK_MS + REFRESH_MARGIN_MS;
2561
+ }
2562
+ function schedule(s, delay) {
2563
+ if (s.timer !== void 0) clearTimeout(s.timer);
2564
+ if (s !== session || s.stopped) return;
2565
+ s.timer = setTimeout(() => {
2566
+ s.timer = void 0;
2567
+ void maintain(s);
2568
+ }, Math.max(1e3, delay));
2569
+ }
2570
+ async function maintain(s) {
2571
+ if (s !== session || s.stopped || s.running) return;
2572
+ const token = readCookie(CLEARANCE_COOKIE);
2573
+ if (token !== s.token) {
2574
+ s.token = token;
2575
+ s.expiresAt = token ? expiryHint(token) : 0;
2576
+ s.renewAt = s.expiresAt - Math.min(REFRESH_MARGIN_MS, Math.max(0, s.expiresAt - Date.now()) / 3);
2577
+ }
2578
+ if (s.retryAt > Date.now()) {
2579
+ schedule(s, s.retryAt - Date.now());
2580
+ return;
2581
+ }
2582
+ if (!s.behavior && token && s.renewAt > Date.now()) {
2583
+ schedule(s, Math.min(COOKIE_CHECK_MS, s.renewAt - Date.now()));
2584
+ return;
2585
+ }
2586
+ s.running = true;
2587
+ const behavior = s.behavior;
2588
+ s.behavior = void 0;
2589
+ try {
2590
+ if (!s.fingerprint) {
2591
+ s.fingerprint = (async () => {
2592
+ const env = new EnvironmentalCollector();
2593
+ return computeDeviceFP({ canvasHash: env._getCanvasHash(), webglInfo: env._getWebGLInfo() });
2594
+ })();
2595
+ }
2596
+ const fp = await s.fingerprint;
2597
+ const result = await mint(s.opts.ingestUrl || DEFAULT_INGEST_URL, s.opts.siteKey, fp, s.opts.scope || "", behavior || s.lastBehavior);
2598
+ if (s !== session) return;
2599
+ if (result && "token" in result) {
2600
+ setClearanceCookie(result.token, result.expiresIn);
2601
+ s.token = readCookie(CLEARANCE_COOKIE);
2602
+ s.expiresAt = Date.now() + result.expiresIn * 1e3;
2603
+ s.renewAt = s.expiresAt - Math.min(REFRESH_MARGIN_MS, result.expiresIn * 1e3 / 3);
2604
+ s.failures = 0;
2605
+ if (behavior) s.lastBehavior = behavior;
2606
+ s.retryAt = 0;
2607
+ schedule(s, Math.min(COOKIE_CHECK_MS, s.renewAt - Date.now()));
2608
+ } else if (result && "denied" in result) {
2609
+ s.stopped = true;
2610
+ if (s.timer !== void 0) clearTimeout(s.timer);
2611
+ } else {
2612
+ s.failures++;
2613
+ const delay = Math.min(3e5, COOKIE_CHECK_MS * Math.pow(2, Math.min(s.failures - 1, 3)));
2614
+ s.retryAt = Date.now() + delay;
2615
+ schedule(s, delay);
2616
+ }
2617
+ } catch {
2618
+ s.fingerprint = void 0;
2619
+ s.failures++;
2620
+ const delay = Math.min(3e5, COOKIE_CHECK_MS * Math.pow(2, Math.min(s.failures - 1, 3)));
2621
+ s.retryAt = Date.now() + delay;
2622
+ schedule(s, delay);
2623
+ } finally {
2624
+ s.running = false;
2625
+ if (s.behavior && !s.stopped && s === session) schedule(s, 1e3);
2626
+ }
2627
+ }
2628
+ function startBehavioralUpgrade(s) {
2535
2629
  if (upgradeStarted) return;
2536
2630
  upgradeStarted = true;
2537
2631
  watchInteraction((behavior) => {
2538
- void (async () => {
2539
- try {
2540
- const env = new EnvironmentalCollector();
2541
- const fp = await computeDeviceFP({
2542
- canvasHash: env._getCanvasHash(),
2543
- webglInfo: env._getWebGLInfo()
2544
- });
2545
- const minted = await mint(ingestUrl, siteKey, fp, scope, behavior);
2546
- if (minted) setClearanceCookie(minted.token, minted.expiresIn);
2547
- } catch {
2548
- }
2549
- })();
2632
+ if (s !== session || s.stopped) return;
2633
+ s.behavior = behavior;
2634
+ void maintain(s);
2550
2635
  });
2551
2636
  }
2552
2637
  function startClearance(opts) {
2553
2638
  if (!opts.siteKey || typeof document === "undefined") return;
2554
2639
  const ingestUrl = opts.ingestUrl || DEFAULT_INGEST_URL;
2555
- const scope = opts.scope || "";
2556
- const run = async () => {
2557
- if (readCookie(CLEARANCE_COOKIE)) {
2558
- return;
2559
- }
2560
- const env = new EnvironmentalCollector();
2561
- const fp = await computeDeviceFP({
2562
- canvasHash: env._getCanvasHash(),
2563
- webglInfo: env._getWebGLInfo()
2640
+ const key = JSON.stringify([ingestUrl.replace(/\/$/, ""), opts.siteKey, opts.scope || ""]);
2641
+ if (!session || session.key !== key) {
2642
+ if (session) {
2643
+ if (session.timer !== void 0) clearTimeout(session.timer);
2644
+ document.removeEventListener("visibilitychange", session.wake);
2645
+ }
2646
+ upgradeStarted = false;
2647
+ const s = {
2648
+ key,
2649
+ opts: { ...opts },
2650
+ token: null,
2651
+ expiresAt: 0,
2652
+ renewAt: 0,
2653
+ retryAt: 0,
2654
+ running: false,
2655
+ stopped: false,
2656
+ failures: 0,
2657
+ wake: () => {
2658
+ if (document.visibilityState === "visible") void maintain(s);
2659
+ }
2660
+ };
2661
+ session = s;
2662
+ document.addEventListener("visibilitychange", s.wake);
2663
+ whenIdle(() => {
2664
+ void maintain(s);
2564
2665
  });
2565
- const minted = await mint(ingestUrl, opts.siteKey, fp, scope);
2566
- if (minted) {
2567
- setClearanceCookie(minted.token, minted.expiresIn);
2568
- const refreshMs = Math.max(6e4, (minted.expiresIn - 120) * 1e3);
2569
- setTimeout(() => startClearance(opts), refreshMs);
2666
+ }
2667
+ if (opts.behavior !== false) {
2668
+ startBehavioralUpgrade(session);
2669
+ }
2670
+ }
2671
+
2672
+ // src/clearance-fetch.ts
2673
+ var reasons = ["missing", "invalid", "insufficient-trust", "revoked", "crawler-refused", "agent-impersonation", "denied"];
2674
+ var recoverableReasons = ["missing", "invalid", "insufficient-trust"];
2675
+ function readClearanceChallenge(response) {
2676
+ if (response.status !== 403 || response.headers.get("x-wd-clearance") !== "challenged" || response.headers.get("x-wd-challenge") !== "1") return null;
2677
+ const reason = response.headers.get("x-wd-challenge-reason");
2678
+ const recovery = response.headers.get("x-wd-challenge-recoverable");
2679
+ if (!reason || !reasons.includes(reason) || recovery !== "true" && recovery !== "false") return null;
2680
+ return { version: 1, reason, recoverable: recovery === "true" && recoverableReasons.includes(reason) };
2681
+ }
2682
+ function abortError(signal) {
2683
+ var _a;
2684
+ return (_a = signal.reason) != null ? _a : new DOMException("The operation was aborted", "AbortError");
2685
+ }
2686
+ function abortable(promise, signal) {
2687
+ return new Promise((resolve, reject) => {
2688
+ if (signal.aborted) {
2689
+ reject(abortError(signal));
2690
+ return;
2570
2691
  }
2571
- };
2572
- whenIdle(() => {
2573
- void run();
2692
+ const onAbort = () => reject(abortError(signal));
2693
+ signal.addEventListener("abort", onAbort, { once: true });
2694
+ void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2574
2695
  });
2575
- if (opts.behavior !== false) {
2576
- startBehavioralUpgrade(ingestUrl, opts.siteKey, scope);
2696
+ }
2697
+ function createClearanceFetch(options) {
2698
+ var _a, _b;
2699
+ const parsedOrigin = new URL(options.origin);
2700
+ if (!["http:", "https:"].includes(parsedOrigin.protocol) || parsedOrigin.username || parsedOrigin.password || parsedOrigin.pathname !== "/" || parsedOrigin.search || parsedOrigin.hash) throw new TypeError("A protected HTTP(S) origin is required");
2701
+ const origin = parsedOrigin.origin;
2702
+ const timeoutMs = (_a = options.timeoutMs) != null ? _a : 1e4;
2703
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4) throw new RangeError("timeoutMs must be between 1 and 60000");
2704
+ const nativeFetch = (_b = options.fetch) != null ? _b : globalThis.fetch.bind(globalThis);
2705
+ let recovery;
2706
+ function observe(type, method, challenge, status) {
2707
+ var _a2;
2708
+ try {
2709
+ (_a2 = options.onEvent) == null ? void 0 : _a2.call(options, { type, origin, method, challenge, status });
2710
+ } catch {
2711
+ }
2577
2712
  }
2713
+ function joinRecovery(challenge) {
2714
+ if (!recovery) {
2715
+ const controller = new AbortController();
2716
+ const entry = { controller, users: 0, promise: Promise.resolve(false) };
2717
+ recovery = entry;
2718
+ const timer = setTimeout(() => controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError")), timeoutMs);
2719
+ controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
2720
+ const actual = Promise.resolve().then(() => options.recover({ origin, challenge, signal: controller.signal }));
2721
+ entry.promise = abortable(actual, controller.signal).then((value) => value === true, () => false);
2722
+ const settled = () => {
2723
+ clearTimeout(timer);
2724
+ if (recovery === entry) recovery = void 0;
2725
+ };
2726
+ void actual.then(settled, settled);
2727
+ }
2728
+ recovery.users++;
2729
+ return recovery;
2730
+ }
2731
+ return async (input, init) => {
2732
+ var _a2, _b2;
2733
+ const method = ((_a2 = init == null ? void 0 : init.method) != null ? _a2 : input instanceof Request ? input.method : "GET").toUpperCase();
2734
+ if (method !== "GET" && method !== "HEAD") {
2735
+ const response2 = await nativeFetch(input, init);
2736
+ const url = input instanceof Request ? input.url : String(input);
2737
+ const target = new URL(url, typeof document !== "undefined" ? document.baseURI : void 0);
2738
+ const challenge2 = readClearanceChallenge(response2);
2739
+ if (challenge2 && target.origin === origin && !response2.redirected && (!response2.url || new URL(response2.url).origin === origin)) observe("challenge-served", method, challenge2, response2.status);
2740
+ return response2;
2741
+ }
2742
+ const requestInput = input instanceof Request ? input : new URL(String(input), typeof document !== "undefined" ? document.baseURI : void 0).href;
2743
+ const request = new Request(requestInput, init);
2744
+ const response = await nativeFetch(request);
2745
+ const challenge = readClearanceChallenge(response);
2746
+ if (!challenge || new URL(request.url).origin !== origin || response.redirected || response.url && new URL(response.url).origin !== origin) return response;
2747
+ observe("challenge-served", method, challenge, response.status);
2748
+ const pageOrigin = typeof location !== "undefined" ? location.origin : origin;
2749
+ if (!challenge.recoverable || request.credentials === "omit" || pageOrigin !== origin && request.credentials !== "include" || typeof navigator !== "undefined" && navigator.onLine === false || typeof AbortSignal.any !== "function") return response;
2750
+ if (request.signal.aborted) throw abortError(request.signal);
2751
+ const controller = new AbortController();
2752
+ let timedOut = false;
2753
+ const onAbort = () => controller.abort(abortError(request.signal));
2754
+ request.signal.addEventListener("abort", onAbort, { once: true });
2755
+ const timer = setTimeout(() => {
2756
+ timedOut = true;
2757
+ controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError"));
2758
+ }, timeoutMs);
2759
+ const entry = joinRecovery(challenge);
2760
+ observe("recovery-attempted", method, challenge);
2761
+ let released = false;
2762
+ const release = () => {
2763
+ if (released) return;
2764
+ released = true;
2765
+ if (--entry.users === 0) entry.controller.abort();
2766
+ };
2767
+ try {
2768
+ const ready = await abortable(entry.promise, controller.signal);
2769
+ release();
2770
+ if (!ready || controller.signal.aborted) {
2771
+ observe("recovery-failed", method, challenge);
2772
+ return response;
2773
+ }
2774
+ const retrySignal = AbortSignal.any([request.signal, controller.signal]);
2775
+ const retried = await abortable(nativeFetch(new Request(request, { signal: retrySignal })), controller.signal);
2776
+ observe("enforcement-outcome", method, (_b2 = readClearanceChallenge(retried)) != null ? _b2 : challenge, retried.status);
2777
+ observe(retried.ok ? "recovery-succeeded" : "recovery-failed", method, challenge, retried.status);
2778
+ return retried;
2779
+ } catch (error) {
2780
+ observe("recovery-failed", method, challenge);
2781
+ if (request.signal.aborted) throw abortError(request.signal);
2782
+ if (timedOut) return response;
2783
+ throw error;
2784
+ } finally {
2785
+ release();
2786
+ clearTimeout(timer);
2787
+ request.signal.removeEventListener("abort", onAbort);
2788
+ }
2789
+ };
2578
2790
  }