@zeldrisho/pi-web-fetch 0.18.0 → 0.18.2

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/src/service.ts CHANGED
@@ -9,12 +9,17 @@ import {
9
9
  type AgentToolResult,
10
10
  } from "@earendil-works/pi-coding-agent";
11
11
  import { ExpiringLruCache, stableKeyHash, canonicalKey, type CachePersistence } from "./cache";
12
- import { sliceCompleteDocument, type CompleteDocument } from "./document/content.ts";
12
+ import {
13
+ MAX_CACHED_FRAGMENT_TABS,
14
+ sliceCompleteDocument,
15
+ type CompleteDocument,
16
+ } from "./document/content.ts";
13
17
  import { revalidateCompleteDocument, type FetchRemoteDependencies } from "./acquisition/fetch.ts";
14
18
  import { fetchDocumentWithLlmsTxtSupport } from "./acquisition/llms.ts";
19
+ import { extractHtmlToMarkdown, filterAndroidBomHtml } from "./document/extract.ts";
15
20
  import { focusMarkdown, type FocusDetails } from "./document/focus.ts";
16
21
  import { isCachedOpenapi } from "./document/openapi.ts";
17
- import { resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
22
+ import { fragmentTabId, resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
18
23
  import { InflightCoalescer } from "./inflight";
19
24
  import { createDocumentOutline, type DocumentOutline } from "./document/outline.ts";
20
25
  import { redactUrlForDisplay } from "./redact";
@@ -27,16 +32,40 @@ import {
27
32
  FETCH_MIN_MAX_CHARACTERS,
28
33
  } from "./limits";
29
34
 
30
- const CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
35
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
31
36
 
32
37
  const CACHE_STALE_RETENTION_MS = 7 * CACHE_TTL_MS;
33
38
 
39
+ // Bump when HTML extraction changes must invalidate persisted results, even fresh ones.
40
+ const HTML_EXTRACTION_CACHE_VERSION = 2;
41
+
34
42
  const CACHE_MAX_ENTRIES = 100;
35
43
 
36
- const CACHE_MAX_MARKDOWN_BYTES = 20 * 1_024 * 1_024;
44
+ const CACHE_MAX_MARKDOWN_BYTES = 20 * 1024 * 1024;
37
45
 
38
46
  const MAX_INFLIGHT_REQUESTS = 100;
39
47
 
48
+ interface CacheDimensions {
49
+ surfaceExtraction?: number;
50
+ androidBomVersion?: string;
51
+ }
52
+
53
+ function androidBomVersionQuery(url: string, query: string | undefined): string | undefined {
54
+ if (query === undefined || !/^\d{4}\.\d{2}\.\d{2}$/.test(query.trim())) return undefined;
55
+
56
+ try {
57
+ const parsed = new URL(url);
58
+
59
+ return parsed.protocol === "https:" &&
60
+ parsed.hostname === "developer.android.com" &&
61
+ parsed.pathname === "/develop/ui/compose/bom/bom-mapping"
62
+ ? query.trim()
63
+ : undefined;
64
+ } catch {
65
+ return undefined;
66
+ }
67
+ }
68
+
40
69
  /** Minimum extracted length for both the low-quality trigger and llms.txt acceptance. */
41
70
  const encoder = new TextEncoder();
42
71
 
@@ -120,8 +149,9 @@ export function classifyContentKind(
120
149
 
121
150
  if (path === "/llms.txt" || path.endsWith("/llms.txt")) return "llms-index";
122
151
 
123
- if (host === "raw.githubusercontent.com" || host === "gist.githubusercontent.com")
152
+ if (host === "raw.githubusercontent.com" || host === "gist.githubusercontent.com") {
124
153
  return "code-file";
154
+ }
125
155
 
126
156
  if (host === "github.com") {
127
157
  const segments = path.split("/").filter(Boolean);
@@ -212,6 +242,8 @@ export interface WebFetchDetails {
212
242
  llmsTxtFallback: boolean;
213
243
  /** True when the returned content is the page's advertised Markdown version served instead of a low-quality page. */
214
244
  markdownAlternateFallback: boolean;
245
+ /** True when the returned content is the page's authored no-JavaScript fallback. */
246
+ noscriptFallback: boolean;
215
247
  /** Identifies an API or specification used instead of the page. */
216
248
  representationFallback?: CompleteDocument["representationFallback"];
217
249
  /** The site's /llms.txt index URL when one exists and the returned content is not that index itself. */
@@ -229,7 +261,7 @@ export interface WebFetchDetails {
229
261
  }
230
262
 
231
263
  interface WebFetchUpdate {
232
- content: Array<{ type: "text"; text: string }>;
264
+ content: { type: "text"; text: string }[];
233
265
  details: Record<string, never>;
234
266
  }
235
267
 
@@ -252,6 +284,7 @@ export interface WebFetchStructuredOutput {
252
284
  characterCount: number;
253
285
  llmsTxtFallback: boolean;
254
286
  markdownAlternateFallback: boolean;
287
+ noscriptFallback: boolean;
255
288
  representationFallback?: CompleteDocument["representationFallback"];
256
289
  extraction?: CompleteDocument["extractionDiagnostics"];
257
290
  focus?: FocusDetails;
@@ -279,6 +312,7 @@ export const webFetchOutputSchema = Type.Object({
279
312
  characterCount: Type.Integer(),
280
313
  llmsTxtFallback: Type.Boolean(),
281
314
  markdownAlternateFallback: Type.Boolean(),
315
+ noscriptFallback: Type.Boolean(),
282
316
  representationFallback: Type.Optional(
283
317
  Type.Union([Type.Literal("packit-api"), Type.Literal("swagger-spec")]),
284
318
  ),
@@ -322,10 +356,14 @@ const completeDocumentCacheSchema = Type.Object(
322
356
  url: Type.String(),
323
357
  contentType: Type.String(),
324
358
  markdown: Type.String(),
359
+ fragmentTabs: Type.Optional(
360
+ Type.Array(Type.String({ maxLength: 80 }), { maxItems: MAX_CACHED_FRAGMENT_TABS }),
361
+ ),
325
362
  surfaceView: Type.Optional(
326
363
  Type.Object({
327
- selected: Type.String({ maxLength: 40 }),
364
+ selected: Type.String({ maxLength: 80 }),
328
365
  omitted: Type.Integer({ minimum: 1, maximum: 19 }),
366
+ fragmentSelected: Type.Optional(Type.Literal(true)),
329
367
  markdown: Type.String(),
330
368
  fragmentOffsets: Type.Optional(Type.Record(Type.String(), Type.Number())),
331
369
  }),
@@ -369,6 +407,8 @@ const completeDocumentCacheSchema = Type.Object(
369
407
  lastModified: Type.Optional(Type.String()),
370
408
  }),
371
409
  ),
410
+ markdownPolicyVersion: Type.Optional(Type.Literal(2)),
411
+ noscriptFallback: Type.Optional(Type.Boolean()),
372
412
  llmsTxtFallback: Type.Optional(Type.Boolean()),
373
413
  llmsTxtIndexUrl: Type.Optional(Type.String()),
374
414
  llmsTxtDescribedBy: Type.Optional(Type.String()),
@@ -378,13 +418,27 @@ const completeDocumentCacheSchema = Type.Object(
378
418
  { additionalProperties: true },
379
419
  );
380
420
 
421
+ const htmlExtractionCacheMarker = Type.Object({
422
+ htmlExtractionCacheVersion: Type.Literal(HTML_EXTRACTION_CACHE_VERSION),
423
+ });
424
+
381
425
  function isCompleteDocument(value: CompleteDocument): boolean {
382
- return Check(completeDocumentCacheSchema, value);
426
+ return (
427
+ Check(completeDocumentCacheSchema, value) &&
428
+ (value.extractor === "raw" || Check(htmlExtractionCacheMarker, value))
429
+ );
383
430
  }
384
431
 
385
432
  const fetchCachePersistence: CachePersistence<string, CompleteDocument> = {
386
433
  directory: resolveCacheDirectory("pi-web-fetch"),
387
- serialize: (document) => encoder.encode(JSON.stringify(document)),
434
+ serialize: (document) =>
435
+ encoder.encode(
436
+ JSON.stringify(
437
+ document.extractor === "raw"
438
+ ? document
439
+ : { ...document, htmlExtractionCacheVersion: HTML_EXTRACTION_CACHE_VERSION },
440
+ ),
441
+ ),
388
442
  // SAFETY: JSON is validated immediately below before entering the cache.
389
443
  deserialize: (bytes) => JSON.parse(new TextDecoder().decode(bytes)) as CompleteDocument,
390
444
  validate: isCompleteDocument,
@@ -396,7 +450,8 @@ const fetchCache = new ExpiringLruCache<string, CompleteDocument>(
396
450
  CACHE_MAX_MARKDOWN_BYTES,
397
451
  (document) =>
398
452
  encoder.encode(document.markdown).byteLength +
399
- encoder.encode(document.surfaceView?.markdown ?? "").byteLength,
453
+ encoder.encode(document.surfaceView?.markdown ?? "").byteLength +
454
+ (document.fragmentTabs?.reduce((length, id) => length + id.length, 0) ?? 0),
400
455
  undefined,
401
456
  fetchCachePersistence,
402
457
  );
@@ -408,6 +463,17 @@ interface FetchAcquisition {
408
463
 
409
464
  const inflightFetches = new InflightCoalescer<string, FetchAcquisition>(MAX_INFLIGHT_REQUESTS);
410
465
 
466
+ /** Returns whether a stale entry predates the Markdown-preference cache policy. */
467
+ export function staleCacheNeedsMarkdownPolicy(document: CompleteDocument): boolean {
468
+ return (
469
+ document.markdownPolicyVersion !== 2 &&
470
+ document.extractor !== "raw" &&
471
+ !document.surfaceView &&
472
+ !document.llmsTxtFallback &&
473
+ !document.representationFallback
474
+ );
475
+ }
476
+
411
477
  /**
412
478
  * Executes a validated web fetch, including caching, focusing, and bounded pagination.
413
479
  *
@@ -463,27 +529,54 @@ export async function executeWebFetch(
463
529
  );
464
530
  }
465
531
 
466
- if (params.url.length < 1 || params.url.length > 2_048) {
532
+ if (params.url.length < 1 || params.url.length > 2048) {
467
533
  throw new Error("web_fetch url must contain between 1 and 2048 characters.");
468
534
  }
469
535
 
470
536
  const displayRequestedUrl = redactUrlForDisplay(params.url);
471
537
  const sourceUrl = urlWithoutFragment(params.url);
538
+ const fragmentTab = fragmentTabId(params.url);
539
+ const bomVersion = androidBomVersionQuery(sourceUrl, params.query);
472
540
 
473
541
  // Older persisted entries predate surface views and must not mask explicit selections.
474
- const cacheKey = safeUrl(sourceUrl)?.searchParams.has("tab")
475
- ? canonicalKey({ url: sourceUrl, surfaceExtraction: 1 })
476
- : canonicalKey({ url: sourceUrl });
542
+ const cacheDimensions: CacheDimensions = {};
543
+
544
+ if (safeUrl(sourceUrl)?.searchParams.has("tab")) cacheDimensions.surfaceExtraction = 1;
477
545
 
478
- let document = fetchCache.get(cacheKey);
546
+ if (bomVersion) cacheDimensions.androidBomVersion = bomVersion;
547
+
548
+ const cacheKey = canonicalKey({ url: sourceUrl, ...cacheDimensions });
549
+ const tabKey = fragmentTab
550
+ ? canonicalKey({ url: sourceUrl, ...cacheDimensions, fragmentTab })
551
+ : undefined;
552
+ const canonical = fetchCache.get(cacheKey);
479
553
  const now = Date.now();
554
+ const isFresh = (entry: CompleteDocument | undefined): boolean =>
555
+ Boolean(
556
+ entry &&
557
+ !entry.llmsTxtFallback &&
558
+ !entry.extractionDiagnostics?.botWall &&
559
+ (entry.cachedAt === undefined || now - entry.cachedAt < CACHE_TTL_MS),
560
+ );
561
+ const canonicalMatches =
562
+ !fragmentTab ||
563
+ (canonical?.fragmentTabs
564
+ ? !canonical.fragmentTabs.includes(fragmentTab)
565
+ : canonical?.extractor === "raw" &&
566
+ !canonical.markdownAlternateFallback &&
567
+ !canonical.representationFallback &&
568
+ !canonical.llmsTxtFallback);
569
+ let document = canonicalMatches ? canonical : undefined;
570
+
571
+ if (fragmentTab && tabKey && !isFresh(document)) {
572
+ const tab = fetchCache.get(tabKey);
573
+
574
+ if (tab?.surfaceView?.fragmentSelected && tab.surfaceView.selected === fragmentTab) {
575
+ document = tab;
576
+ }
577
+ }
480
578
 
481
- const fresh = Boolean(
482
- document &&
483
- !document.llmsTxtFallback &&
484
- !document.extractionDiagnostics?.botWall &&
485
- (document.cachedAt === undefined || now - document.cachedAt < CACHE_TTL_MS),
486
- );
579
+ const fresh = isFresh(document);
487
580
 
488
581
  let cacheStatus: CacheStatus = fresh ? "hit" : "miss";
489
582
  onUpdate?.({
@@ -502,42 +595,69 @@ export async function executeWebFetch(
502
595
 
503
596
  if (!fresh) {
504
597
  const stale = document;
598
+ const acquisitionDependencies: FetchRemoteDependencies =
599
+ bomVersion || fragmentTab
600
+ ? {
601
+ ...dependencies,
602
+ extractHtml: async (html, url) => {
603
+ if (!bomVersion) {
604
+ return (dependencies.extractHtml ?? extractHtmlToMarkdown)(html, url, fragmentTab);
605
+ }
606
+
607
+ const filtered = filterAndroidBomHtml(html, bomVersion);
608
+
609
+ if (filtered === undefined) {
610
+ throw new Error(`web_fetch: Android BOM version ${bomVersion} was not found.`);
611
+ }
612
+
613
+ return extractHtmlToMarkdown(filtered, url, fragmentTab);
614
+ },
615
+ }
616
+ : dependencies;
505
617
 
618
+ // Keep pending fragment selections separate until extraction identifies the view.
506
619
  const acquisition = await inflightFetches.run(
507
- cacheKey,
620
+ tabKey ?? cacheKey,
508
621
  async (sharedSignal) => {
509
622
  let fetched: CompleteDocument;
510
623
  let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
511
624
 
512
- const staleCanUseMarkdownPolicy =
513
- stale !== undefined &&
514
- stale.extractor !== "raw" &&
515
- !stale.surfaceView &&
516
- !stale.llmsTxtFallback &&
517
- !stale.representationFallback;
625
+ const staleNeedsMarkdownPolicy =
626
+ stale !== undefined && staleCacheNeedsMarkdownPolicy(stale);
518
627
 
519
628
  if (
520
629
  stale?.validators &&
521
- !staleCanUseMarkdownPolicy &&
630
+ !staleNeedsMarkdownPolicy &&
522
631
  !stale.llmsTxtFallback &&
523
632
  !stale.markdownAlternateFallback &&
524
- !stale.representationFallback
633
+ !stale.representationFallback &&
634
+ !bomVersion
525
635
  ) {
526
636
  const outcome = await revalidateCompleteDocument(
527
637
  sourceUrl,
528
638
  stale,
529
639
  sharedSignal,
530
- dependencies,
640
+ acquisitionDependencies,
531
641
  );
532
642
 
533
643
  fetched = outcome.document;
534
644
  acquisitionStatus = outcome.revalidated ? "revalidated" : "miss";
535
645
  } else {
536
- fetched = await fetchDocumentWithLlmsTxtSupport(sourceUrl, sharedSignal, dependencies);
646
+ fetched = await fetchDocumentWithLlmsTxtSupport(
647
+ sourceUrl,
648
+ sharedSignal,
649
+ acquisitionDependencies,
650
+ Boolean(bomVersion),
651
+ !bomVersion,
652
+ );
537
653
  }
538
654
 
539
655
  if (!fetched.extractionDiagnostics?.botWall) {
540
- fetchCache.set(cacheKey, fetched, Date.now() + CACHE_STALE_RETENTION_MS);
656
+ const storageKey = fetched.surfaceView?.fragmentSelected ? tabKey : cacheKey;
657
+
658
+ if (storageKey) {
659
+ fetchCache.set(storageKey, fetched, Date.now() + CACHE_STALE_RETENTION_MS);
660
+ }
541
661
  }
542
662
 
543
663
  return { document: fetched, cacheStatus: acquisitionStatus };
@@ -554,7 +674,7 @@ export async function executeWebFetch(
554
674
  const blocked = Boolean(document.extractionDiagnostics?.botWall);
555
675
 
556
676
  // Keep acquisition diagnostics, but never expose challenge prose, links, or continuation.
557
- if (blocked)
677
+ if (blocked) {
558
678
  document = {
559
679
  ...document,
560
680
  markdown: "",
@@ -562,6 +682,7 @@ export async function executeWebFetch(
562
682
  links: undefined,
563
683
  fragmentOffsets: undefined,
564
684
  };
685
+ }
565
686
  const canonicalMarkdown = document.markdown;
566
687
 
567
688
  const surface =
@@ -577,7 +698,10 @@ export async function executeWebFetch(
577
698
  };
578
699
  }
579
700
 
580
- const resolvedFragment = resolveFragmentOffset(document, params.url);
701
+ const fragmentSurface = surface && document.surfaceView?.fragmentSelected ? surface : undefined;
702
+ const resolvedFragment = fragmentSurface
703
+ ? { fragment: fragmentSurface.selected, offset: 0, endOffset: undefined }
704
+ : resolveFragmentOffset(document, params.url);
581
705
  const fragmentOffset = resolvedFragment.offset;
582
706
  const fragmentMatched = resolvedFragment.fragment !== undefined && fragmentOffset !== undefined;
583
707
 
@@ -612,7 +736,9 @@ export async function executeWebFetch(
612
736
  const startingOffset = explicitOffset ?? fragmentOffset ?? FETCH_DEFAULT_OFFSET;
613
737
 
614
738
  const useFragment =
615
- fragmentOffset !== undefined && (explicitOffset === undefined || params.query !== undefined);
739
+ !fragmentSurface &&
740
+ fragmentOffset !== undefined &&
741
+ (explicitOffset === undefined || params.query !== undefined);
616
742
 
617
743
  const hasFragmentRange = useFragment && resolvedFragment.endOffset !== undefined;
618
744
 
@@ -627,7 +753,7 @@ export async function executeWebFetch(
627
753
  : document;
628
754
 
629
755
  const focused =
630
- blocked || params.query === undefined
756
+ blocked || params.query === undefined || bomVersion
631
757
  ? undefined
632
758
  : focusMarkdown(fragmentDocument.markdown, params.query);
633
759
 
@@ -700,6 +826,12 @@ export async function executeWebFetch(
700
826
  "",
701
827
  ]
702
828
  : []),
829
+ ...(result.noscriptFallback
830
+ ? [
831
+ "[Showing the page's no-JavaScript fallback; script-rendered content is unavailable.]",
832
+ "",
833
+ ]
834
+ : []),
703
835
  ...(result.llmsTxtFallback
704
836
  ? [
705
837
  "[Showing the site index instead of the requested page. Follow a link for details.]",
@@ -724,7 +856,9 @@ export async function executeWebFetch(
724
856
  "",
725
857
  ]
726
858
  : []),
727
- ...(fragmentMatched ? ["[Starting at the requested URL fragment.]", ""] : []),
859
+ ...(fragmentMatched && !fragmentSurface
860
+ ? ["[Starting at the requested URL fragment.]", ""]
861
+ : []),
728
862
  ...(focused
729
863
  ? [
730
864
  focused.details.matchedSections > 0
@@ -790,6 +924,7 @@ export async function executeWebFetch(
790
924
  characterCount: 0,
791
925
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
792
926
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
927
+ noscriptFallback: Boolean(result.noscriptFallback),
793
928
  representationFallback: result.representationFallback,
794
929
  extraction: result.extractionDiagnostics,
795
930
  focus: focused?.details,
@@ -829,6 +964,7 @@ export async function executeWebFetch(
829
964
 
830
965
  // SAFETY: this DTO contains only bounded JSON data; serialization omits optional
831
966
  // undefined properties so the emitted value matches the declared output schema.
967
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- preserve output's JSON representation
832
968
  const structuredContent = JSON.parse(JSON.stringify(structured)) as NonNullable<
833
969
  AgentToolResult["structuredContent"]
834
970
  >;
@@ -853,6 +989,7 @@ export async function executeWebFetch(
853
989
  surface,
854
990
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
855
991
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
992
+ noscriptFallback: Boolean(result.noscriptFallback),
856
993
  representationFallback: result.representationFallback,
857
994
  llmsTxtUrl:
858
995
  result.llmsTxtIndexUrl === undefined
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  /** Maximum length in bytes of the server-provided random challenge data. */
3
- export const ANUBIS_MAX_RANDOM_DATA_BYTES = 4_096;
3
+ export const ANUBIS_MAX_RANDOM_DATA_BYTES = 4096;
4
4
  /** Maximum size in bytes of a server-provided WebAssembly challenge module. */
5
- export const ANUBIS_MAX_WASM_BYTES = 4 * 1_024 * 1_024;
5
+ export const ANUBIS_MAX_WASM_BYTES = 4 * 1024 * 1024;
6
6
  /** The host function Anubis baseline WebAssembly modules import. */
7
7
  const ANUBIS_WASM_IMPORT = { module: "anubis", name: "anubis_update_nonce" };
8
8
  /** Exports required from an Anubis baseline WebAssembly module. */
@@ -95,8 +95,8 @@ export function solveAnubisSha256Hex(randomData, difficulty, deadline) {
95
95
  if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 64)
96
96
  throw new Error("Anubis challenge requested an unsupported difficulty.");
97
97
  const prefix = "0".repeat(difficulty);
98
- for (let nonce = 0; nonce <= 0xffff_ffff; nonce += 1) {
99
- if ((nonce & 0xfff) === 0 && Date.now() > deadline)
98
+ for (let nonce = 0; nonce <= 0xff_ff_ff_ff; nonce += 1) {
99
+ if ((nonce & 0xf_ff) === 0 && Date.now() > deadline)
100
100
  throw new Error("Anubis proof of work exceeded the time budget.");
101
101
  const hash = createHash("sha256").update(randomData).update(String(nonce)).digest("hex");
102
102
  if (hash.startsWith(prefix))
@@ -122,7 +122,7 @@ export function solveAnubisSha256Hex(randomData, difficulty, deadline) {
122
122
  export function solveAnubisWasm(moduleBytes, randomData, difficulty, deadline) {
123
123
  if (moduleBytes.byteLength === 0 || moduleBytes.byteLength > ANUBIS_MAX_WASM_BYTES)
124
124
  throw new Error("Anubis challenge module exceeded the size limit.");
125
- if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 0xffff_ffff)
125
+ if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 0xff_ff_ff_ff)
126
126
  throw new Error("Anubis challenge requested an unsupported difficulty.");
127
127
  const data = decodeHex(randomData);
128
128
  if (!data || data.byteLength > ANUBIS_MAX_RANDOM_DATA_BYTES)
@@ -146,7 +146,7 @@ export function solveAnubisWasm(moduleBytes, randomData, difficulty, deadline) {
146
146
  setDataLength(data.byteLength);
147
147
  const nonce = work(difficulty, 0, 1);
148
148
  const hashSize = resultHashSize() >>> 0;
149
- if (hashSize < 1 || hashSize > 4_096)
149
+ if (hashSize < 1 || hashSize > 4096)
150
150
  throw new Error("Anubis challenge module returned an invalid hash size.");
151
151
  const hashBytes = readMemory(memory, resultHashPtr(), hashSize);
152
152
  if (Date.now() > deadline)
@@ -1,56 +1,44 @@
1
1
  import { createHash, scryptSync } from "node:crypto";
2
-
3
2
  /** Returns whether the first `difficulty` bits of a hash are zero. */
4
3
  export function hasLeadingZeroBits(hash, difficulty) {
5
4
  for (let bit = 0; bit < difficulty; bit += 1) {
6
5
  const byte = hash[Math.floor(bit / 8)];
7
-
8
6
  if (byte === undefined || (byte & (1 << (7 - (bit % 8)))) !== 0) return false;
9
7
  }
10
-
11
8
  return true;
12
9
  }
13
-
14
10
  /** Solves the bandwidth challenge using a bounded zero-filled buffer. */
15
11
  export function solveAwsWafBandwidth(difficulty) {
16
- const sizes = [1_024, 1_024, 10_240, 102_400, 1_048_576, 10_485_760];
17
-
18
- return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1_024).toString("base64");
12
+ const sizes = [1024, 1024, 10_240, 102_400, 1_048_576, 10_485_760];
13
+ return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1024).toString("base64");
19
14
  }
20
-
21
15
  /** Computes bounded proof-of-work inside a disposable worker. */
22
16
  export function solveAwsWafWork(work) {
23
- if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32)
17
+ if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32) {
24
18
  return undefined;
25
-
19
+ }
26
20
  if (work.type === "NetworkBandwidth") return solveAwsWafBandwidth(work.difficulty);
27
-
28
21
  if (work.type === "SHA256") {
29
22
  for (let nonce = 0; nonce < 2_000_000; nonce += 1) {
30
23
  const digest = createHash("sha256").update(`${work.input}${work.checksum}${nonce}`).digest();
31
-
32
24
  if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
33
25
  }
34
26
  }
35
-
36
27
  if (work.type === "HashcashScrypt") {
37
28
  const cost = work.memory > 0 ? work.memory : 128;
38
-
39
29
  // Reject large or invalid costs before invoking OpenSSL.
40
- if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0)
30
+ if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0) {
41
31
  return undefined;
42
-
32
+ }
43
33
  for (let nonce = 0; nonce < 100_000; nonce += 1) {
44
34
  const digest = scryptSync(`${work.input}${work.checksum}${nonce}`, work.checksum, 32, {
45
35
  N: cost,
46
36
  r: 8,
47
37
  p: 1,
48
- maxmem: 64 * 1_024 * 1_024,
38
+ maxmem: 64 * 1024 * 1024,
49
39
  });
50
-
51
40
  if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
52
41
  }
53
42
  }
54
-
55
43
  return undefined;
56
44
  }
@@ -1,9 +1,7 @@
1
1
  /* v8 ignore file -- exercised through worker integration tests. */
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
3
  import { solveAwsWafWork } from "./aws-waf-solver.js";
4
-
5
4
  const work = workerData;
6
-
7
5
  try {
8
6
  parentPort?.postMessage({ kind: "solved", solution: solveAwsWafWork(work) });
9
7
  } catch (error) {