@zeldrisho/pi-web-fetch 0.18.1 → 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.
@@ -160,8 +160,9 @@ function sanitizeBasePrefix(value: AnubisScriptValue | undefined): string | unde
160
160
 
161
161
  if (!value.startsWith("/") || value.startsWith("//")) return undefined;
162
162
 
163
- if (value.includes("\\") || value.includes("?") || value.includes("#") || value.includes("%"))
163
+ if (value.includes("\\") || value.includes("?") || value.includes("#") || value.includes("%")) {
164
164
  return undefined;
165
+ }
165
166
 
166
167
  if (hasControlCharacters(value)) return undefined;
167
168
 
@@ -224,8 +225,9 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
224
225
  const version = readJsonScript(document, "anubis_version");
225
226
  const challengePayload = readJsonScript(document, "anubis_challenge");
226
227
 
227
- if (!isString(version) || version.length === 0 || version.length > MAX_VERSION_CHARACTERS)
228
+ if (!isString(version) || version.length === 0 || version.length > MAX_VERSION_CHARACTERS) {
228
229
  return undefined;
230
+ }
229
231
 
230
232
  if (isCrossOriginPublicUrl(document, pageUrl)) return undefined;
231
233
 
@@ -260,8 +262,9 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
260
262
 
261
263
  if (hasControlCharacters(id)) return undefined;
262
264
 
263
- if (!isString(method) || method.length === 0 || method.length > MAX_CHALLENGE_ID_CHARACTERS)
265
+ if (!isString(method) || method.length === 0 || method.length > MAX_CHALLENGE_ID_CHARACTERS) {
264
266
  return undefined;
267
+ }
265
268
 
266
269
  if (hasControlCharacters(method)) return undefined;
267
270
 
@@ -269,7 +272,7 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
269
272
  !isNumber(difficulty) ||
270
273
  !Number.isInteger(difficulty) ||
271
274
  difficulty < 0 ||
272
- difficulty > 0xffff_ffff
275
+ difficulty > 0xff_ff_ff_ff
273
276
  ) {
274
277
  return undefined;
275
278
  }
@@ -287,8 +290,9 @@ export function parseAnubisChallenge(raw: string, pageUrl: URL): AnubisChallenge
287
290
 
288
291
  if (!isStringArray(extensions) || extensions.length > MAX_EXTENSIONS) return undefined;
289
292
 
290
- if (extensions.some((extension) => extension.length === 0 || extension.length > 64))
293
+ if (extensions.some((extension) => extension.length === 0 || extension.length > 64)) {
291
294
  return undefined;
295
+ }
292
296
 
293
297
  return { id, method, randomData, difficulty, version, basePrefix, extensions };
294
298
  }
@@ -367,8 +371,9 @@ function solveInWorker(request: AnubisWorkerRequest, signal: AbortSignal): Promi
367
371
 
368
372
  worker.on("error", (error) => finish(() => reject(error)));
369
373
  worker.on("exit", (code) => {
370
- if (code !== 0)
374
+ if (code !== 0) {
371
375
  finish(() => reject(new Error(`Anubis solve worker exited with code ${code}.`)));
376
+ }
372
377
  });
373
378
 
374
379
  if (signal.aborted) onAbort();
@@ -401,8 +406,9 @@ async function fetchWasmModule(
401
406
  const bytes = await readResponseBytes(response, ANUBIS_MAX_WASM_BYTES, signal);
402
407
  const decoded = decompressResponse(bytes, responseHeader(response, "content-encoding"));
403
408
 
404
- if (decoded.byteLength === 0 || decoded.byteLength > ANUBIS_MAX_WASM_BYTES)
409
+ if (decoded.byteLength === 0 || decoded.byteLength > ANUBIS_MAX_WASM_BYTES) {
405
410
  throw new Error("Anubis challenge module exceeded the size limit.");
411
+ }
406
412
 
407
413
  return decoded;
408
414
  }
@@ -442,8 +448,9 @@ function cssLoadUrls(raw: string, pageUrl: URL): URL[] {
442
448
  for (const match of matches) consider(match[1]);
443
449
  }
444
450
 
