@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/CHANGELOG.md +25 -1
- package/README.md +8 -8
- package/package.json +7 -10
- package/src/abort.ts +1 -1
- package/src/acquisition/admission.ts +1 -1
- package/src/acquisition/fetch-metadata.ts +9 -9
- package/src/acquisition/fetch.ts +45 -11
- package/src/acquisition/llms.ts +75 -42
- package/src/acquisition/reddit.ts +4 -2
- package/src/cache.ts +33 -20
- package/src/challenges/anubis-solver.ts +27 -15
- package/src/challenges/anubis.ts +19 -10
- package/src/challenges/aws-waf-resolver.ts +0 -4
- package/src/challenges/aws-waf-solver.ts +7 -5
- package/src/challenges/reddit.ts +12 -6
- package/src/document/complexity.ts +4 -3
- package/src/document/content.ts +11 -1
- package/src/document/evidence.ts +32 -5
- package/src/document/extract.ts +326 -62
- package/src/document/focus.ts +22 -9
- package/src/document/fragment-index.ts +4 -4
- package/src/document/fragments.ts +34 -18
- package/src/document/markdown-cleanup.ts +2 -2
- package/src/document/openapi.ts +23 -5
- package/src/document/source-format.ts +4 -3
- package/src/limits.ts +3 -3
- package/src/network/cookies.ts +2 -2
- package/src/network/network-policy.ts +5 -3
- package/src/network/network-redirects.ts +6 -4
- package/src/network/network-transport.ts +6 -4
- package/src/render.ts +1 -1
- package/src/service.ts +175 -38
- package/workers/anubis-solver.js +6 -6
- package/workers/aws-waf-solver.js +7 -19
- package/workers/aws-waf-worker.js +0 -2
package/src/acquisition/llms.ts
CHANGED
|
@@ -21,15 +21,19 @@ function restrictOrigin(
|
|
|
21
21
|
validateUrl: async (value) => {
|
|
22
22
|
const url = value instanceof URL ? value : new URL(value);
|
|
23
23
|
|
|
24
|
-
if (url.origin !== origin || url.username || url.password)
|
|
24
|
+
if (url.origin !== origin || url.username || url.password) {
|
|
25
25
|
throw new Error("Cross-origin fallback redirect refused.");
|
|
26
|
+
}
|
|
26
27
|
|
|
27
28
|
return validate(value);
|
|
28
29
|
},
|
|
29
30
|
};
|
|
30
31
|
}
|
|
31
32
|
|
|
32
|
-
const CACHE_TTL_MS = 24 * 60 * 60 *
|
|
33
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
34
|
+
|
|
35
|
+
/** Bounds parallel index probes while allowing substantially deeper paths than two levels. */
|
|
36
|
+
const MAX_LLMS_TXT_CANDIDATES = 16;
|
|
33
37
|
|
|
34
38
|
const LLMS_TXT_MIN_MARKDOWN_CHARACTERS = 200;
|
|
35
39
|
|
|
@@ -44,11 +48,10 @@ function safeUrl(value: string): URL | undefined {
|
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
/**
|
|
47
|
-
* Builds candidate `/llms.txt` URLs for a page: the site-root index plus
|
|
48
|
-
* directory index
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* the page itself is already a `llms.txt` path, so a fallback never retries itself.
|
|
51
|
+
* Builds candidate `/llms.txt` URLs for a page: the site-root index plus every ancestor
|
|
52
|
+
* directory index, mirroring sites that publish per-section indexes. Returns them ordered
|
|
53
|
+
* shallow → deep, and an empty list for non-HTTP(S) targets or when the page itself is
|
|
54
|
+
* already a `llms.txt` path, so a fallback never retries itself.
|
|
52
55
|
*/
|
|
53
56
|
function isGitHubLikeHost(hostname: string): boolean {
|
|
54
57
|
return (
|
|
@@ -79,9 +82,8 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
79
82
|
|
|
80
83
|
if (url.pathname === "/llms.txt" || url.pathname.endsWith("/llms.txt")) return [];
|
|
81
84
|
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
// segment as a directory itself, so `/r2/` still probes `/r2/llms.txt`.
|
|
85
|
+
// A trailing slash marks the final segment as a directory itself, so `/r2/`
|
|
86
|
+
// probes `/r2/llms.txt`.
|
|
85
87
|
const trimmedDirectory = url.pathname.endsWith("/")
|
|
86
88
|
? url.pathname
|
|
87
89
|
: url.pathname.replace(/\/[^/]*$/, "/");
|
|
@@ -89,11 +91,16 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
|
|
|
89
91
|
const directories = ["/"];
|
|
90
92
|
const parts = trimmedDirectory.split("/").filter(Boolean);
|
|
91
93
|
|
|
92
|
-
for (let depth = 1; depth <=
|
|
94
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
93
95
|
directories.push(`/${parts.slice(0, depth).join("/")}/`);
|
|
94
96
|
}
|
|
95
97
|
|
|
96
|
-
|
|
98
|
+
const selectedDirectories =
|
|
99
|
+
directories.length <= MAX_LLMS_TXT_CANDIDATES
|
|
100
|
+
? directories
|
|
101
|
+
: [directories[0], ...directories.slice(-(MAX_LLMS_TXT_CANDIDATES - 1))];
|
|
102
|
+
|
|
103
|
+
return selectedDirectories.map((pathname) => {
|
|
97
104
|
const candidate = new URL(url.origin);
|
|
98
105
|
candidate.pathname = `${pathname}llms.txt`;
|
|
99
106
|
|
|
@@ -115,8 +122,9 @@ export function documentationMarkdownUrl(value: string): URL | undefined {
|
|
|
115
122
|
(url.hostname === "nextjs.org" || url.hostname === "vercel.com") &&
|
|
116
123
|
(url.pathname === "/docs" || url.pathname.startsWith("/docs/"))
|
|
117
124
|
)
|
|
118
|
-
)
|
|
125
|
+
) {
|
|
119
126
|
return;
|
|
127
|
+
}
|
|
120
128
|
|
|
121
129
|
if (url.pathname.endsWith(".md")) return;
|
|
122
130
|
url.pathname = `${url.pathname.replace(/\/$/, "")}.md`;
|
|
@@ -126,6 +134,9 @@ export function documentationMarkdownUrl(value: string): URL | undefined {
|
|
|
126
134
|
}
|
|
127
135
|
|
|
128
136
|
function isLowQualityDocument(document: CompleteDocument): boolean {
|
|
137
|
+
// An authored fallback is readable content, so a site index would be a downgrade.
|
|
138
|
+
if (document.noscriptFallback && !document.extractionDiagnostics?.botWall) return false;
|
|
139
|
+
|
|
129
140
|
// Sparse extraction alone is not proof of an empty app shell: server-rendered pages
|
|
130
141
|
// may include useful content in streaming/framework markup that article extraction
|
|
131
142
|
// does not fully recognize. Keep that page rather than replacing it with a site index.
|
|
@@ -144,14 +155,6 @@ interface LlmsTxtProbe {
|
|
|
144
155
|
|
|
145
156
|
const MAX_LLMS_TXT_PROBE_ENTRIES = 512;
|
|
146
157
|
|
|
147
|
-
/**
|
|
148
|
-
* Deepest ancestor-directory `/llms.txt` probed, e.g. `/a/b/c` also probes
|
|
149
|
-
* `/a/b/llms.txt`. Locale-prefixed documentation sites publish their section index
|
|
150
|
-
* one level below the locale root, so two levels are needed to reach
|
|
151
|
-
* `/en/docs/llms.txt` from `/en/docs/catalog/...`.
|
|
152
|
-
*/
|
|
153
|
-
const MAX_LLMS_TXT_DIRECTORY_DEPTH = 2;
|
|
154
|
-
|
|
155
158
|
const llmsTxtProbes = new ExpiringLruCache<string, LlmsTxtProbe>(
|
|
156
159
|
MAX_LLMS_TXT_PROBE_ENTRIES,
|
|
157
160
|
8 * 1024 * 1024,
|
|
@@ -193,21 +196,29 @@ async function ensureLlmsTxtIndex(
|
|
|
193
196
|
signal: AbortSignal | undefined,
|
|
194
197
|
dependencies: FetchRemoteDependencies,
|
|
195
198
|
): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
+
// Candidates are ordered shallow → deep. Probe from the page upward in small batches:
|
|
200
|
+
// this preserves a preference for the deepest usable index without issuing every
|
|
201
|
+
// ancestor request when a nearby section index already exists.
|
|
202
|
+
const batchSize = 4;
|
|
199
203
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const document = documents[depth];
|
|
204
|
+
for (let end = candidates.length; end > 0; end -= batchSize) {
|
|
205
|
+
const start = Math.max(0, end - batchSize);
|
|
206
|
+
const batch = candidates.slice(start, end);
|
|
204
207
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
);
|
|
208
|
+
const documents = await Promise.all(
|
|
209
|
+
batch.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
|
|
210
|
+
);
|
|
209
211
|
|
|
210
|
-
|
|
212
|
+
for (let index = documents.length - 1; index >= 0; index -= 1) {
|
|
213
|
+
const document = documents[index];
|
|
214
|
+
|
|
215
|
+
if (document) {
|
|
216
|
+
const aliases = documents.flatMap((other, i) =>
|
|
217
|
+
i !== index && other && other.markdown === document.markdown ? [batch[i].href] : [],
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
return { url: batch[index].href, document, aliases };
|
|
221
|
+
}
|
|
211
222
|
}
|
|
212
223
|
}
|
|
213
224
|
|
|
@@ -300,6 +311,8 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
300
311
|
rawUrl: string,
|
|
301
312
|
signal: AbortSignal | undefined,
|
|
302
313
|
dependencies: FetchRemoteDependencies,
|
|
314
|
+
preferHtml = false,
|
|
315
|
+
allowMarkdownAlternates = true,
|
|
303
316
|
): Promise<CompleteDocument> {
|
|
304
317
|
try {
|
|
305
318
|
const url = new URL(rawUrl);
|
|
@@ -325,14 +338,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
325
338
|
if (
|
|
326
339
|
new URL(document.url).origin === "https://prod.packit.dev" &&
|
|
327
340
|
document.contentType === "application/json"
|
|
328
|
-
)
|
|
341
|
+
) {
|
|
329
342
|
return { ...document, representationFallback: "packit-api" };
|
|
343
|
+
}
|
|
330
344
|
} catch (error) {
|
|
331
345
|
if (signal?.aborted) throw error;
|
|
332
346
|
}
|
|
333
347
|
}
|
|
334
348
|
|
|
335
349
|
if (isGitHubLikeHost(url.hostname)) {
|
|
350
|
+
// oxlint-disable-next-line typescript/return-await -- fetch failures must not fall through and retry this URL
|
|
336
351
|
return fetchCompleteDocument(rawUrl, signal, dependencies);
|
|
337
352
|
}
|
|
338
353
|
} catch (error) {
|
|
@@ -345,7 +360,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
345
360
|
// A withheld page must not discard an index that is still usable, so the pair is
|
|
346
361
|
// settled instead of rejected together.
|
|
347
362
|
const [primarySettled, indexSettled] = await Promise.allSettled([
|
|
348
|
-
fetchCompleteDocument(rawUrl, signal, dependencies, true),
|
|
363
|
+
fetchCompleteDocument(rawUrl, signal, dependencies, true, true, preferHtml),
|
|
349
364
|
candidates.length > 0
|
|
350
365
|
? ensureLlmsTxtIndex(candidates, signal, dependencies)
|
|
351
366
|
: Promise.resolve(undefined),
|
|
@@ -357,8 +372,9 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
357
372
|
if (primarySettled.status === "rejected") {
|
|
358
373
|
// A bot-protection layer replaced the page with a challenge that carries no
|
|
359
374
|
// content; the discovered index is the only remaining pointer to that content.
|
|
360
|
-
if (indexSettled.value && primarySettled.reason instanceof ChallengeBlockedError)
|
|
375
|
+
if (indexSettled.value && primarySettled.reason instanceof ChallengeBlockedError) {
|
|
361
376
|
return { ...indexSettled.value.document, llmsTxtFallback: true };
|
|
377
|
+
}
|
|
362
378
|
|
|
363
379
|
throw primarySettled.reason;
|
|
364
380
|
}
|
|
@@ -377,8 +393,9 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
377
393
|
? await probeUsableRawText(describedBy, signal, dependencies)
|
|
378
394
|
: undefined;
|
|
379
395
|
|
|
380
|
-
if (described && describedBy && index?.url !== describedBy.href)
|
|
396
|
+
if (described && describedBy && index?.url !== describedBy.href) {
|
|
381
397
|
index = { url: describedBy.href, document: described };
|
|
398
|
+
}
|
|
382
399
|
}
|
|
383
400
|
|
|
384
401
|
if (
|
|
@@ -395,8 +412,13 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
395
412
|
false,
|
|
396
413
|
);
|
|
397
414
|
|
|
398
|
-
if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec)
|
|
399
|
-
return {
|
|
415
|
+
if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec) {
|
|
416
|
+
return {
|
|
417
|
+
...spec,
|
|
418
|
+
fragmentTabs: primary.fragmentTabs,
|
|
419
|
+
representationFallback: "swagger-spec",
|
|
420
|
+
};
|
|
421
|
+
}
|
|
400
422
|
} catch (error) {
|
|
401
423
|
if (signal?.aborted) throw error;
|
|
402
424
|
}
|
|
@@ -405,6 +427,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
405
427
|
// Prefer a page-specific Markdown representation even when HTML extraction succeeded.
|
|
406
428
|
// Restrict the entire redirect chain, and never substitute HTML or arbitrary text.
|
|
407
429
|
if (
|
|
430
|
+
allowMarkdownAlternates &&
|
|
408
431
|
!primary.surfaceView &&
|
|
409
432
|
primary.extractor !== "raw" &&
|
|
410
433
|
(!primary.markdownAlternateUrl || (!isLowQualityDocument(primary) && primary.markdown.trim()))
|
|
@@ -430,14 +453,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
430
453
|
/^(text\/markdown|text\/x-markdown)(?:;|$)/i.test(alternate.contentType) &&
|
|
431
454
|
alternate.markdown.trim().length >= LLMS_TXT_MIN_MARKDOWN_CHARACTERS &&
|
|
432
455
|
!alternate.shellSuspected
|
|
433
|
-
)
|
|
456
|
+
) {
|
|
434
457
|
return {
|
|
435
458
|
...alternate,
|
|
459
|
+
fragmentTabs: primary.fragmentTabs,
|
|
436
460
|
markdownAlternateFallback: true,
|
|
437
461
|
markdownAlternateReason: advertised ? "advertised" : "preferred",
|
|
438
462
|
llmsTxtIndexUrl: index?.url,
|
|
439
463
|
llmsTxtIndexAliases: index?.aliases,
|
|
440
464
|
};
|
|
465
|
+
}
|
|
441
466
|
} catch (error) {
|
|
442
467
|
if (signal?.aborted) throw error;
|
|
443
468
|
}
|
|
@@ -451,13 +476,17 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
451
476
|
: undefined;
|
|
452
477
|
|
|
453
478
|
const alternate =
|
|
454
|
-
|
|
479
|
+
allowMarkdownAlternates &&
|
|
480
|
+
!primary.surfaceView &&
|
|
481
|
+
markdownAlternate &&
|
|
482
|
+
isSafeToProbe(markdownAlternate, primary.url)
|
|
455
483
|
? await probeUsableRawText(markdownAlternate, signal, dependencies)
|
|
456
484
|
: undefined;
|
|
457
485
|
|
|
458
486
|
if (alternate && markdownAlternate) {
|
|
459
487
|
return {
|
|
460
488
|
...alternate,
|
|
489
|
+
fragmentTabs: primary.fragmentTabs,
|
|
461
490
|
markdownAlternateFallback: true,
|
|
462
491
|
markdownAlternateReason: "advertised",
|
|
463
492
|
};
|
|
@@ -473,8 +502,12 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
473
502
|
(!primary.links || (primary.links.internal.length === 0 && primary.links.external.length === 0))
|
|
474
503
|
) {
|
|
475
504
|
// Preserve diagnostics for empty challenge pages and JavaScript app shells.
|
|
476
|
-
if (
|
|
505
|
+
if (
|
|
506
|
+
primary.extractionDiagnostics?.botWall ||
|
|
507
|
+
primary.extractionDiagnostics?.javascriptRequired
|
|
508
|
+
) {
|
|
477
509
|
return primary;
|
|
510
|
+
}
|
|
478
511
|
|
|
479
512
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
480
513
|
}
|
|
@@ -12,8 +12,9 @@ export function redditFeedUrl(rawUrl: string): string | undefined {
|
|
|
12
12
|
url.username ||
|
|
13
13
|
url.password ||
|
|
14
14
|
url.port
|
|
15
|
-
)
|
|
15
|
+
) {
|
|
16
16
|
return undefined;
|
|
17
|
+
}
|
|
17
18
|
|
|
18
19
|
const match = /^\/r\/([a-z0-9_]+)\/comments\/([a-z0-9]+)(?:\/[^/]+)?\/?$/i.exec(url.pathname);
|
|
19
20
|
|
|
@@ -56,8 +57,9 @@ export function extractRedditFeed(raw: string, feedUrl: string): string | undefi
|
|
|
56
57
|
if (
|
|
57
58
|
entry === post ||
|
|
58
59
|
!/^t1_[a-z0-9]+$/i.test(entry.querySelector("id")?.textContent?.trim() ?? "")
|
|
59
|
-
)
|
|
60
|
+
) {
|
|
60
61
|
continue;
|
|
62
|
+
}
|
|
61
63
|
const comment = render(entry);
|
|
62
64
|
|
|
63
65
|
if (comment) comments.push(comment);
|
package/src/cache.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
chmodSync,
|
|
3
3
|
closeSync,
|
|
4
|
+
fchmodSync,
|
|
4
5
|
mkdirSync,
|
|
5
6
|
openSync,
|
|
6
7
|
readFileSync,
|
|
@@ -12,7 +13,7 @@ import {
|
|
|
12
13
|
writeFileSync,
|
|
13
14
|
} from "node:fs";
|
|
14
15
|
import { resolve, sep } from "node:path";
|
|
15
|
-
import { createHash } from "node:crypto";
|
|
16
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
16
17
|
|
|
17
18
|
interface ExpiringCacheEntry<V> {
|
|
18
19
|
expiresAt: number;
|
|
@@ -40,11 +41,8 @@ export function stableKeyHash(key: string): string {
|
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
/** Hash canonical JSON, sorting object keys recursively while preserving array order. */
|
|
43
|
-
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- JSON serialization defines the accepted values.
|
|
44
44
|
export function canonicalKey(value: unknown): string {
|
|
45
|
-
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- JSON replacer receives arbitrary JSON values.
|
|
46
45
|
const json = JSON.stringify(value, (_key, entry: unknown) => {
|
|
47
|
-
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- recursively sort JSON objects.
|
|
48
46
|
if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
|
|
49
47
|
return Object.fromEntries(
|
|
50
48
|
Object.entries(entry).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
|
|
@@ -76,6 +74,30 @@ export function resolveCachePath(directory: string, keyPath: string): string {
|
|
|
76
74
|
return full;
|
|
77
75
|
}
|
|
78
76
|
|
|
77
|
+
/** Publishes a cache file atomically using a temporary path in the same directory. */
|
|
78
|
+
export function writeCacheFile(path: string, temp: string, bytes: Uint8Array): void {
|
|
79
|
+
const descriptor = openSync(temp, "wx", 0o600);
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
try {
|
|
83
|
+
writeFileSync(descriptor, bytes);
|
|
84
|
+
fchmodSync(descriptor, 0o600);
|
|
85
|
+
} finally {
|
|
86
|
+
closeSync(descriptor);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
renameSync(temp, path);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
try {
|
|
92
|
+
unlinkSync(temp);
|
|
93
|
+
} catch {
|
|
94
|
+
// Best-effort cleanup must not hide the write or rename failure.
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
79
101
|
/**
|
|
80
102
|
* Encodes an expiration timestamp as an 8-byte big-endian buffer.
|
|
81
103
|
*
|
|
@@ -233,8 +255,9 @@ export class ExpiringLruCache<K, V> {
|
|
|
233
255
|
|
|
234
256
|
const size = this.sizeOf(value);
|
|
235
257
|
|
|
236
|
-
if (!Number.isFinite(size) || size < 0 || size > this.maxBytes)
|
|
258
|
+
if (!Number.isFinite(size) || size < 0 || size > this.maxBytes) {
|
|
237
259
|
throw new Error("oversized cache entry");
|
|
260
|
+
}
|
|
238
261
|
entry = { expiresAt, size, value };
|
|
239
262
|
} catch {
|
|
240
263
|
this.#removeFromDisk(key);
|
|
@@ -262,22 +285,12 @@ export class ExpiringLruCache<K, V> {
|
|
|
262
285
|
chmodSync(directory, 0o700);
|
|
263
286
|
const payload = this.persistence!.serialize(value);
|
|
264
287
|
|
|
265
|
-
if (payload.byteLength > this.maxBytes * 2 + 65_536)
|
|
288
|
+
if (payload.byteLength > this.maxBytes * 2 + 65_536) {
|
|
266
289
|
throw new Error("oversized cache payload");
|
|
267
|
-
const path = resolveCachePath(directory, this.persistence!.keyToPath(key));
|
|
268
|
-
const temp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
269
|
-
|
|
270
|
-
try {
|
|
271
|
-
writeFileSync(temp, Buffer.concat([encodeExpiresAt(expiresAt), payload]), { mode: 0o600 });
|
|
272
|
-
chmodSync(temp, 0o600);
|
|
273
|
-
renameSync(temp, path);
|
|
274
|
-
} finally {
|
|
275
|
-
try {
|
|
276
|
-
unlinkSync(temp);
|
|
277
|
-
} catch {
|
|
278
|
-
// The rename may already have removed the temporary path.
|
|
279
|
-
}
|
|
280
290
|
}
|
|
291
|
+
const path = resolveCachePath(directory, this.persistence!.keyToPath(key));
|
|
292
|
+
const temp = `${path}.${randomUUID()}.tmp`;
|
|
293
|
+
writeCacheFile(path, temp, Buffer.concat([encodeExpiresAt(expiresAt), payload]));
|
|
281
294
|
} catch {
|
|
282
295
|
// Best-effort persistence: a failed disk write never fails the caller.
|
|
283
296
|
}
|
|
@@ -296,7 +309,7 @@ export class ExpiringLruCache<K, V> {
|
|
|
296
309
|
|
|
297
310
|
try {
|
|
298
311
|
const files = readdirSync(persistence.directory);
|
|
299
|
-
const candidates:
|
|
312
|
+
const candidates: { path: string; size: number; mtime: number }[] = [];
|
|
300
313
|
|
|
301
314
|
for (const file of files) {
|
|
302
315
|
const path = resolveCachePath(persistence.directory, file);
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
|
|
3
3
|
/** Maximum length in bytes of the server-provided random challenge data. */
|
|
4
|
-
export const ANUBIS_MAX_RANDOM_DATA_BYTES =
|
|
4
|
+
export const ANUBIS_MAX_RANDOM_DATA_BYTES = 4096;
|
|
5
5
|
|
|
6
6
|
/** Maximum size in bytes of a server-provided WebAssembly challenge module. */
|
|
7
|
-
export const ANUBIS_MAX_WASM_BYTES = 4 *
|
|
7
|
+
export const ANUBIS_MAX_WASM_BYTES = 4 * 1024 * 1024;
|
|
8
8
|
|
|
9
9
|
/** A solved Anubis proof of work, using the nonce and hash the server expects. */
|
|
10
10
|
export interface AnubisSolution {
|
|
@@ -42,8 +42,9 @@ const ANUBIS_WASM_EXPORTS = [
|
|
|
42
42
|
|
|
43
43
|
/** Decodes a lowercase or uppercase hexadecimal string, rejecting odd or non-hex input. */
|
|
44
44
|
function decodeHex(value: string): Uint8Array | undefined {
|
|
45
|
-
if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value))
|
|
45
|
+
if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value)) {
|
|
46
46
|
return undefined;
|
|
47
|
+
}
|
|
47
48
|
|
|
48
49
|
const bytes = new Uint8Array(value.length / 2);
|
|
49
50
|
|
|
@@ -58,8 +59,9 @@ function decodeHex(value: string): Uint8Array | undefined {
|
|
|
58
59
|
function readMemory(memory: WebAssembly.Memory, pointer: number, size: number): Uint8Array {
|
|
59
60
|
const offset = pointer >>> 0;
|
|
60
61
|
|
|
61
|
-
if (size < 0 || offset + size > memory.buffer.byteLength)
|
|
62
|
+
if (size < 0 || offset + size > memory.buffer.byteLength) {
|
|
62
63
|
throw new Error("Anubis challenge module returned an out-of-bounds pointer.");
|
|
64
|
+
}
|
|
63
65
|
|
|
64
66
|
return new Uint8Array(memory.buffer, offset, size).slice();
|
|
65
67
|
}
|
|
@@ -68,8 +70,9 @@ function readMemory(memory: WebAssembly.Memory, pointer: number, size: number):
|
|
|
68
70
|
function writeMemory(memory: WebAssembly.Memory, pointer: number, bytes: Uint8Array): void {
|
|
69
71
|
const offset = pointer >>> 0;
|
|
70
72
|
|
|
71
|
-
if (offset + bytes.byteLength > memory.buffer.byteLength)
|
|
73
|
+
if (offset + bytes.byteLength > memory.buffer.byteLength) {
|
|
72
74
|
throw new Error("Anubis challenge module returned an out-of-bounds pointer.");
|
|
75
|
+
}
|
|
73
76
|
|
|
74
77
|
new Uint8Array(memory.buffer, offset, bytes.byteLength).set(bytes);
|
|
75
78
|
}
|
|
@@ -152,14 +155,16 @@ export function solveAnubisSha256Hex(
|
|
|
152
155
|
difficulty: number,
|
|
153
156
|
deadline: number,
|
|
154
157
|
): AnubisSolution {
|
|
155
|
-
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 64)
|
|
158
|
+
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 64) {
|
|
156
159
|
throw new Error("Anubis challenge requested an unsupported difficulty.");
|
|
160
|
+
}
|
|
157
161
|
|
|
158
162
|
const prefix = "0".repeat(difficulty);
|
|
159
163
|
|
|
160
|
-
for (let nonce = 0; nonce <=
|
|
161
|
-
if ((nonce &
|
|
164
|
+
for (let nonce = 0; nonce <= 0xff_ff_ff_ff; nonce += 1) {
|
|
165
|
+
if ((nonce & 0xf_ff) === 0 && Date.now() > deadline) {
|
|
162
166
|
throw new Error("Anubis proof of work exceeded the time budget.");
|
|
167
|
+
}
|
|
163
168
|
|
|
164
169
|
const hash = createHash("sha256").update(randomData).update(String(nonce)).digest("hex");
|
|
165
170
|
|
|
@@ -190,16 +195,19 @@ export function solveAnubisWasm(
|
|
|
190
195
|
difficulty: number,
|
|
191
196
|
deadline: number,
|
|
192
197
|
): AnubisSolution {
|
|
193
|
-
if (moduleBytes.byteLength === 0 || moduleBytes.byteLength > ANUBIS_MAX_WASM_BYTES)
|
|
198
|
+
if (moduleBytes.byteLength === 0 || moduleBytes.byteLength > ANUBIS_MAX_WASM_BYTES) {
|
|
194
199
|
throw new Error("Anubis challenge module exceeded the size limit.");
|
|
200
|
+
}
|
|
195
201
|
|
|
196
|
-
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty >
|
|
202
|
+
if (!Number.isInteger(difficulty) || difficulty < 0 || difficulty > 0xff_ff_ff_ff) {
|
|
197
203
|
throw new Error("Anubis challenge requested an unsupported difficulty.");
|
|
204
|
+
}
|
|
198
205
|
|
|
199
206
|
const data = decodeHex(randomData);
|
|
200
207
|
|
|
201
|
-
if (!data || data.byteLength > ANUBIS_MAX_RANDOM_DATA_BYTES)
|
|
208
|
+
if (!data || data.byteLength > ANUBIS_MAX_RANDOM_DATA_BYTES) {
|
|
202
209
|
throw new Error("Anubis challenge supplied unsupported random data.");
|
|
210
|
+
}
|
|
203
211
|
|
|
204
212
|
if (Date.now() > deadline) throw new Error("Anubis proof of work exceeded the time budget.");
|
|
205
213
|
|
|
@@ -212,8 +220,9 @@ export function solveAnubisWasm(
|
|
|
212
220
|
|
|
213
221
|
const memory = instance.exports.memory;
|
|
214
222
|
|
|
215
|
-
if (!(memory instanceof WebAssembly.Memory))
|
|
223
|
+
if (!(memory instanceof WebAssembly.Memory)) {
|
|
216
224
|
throw new Error("Anubis challenge module is missing memory.");
|
|
225
|
+
}
|
|
217
226
|
|
|
218
227
|
const dataPtr = requireFunction(instance.exports, "data_ptr");
|
|
219
228
|
const setDataLength = requireFunction(instance.exports, "set_data_length");
|
|
@@ -226,15 +235,17 @@ export function solveAnubisWasm(
|
|
|
226
235
|
const nonce = work(difficulty, 0, 1);
|
|
227
236
|
const hashSize = resultHashSize() >>> 0;
|
|
228
237
|
|
|
229
|
-
if (hashSize < 1 || hashSize >
|
|
238
|
+
if (hashSize < 1 || hashSize > 4096) {
|
|
230
239
|
throw new Error("Anubis challenge module returned an invalid hash size.");
|
|
240
|
+
}
|
|
231
241
|
|
|
232
242
|
const hashBytes = readMemory(memory, resultHashPtr(), hashSize);
|
|
233
243
|
|
|
234
244
|
if (Date.now() > deadline) throw new Error("Anubis proof of work exceeded the time budget.");
|
|
235
245
|
|
|
236
|
-
if (difficulty > 0 && leadingZeroBits(hashBytes) < difficulty)
|
|
246
|
+
if (difficulty > 0 && leadingZeroBits(hashBytes) < difficulty) {
|
|
237
247
|
throw new Error("Anubis proof of work produced an invalid solution.");
|
|
248
|
+
}
|
|
238
249
|
|
|
239
250
|
const hash = Array.from(hashBytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
240
251
|
|
|
@@ -243,8 +254,9 @@ export function solveAnubisWasm(
|
|
|
243
254
|
|
|
244
255
|
/** Dispatches one worker solve request to the matching pure solver. */
|
|
245
256
|
export function solveAnubisRequest(request: AnubisWorkerRequest): AnubisSolution {
|
|
246
|
-
if (request.kind === "sha256")
|
|
257
|
+
if (request.kind === "sha256") {
|
|
247
258
|
return solveAnubisSha256Hex(request.randomData, request.difficulty, request.deadline);
|
|
259
|
+
}
|
|
248
260
|
|
|
249
261
|
return solveAnubisWasm(
|
|
250
262
|
request.moduleBytes,
|
package/src/challenges/anubis.ts
CHANGED
|
@@ -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 >
|
|
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
|
|