445
- for (const element of document.querySelectorAll("link[rel=stylesheet][href]"))
451
+ for (const element of document.querySelectorAll("link[rel=stylesheet][href]")) {
446
452
  consider(element.getAttribute("href"));
453
+ }
447
454
 
448
455
  return urls;
449
456
  }
@@ -486,11 +493,13 @@ export async function solveAnubisChallenge(context: AnubisSolveContext): Promise
486
493
  const { challenge, pageUrl, raw, dependencies, signal } = context;
487
494
  const started = Date.now();
488
495
 
489
- if (!hasSupportedExtensions(challenge))
496
+ if (!hasSupportedExtensions(challenge)) {
490
497
  throw new Error("web_fetch does not support the extensions required by this Anubis challenge.");
498
+ }
491
499
 
492
- if (challenge.extensions.includes("css-load"))
500
+ if (challenge.extensions.includes("css-load")) {
493
501
  await performCssLoad(raw, pageUrl, dependencies, signal);
502
+ }
494
503
 
495
504
  const deadline = Date.now() + WORKER_DEADLINE_MS;
496
505
  let params: AnubisPassParameters;
@@ -185,9 +185,7 @@ interface BuiltMetrics {
185
185
  }
186
186
 
187
187
  /** Returns whether a value is a plain JSON object. */
188
- // oxlint-disable-next-line anti-slop/no-unknown-parameters -- parses untrusted challenge JSON at the I/O boundary
189
188
  function isJsonObject(value: unknown): value is JsonObject {
190
- // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validates untrusted challenge JSON before use
191
189
  return typeof value === "object" && value !== null && !Array.isArray(value);
192
190
  }
193
191
 
@@ -206,7 +204,6 @@ function parseJsonObject(text: string): JsonObject | undefined {
206
204
  function stringField(value: JsonObject, key: string): string | undefined {
207
205
  const field = value[key];
208
206
 
209
- // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validates an untrusted JSON field
210
207
  return typeof field === "string" ? field : undefined;
211
208
  }
212
209
 
@@ -214,7 +211,6 @@ function stringField(value: JsonObject, key: string): string | undefined {
214
211
  function numberField(value: JsonObject, key: string): number | undefined {
215
212
  const field = value[key];
216
213
 
217
- // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validates an untrusted JSON field
218
214
  return typeof field === "number" && Number.isFinite(field) ? field : undefined;
219
215
  }
220
216
 
@@ -22,15 +22,16 @@ export function hasLeadingZeroBits(hash: Uint8Array, difficulty: number): boolea
22
22
 
23
23
  /** Solves the bandwidth challenge using a bounded zero-filled buffer. */
24
24
  export function solveAwsWafBandwidth(difficulty: number): string {
25
- const sizes = [1_024, 1_024, 10_240, 102_400, 1_048_576, 10_485_760];
25
+ const sizes = [1024, 1024, 10_240, 102_400, 1_048_576, 10_485_760];
26
26
 
27
- return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1_024).toString("base64");
27
+ return Buffer.alloc(sizes[Math.min(5, Math.max(0, difficulty))] ?? 1024).toString("base64");
28
28
  }
29
29
 
30
30
  /** Computes bounded proof-of-work inside a disposable worker. */
31
31
  export function solveAwsWafWork(work: AwsWafWork): string | undefined {
32
- if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32)
32
+ if (!Number.isInteger(work.difficulty) || work.difficulty < 1 || work.difficulty > 32) {
33
33
  return undefined;
34
+ }
34
35
 
35
36
  if (work.type === "NetworkBandwidth") return solveAwsWafBandwidth(work.difficulty);
36
37
 
@@ -46,15 +47,16 @@ export function solveAwsWafWork(work: AwsWafWork): string | undefined {
46
47
  const cost = work.memory > 0 ? work.memory : 128;
47
48
 
48
49
  // Reject large or invalid costs before invoking OpenSSL.
49
- if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0)
50
+ if (!Number.isInteger(cost) || cost < 2 || cost > 16_384 || (cost & (cost - 1)) !== 0) {
50
51
  return undefined;
52
+ }
51
53
 
52
54
  for (let nonce = 0; nonce < 100_000; nonce += 1) {
53
55
  const digest = scryptSync(`${work.input}${work.checksum}${nonce}`, work.checksum, 32, {
54
56
  N: cost,
55
57
  r: 8,
56
58
  p: 1,
57
- maxmem: 64 * 1_024 * 1_024,
59
+ maxmem: 64 * 1024 * 1024,
58
60
  });
59
61
 
60
62
  if (hasLeadingZeroBits(digest, work.difficulty)) return String(nonce);
@@ -8,16 +8,18 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
8
8
  pageUrl.username ||
9
9
  pageUrl.password ||
10
10
  pageUrl.port
11
- )
11
+ ) {
12
12
  return undefined;
13
+ }
13
14
  const { document } = parseHTML(raw);
14
15
  const forms = document.querySelectorAll("form");
15
16
 
16
17
  if (forms.length !== 1) return undefined;
17
18
  const form = forms[0];
18
19
 
19
- if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get")
20
+ if (!form.hasAttribute("hidden") || form.getAttribute("method")?.toLowerCase() !== "get") {
20
21
  return undefined;
22
+ }
21
23
  const action = form.getAttribute("action");
22
24
 
23
25
  if (!action) return undefined;
@@ -34,8 +36,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
34
36
  target.pathname !== pageUrl.pathname ||
35
37
  target.search ||
36
38
  target.hash
37
- )
39
+ ) {
38
40
  return undefined;
41
+ }
39
42
  const inputs = [...form.querySelectorAll("input")];
40
43
 
41
44
  if (inputs.length !== 4) return undefined;
@@ -44,8 +47,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
44
47
  for (const input of inputs) {
45
48
  const name = input.getAttribute("name");
46
49
 
47
- if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden")
50
+ if (!name || values.has(name) || input.getAttribute("type")?.toLowerCase() !== "hidden") {
48
51
  return undefined;
52
+ }
49
53
  values.set(name, input.getAttribute("value") ?? "");
50
54
  }
51
55
 
@@ -57,8 +61,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
57
61
  !token ||
58
62
  !/^[a-f0-9]{1,256}$/i.test(token) ||
59
63
  values.get("jsc_orig_r") !== ""
60
- )
64
+ ) {
61
65
  return undefined;
66
+ }
62
67
 
63
68
  for (const name of values.keys()) if (pageUrl.searchParams.has(name)) return undefined;
64
69
 
@@ -80,8 +85,9 @@ export function redditChallengeUrl(raw: string, pageUrl: URL): URL | undefined {
80
85
  !match ||
81
86
  !/namedItem\(["']solution["']\)\.value\s*=/.test(script) ||
82
87
  !/requestSubmit\(\)/.test(script)
83
- )
88
+ ) {
84
89
  return undefined;
90
+ }
85
91
  target.searchParams.set("solution", match[3] + match[3]);
86
92
  target.searchParams.set("js_challenge", "1");
87
93
  target.searchParams.set("jsc_token", token);
@@ -93,7 +93,7 @@ const IMPLIED_END_TAGS = new Map<string, ReadonlySet<string>>([
93
93
  ["rp", new Set(["rt", "rp"])],
94
94
  ["tbody", new Set(["thead", "tbody"])],
95
95
  ["tfoot", new Set(["thead", "tbody"])],
96
- ] satisfies Array<[string, ReadonlySet<string>]>);
96
+ ] satisfies [string, ReadonlySet<string>][]);
97
97
 
98
98
  /**
99
99
  * Elements that open foreign content, where self-closing syntax is honored.
@@ -125,8 +125,9 @@ function findRawTextEnd(html: string, name: string, from: number): number {
125
125
  while (candidate !== -1) {
126
126
  const boundary = html[candidate + prefix.length];
127
127
 
128
- if (boundary === undefined || boundary === ">" || boundary === "/" || /\s/u.test(boundary))
128
+ if (boundary === undefined || boundary === ">" || boundary === "/" || /\s/u.test(boundary)) {
129
129
  return candidate;
130
+ }
130
131
 
131
132
  candidate = html.indexOf(prefix, candidate + prefix.length);
132
133
  }
@@ -147,7 +148,7 @@ function findRawTextEnd(html: string, name: string, from: number): number {
147
148
  */
148
149
  export function exceedsConversionDepth(html: string): boolean {
149
150
  // Preserve code-unit positions when normalizing ASCII tag names.
150
- const lower = html.replace(/[A-Z]+/g, (match) => match.toLowerCase());
151
+ const lower = html.replaceAll(/[A-Z]+/g, (match) => match.toLowerCase());
151
152
  const stack: string[] = [];
152
153
  // htmlparser2 keeps this flag in parallel with its element stack. Integration points
153
154
  // push HTML mode even under SVG or MathML; this must happen before self-closing checks.
@@ -3,10 +3,12 @@ import type { ExtractedLinks, ExtractionDiagnostics } from "./evidence.ts";
3
3
 
4
4
  const CONTENT_LINE_BUDGET = Math.max(1, DEFAULT_MAX_LINES - 10);
5
5
 
6
- const CONTENT_BYTE_BUDGET = Math.max(1_024, DEFAULT_MAX_BYTES - 2_048);
6
+ const CONTENT_BYTE_BUDGET = Math.max(1024, DEFAULT_MAX_BYTES - 2048);
7
7
 
8
8
  const encoder = new TextEncoder();
9
9
 
10
+ export const MAX_CACHED_FRAGMENT_TABS = 128;
11
+
10
12
  /**
11
13
  * A complete fetched document with extracted content and metadata.
12
14
  *
@@ -19,10 +21,14 @@ export interface CompleteDocument {
19
21
  /** Character offsets for document fragments, derived from HTML anchors/headings. */
20
22
  fragmentOffsets?: Record<string, number>;
21
23
  markdown: string;
24
+ /** Known tab IDs on the source HTML. Omitted when the inventory is unavailable. */
25
+ fragmentTabs?: string[];
22
26
  /** A URL-selected surface derived from the complete extracted page. */
23
27
  surfaceView?: {
24
28
  selected: string;
25
29
  omitted: number;
30
+ /** The URL fragment itself selected this view; no anchor slicing is needed. */
31
+ fragmentSelected?: true;
26
32
  markdown: string;
27
33
  fragmentOffsets?: Record<string, number>;
28
34
  };
@@ -6,9 +6,9 @@ const MAX_LINKS = 16;
6
6
  const MAX_ANCHOR_CHARACTERS = 120;
7
7
 
8
8
  /** Raw and extracted sizes below which an HTML page counts as sparsely extracted. */
9
- const SPARSE_MIN_RAW_CHARACTERS = 4_000;
9
+ const SPARSE_MIN_RAW_CHARACTERS = 4000;
10
10
 
11
- const SPARSE_MAX_MARKDOWN_CHARACTERS = 1_024;
11
+ const SPARSE_MAX_MARKDOWN_CHARACTERS = 1024;
12
12
 
13
13
  const SPARSE_MAX_MARKDOWN_RATIO = 0.008;
14
14
 
@@ -160,7 +160,7 @@ export function hasExtractionWarning(diagnostics: ExtractionDiagnostics): boolea
160
160
  * @returns Normalized text, truncated to MAX_ANCHOR_CHARACTERS if needed
161
161
  */
162
162
  function normalizedAnchor(value: string): string {
163
- const text = value.replace(/\s+/g, " ").trim();
163
+ const text = value.replaceAll(/\s+/g, " ").trim();
164
164
 
165
165
  return text.length > MAX_ANCHOR_CHARACTERS
166
166
  ? `${text.slice(0, MAX_ANCHOR_CHARACTERS - 1)}…`
@@ -188,8 +188,9 @@ export function extractDocumentLinks(raw: string, pageUrl: URL): ExtractedLinks
188
188
  continue;
189
189
  }
190
190
 
191
- if (!["http:", "https:"].includes(target.protocol) || target.username || target.password)
191
+ if (!["http:", "https:"].includes(target.protocol) || target.username || target.password) {
192
192
  continue;
193
+ }
193
194
  target.hash = "";
194
195
  const anchorText = normalizedAnchor(element.textContent ?? "");
195
196
  const key = `${target.href}\0${anchorText}`;