@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.
- package/CHANGELOG.md +15 -1
- package/README.md +7 -7
- 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 +18 -9
- package/src/acquisition/llms.ts +28 -10
- 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 +7 -1
- package/src/document/evidence.ts +5 -4
- package/src/document/extract.ts +221 -63
- 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 +2 -1
- 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 +5 -3
- package/src/network/network-transport.ts +6 -4
- package/src/render.ts +1 -1
- package/src/service.ts +108 -40
- package/workers/anubis-solver.js +6 -6
- package/workers/aws-waf-solver.js +7 -19
- package/workers/aws-waf-worker.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.18.2] - 2026-12-01
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Fetch only the selected panel for fragment-linked tabs, such as AppSales charts, without skipping the first entry or spilling into other panels. Ordinary anchors still reuse the cached full page.
|
|
15
|
+
- Ignore explicitly hidden HTML, including hidden page bodies, and avoid returning sparse interface text as page content when a scripted main region is empty. Refetch older cached HTML so it does not retain the discarded text.
|
|
16
|
+
- Update Defuddle to 0.19.13 to better preserve table captions, figure links, and Markdown list formatting.
|
|
17
|
+
|
|
18
|
+
### Security
|
|
19
|
+
|
|
20
|
+
- Create private cache temporary files exclusively so a write cannot overwrite or remove an existing temporary file.
|
|
21
|
+
- Pick up Defuddle's fix for unsafe serialization of MathML title elements.
|
|
22
|
+
|
|
10
23
|
## [0.18.1] - 2026-11-23
|
|
11
24
|
|
|
12
25
|
### Fixed
|
|
@@ -392,7 +405,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
392
405
|
|
|
393
406
|
- Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
|
|
394
407
|
|
|
395
|
-
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.
|
|
408
|
+
[Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.2...HEAD
|
|
409
|
+
[0.18.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.1...pi-web-fetch-v0.18.2
|
|
396
410
|
[0.18.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...pi-web-fetch-v0.18.1
|
|
397
411
|
[0.18.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...pi-web-fetch-v0.18.0
|
|
398
412
|
[0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
|
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-web-fetch
|
|
2
2
|
|
|
3
3
|
Fetch bounded content from public HTTP(S) pages and source files with Pi. No API key is required.
|
|
4
4
|
|
|
@@ -17,13 +17,13 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
|
|
|
17
17
|
|
|
18
18
|
The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markdown, plain text, JSON, and XML. HTML is converted to Markdown; images are omitted. Minified JavaScript, JSON, and YAML are returned as indented code blocks so long single-line payloads stay readable. URLs with credentials, local or private network targets, unsafe redirects, downloads over 5 MiB, and unsupported content types are rejected.
|
|
19
19
|
|
|
20
|
-
| Parameter | Description
|
|
21
|
-
| --------- |
|
|
22
|
-
| `url` | Required page URL.
|
|
23
|
-
| `query` | Optional; selects matching sections from a long page. Sections remain in source order.
|
|
24
|
-
| `offset` | Optional character offset for continuing through extracted content.
|
|
20
|
+
| Parameter | Description |
|
|
21
|
+
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `url` | Required page URL. A fragment can select a supported tab or start output at a matching heading or anchor. |
|
|
23
|
+
| `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
|
|
24
|
+
| `offset` | Optional character offset for continuing through extracted content. Offsets apply to the selected tab or focused view, if any. Otherwise an offset takes precedence over the fragment. |
|
|
25
25
|
|
|
26
|
-
When a
|
|
26
|
+
When a page exposes a supported tab selector, a query parameter such as `?tab=cli` can show the selected tab and shared content. A fragment such as `#charts-week` can select just its panel when the page links to it from an unambiguous tab group. The output notes that other tabs were omitted. Remove the tab parameter or fragment to see the full extracted page. Continuation offsets apply to the selected view.
|
|
27
27
|
|
|
28
28
|
Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` with the same URL and query to continue. Queries use approximate word matching and relevance selection; dotted identifiers in longer queries, and standalone dotted or hyphenated identifiers and flags, are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
|
|
29
29
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeldrisho/pi-web-fetch",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.2",
|
|
4
4
|
"description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
@@ -32,17 +32,17 @@
|
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"acorn": "^8.19.0",
|
|
34
34
|
"acorn-walk": "^8.3.5",
|
|
35
|
-
"defuddle": "^0.19.
|
|
35
|
+
"defuddle": "^0.19.13",
|
|
36
36
|
"linkedom": "^0.18.15",
|
|
37
37
|
"yaml": "^2.9.1"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
41
|
-
"@earendil-works/pi-tui": "^1.
|
|
42
|
-
"typebox": "^1.4.
|
|
40
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
41
|
+
"@earendil-works/pi-tui": "^1.6.0",
|
|
42
|
+
"typebox": "^1.4.7",
|
|
43
43
|
"typescript": "^7.0.2",
|
|
44
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@
|
|
45
|
-
"vite-plus": "1.
|
|
44
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
|
|
45
|
+
"vite-plus": "1.7.0"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"@earendil-works/pi-coding-agent": ">=0.99.0",
|
|
@@ -53,8 +53,5 @@
|
|
|
53
53
|
"extensions": [
|
|
54
54
|
"./src/index.ts"
|
|
55
55
|
]
|
|
56
|
-
},
|
|
57
|
-
"scripts": {
|
|
58
|
-
"test": "vp test"
|
|
59
56
|
}
|
|
60
57
|
}
|
package/src/abort.ts
CHANGED
|
@@ -24,7 +24,7 @@ export function awaitWithAbort<T>(operation: Promise<T>, signal: AbortSignal): P
|
|
|
24
24
|
|
|
25
25
|
operation.then(
|
|
26
26
|
(value) => finish(() => resolve(value)),
|
|
27
|
-
(error) => finish(() => reject(error)),
|
|
27
|
+
(error: unknown) => finish(() => reject(error)),
|
|
28
28
|
);
|
|
29
29
|
|
|
30
30
|
if (signal.aborted) abort();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Limits complete acquisitions, including slow response bodies and extraction. */
|
|
2
2
|
export class AcquisitionAdmission {
|
|
3
3
|
#active = 0;
|
|
4
|
-
readonly #waiting:
|
|
4
|
+
readonly #waiting: (() => void)[] = [];
|
|
5
5
|
|
|
6
6
|
readonly maxActive: number;
|
|
7
7
|
readonly maxWaiting: number;
|
|
@@ -38,9 +38,9 @@ export function normalizeGitHubRawUrl(rawUrl: string): string {
|
|
|
38
38
|
const segments = url.pathname.split("/").filter(Boolean);
|
|
39
39
|
|
|
40
40
|
if (segments.length >= 4 && segments[2] === "tree") {
|
|
41
|
-
const lastSegment = segments
|
|
41
|
+
const lastSegment = segments.at(-1);
|
|
42
42
|
|
|
43
|
-
if (lastSegment
|
|
43
|
+
if (lastSegment?.includes(".")) {
|
|
44
44
|
// Reconstruct path: /owner/repo/ref/path (remove "tree" segment)
|
|
45
45
|
const newPath = `/${segments[0]}/${segments[1]}/${segments.slice(3).join("/")}`;
|
|
46
46
|
|
|
@@ -97,15 +97,15 @@ export function markdownFragmentOffsets(markdown: string) {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
const base = withoutHtml
|
|
100
|
-
.
|
|
101
|
-
.
|
|
102
|
-
.
|
|
100
|
+
.replaceAll(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
101
|
+
.replaceAll(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
102
|
+
.replaceAll(/[`*_~]/g, "")
|
|
103
103
|
.normalize("NFKD")
|
|
104
|
-
.
|
|
104
|
+
.replaceAll(/[\u0300-\u036f]/g, "")
|
|
105
105
|
.toLowerCase()
|
|
106
|
-
.
|
|
106
|
+
.replaceAll(/[^\p{Letter}\p{Number} _-]/gu, "")
|
|
107
107
|
.trim()
|
|
108
|
-
.
|
|
108
|
+
.replaceAll(/[ _]+/g, "-");
|
|
109
109
|
|
|
110
110
|
if (!base) return;
|
|
111
111
|
|
|
@@ -212,7 +212,7 @@ export function parseLinkHeaderForAgentHints(
|
|
|
212
212
|
const value = parameter
|
|
213
213
|
.slice(equals + 1)
|
|
214
214
|
.trim()
|
|
215
|
-
.
|
|
215
|
+
.replaceAll(/^"|"$/g, "");
|
|
216
216
|
|
|
217
217
|
parameters.set(key, value);
|
|
218
218
|
}
|
package/src/acquisition/fetch.ts
CHANGED
|
@@ -64,8 +64,9 @@ export function npmRegistryFallbackUrl(rawUrl: string): string | undefined {
|
|
|
64
64
|
|
|
65
65
|
const segments = url.pathname.split("/").filter(Boolean);
|
|
66
66
|
|
|
67
|
-
if (segments[0] !== "package" || (segments.length !== 2 && segments.length !== 3))
|
|
67
|
+
if (segments[0] !== "package" || (segments.length !== 2 && segments.length !== 3)) {
|
|
68
68
|
return undefined;
|
|
69
|
+
}
|
|
69
70
|
|
|
70
71
|
const name = segments.length === 3 ? `${segments[1]}/${segments[2]}` : segments[1];
|
|
71
72
|
|
|
@@ -144,13 +145,13 @@ function normalizeContentType(header: string): string | undefined {
|
|
|
144
145
|
}
|
|
145
146
|
|
|
146
147
|
/** Content types other than `text/*` that web_fetch extracts. */
|
|
147
|
-
const ALLOWED_CONTENT_TYPES = [
|
|
148
|
+
const ALLOWED_CONTENT_TYPES = new Set([
|
|
148
149
|
"application/json",
|
|
149
150
|
"application/markdown",
|
|
150
151
|
"application/x-markdown",
|
|
151
152
|
"application/xml",
|
|
152
153
|
"application/xhtml+xml",
|
|
153
|
-
];
|
|
154
|
+
]);
|
|
154
155
|
|
|
155
156
|
/** A response body decoded once so challenge detection and extraction share it. */
|
|
156
157
|
interface DecodedBody {
|
|
@@ -183,7 +184,7 @@ const TEXT_DOCUMENT_PATH_PATTERN = /\.(?:md|markdown|mdx|txt)$/i;
|
|
|
183
184
|
function isAllowedContentType(value: string | undefined, pathname: string): value is string {
|
|
184
185
|
if (value === undefined) return false;
|
|
185
186
|
|
|
186
|
-
if (value.startsWith("text/") || ALLOWED_CONTENT_TYPES.
|
|
187
|
+
if (value.startsWith("text/") || ALLOWED_CONTENT_TYPES.has(value)) return true;
|
|
187
188
|
|
|
188
189
|
return value === "application/octet-stream" && TEXT_DOCUMENT_PATH_PATTERN.test(pathname);
|
|
189
190
|
}
|
|
@@ -281,8 +282,9 @@ async function documentFromDecoded(
|
|
|
281
282
|
): Promise<CompleteDocument> {
|
|
282
283
|
const { raw, contentType, contentTypeHeader } = body;
|
|
283
284
|
|
|
284
|
-
if (!raw.trim() && !allowEmptyContent)
|
|
285
|
+
if (!raw.trim() && !allowEmptyContent) {
|
|
285
286
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
287
|
+
}
|
|
286
288
|
|
|
287
289
|
const linkHints = parseLinkHeaderForAgentHints(
|
|
288
290
|
responseHeader(response, "link") ?? "",
|
|
@@ -292,6 +294,7 @@ async function documentFromDecoded(
|
|
|
292
294
|
let markdown: string;
|
|
293
295
|
let title: string | undefined;
|
|
294
296
|
let fragmentOffsets: Record<string, number> | undefined;
|
|
297
|
+
let fragmentTabs: string[] | undefined;
|
|
295
298
|
let surfaceView: CompleteDocument["surfaceView"];
|
|
296
299
|
let extractor: CompleteDocument["extractor"] = "raw";
|
|
297
300
|
let describedBy: string | undefined = linkHints.describedBy;
|
|
@@ -306,6 +309,7 @@ async function documentFromDecoded(
|
|
|
306
309
|
markdown = extracted.markdown;
|
|
307
310
|
title = extracted.title;
|
|
308
311
|
fragmentOffsets = extracted.fragmentOffsets;
|
|
312
|
+
fragmentTabs = extracted.fragmentTabs;
|
|
309
313
|
surfaceView = extracted.surfaceView;
|
|
310
314
|
extractor = extracted.extractor;
|
|
311
315
|
githubReadme = extracted.githubReadme === true;
|
|
@@ -372,8 +376,9 @@ async function documentFromDecoded(
|
|
|
372
376
|
!candidate.username &&
|
|
373
377
|
!candidate.password &&
|
|
374
378
|
!candidate.hash
|
|
375
|
-
)
|
|
379
|
+
) {
|
|
376
380
|
swaggerSpecUrl = candidate.href;
|
|
381
|
+
}
|
|
377
382
|
} catch {
|
|
378
383
|
// Ignore malformed advertisements.
|
|
379
384
|
}
|
|
@@ -419,6 +424,7 @@ async function documentFromDecoded(
|
|
|
419
424
|
contentType,
|
|
420
425
|
markdown,
|
|
421
426
|
fragmentOffsets,
|
|
427
|
+
fragmentTabs,
|
|
422
428
|
surfaceView,
|
|
423
429
|
title,
|
|
424
430
|
extractor,
|
|
@@ -542,8 +548,9 @@ async function documentFromAcquisition(
|
|
|
542
548
|
signal,
|
|
543
549
|
});
|
|
544
550
|
} catch (error) {
|
|
545
|
-
if (signal.aborted || (error instanceof Error && error.name === "AbortError"))
|
|
551
|
+
if (signal.aborted || (error instanceof Error && error.name === "AbortError")) {
|
|
546
552
|
throw error;
|
|
553
|
+
}
|
|
547
554
|
|
|
548
555
|
return documentFromDecoded(
|
|
549
556
|
target,
|
|
@@ -700,8 +707,9 @@ async function fetchDocument(
|
|
|
700
707
|
|
|
701
708
|
if (cached?.validators?.etag) conditionalHeaders["If-None-Match"] = cached.validators.etag;
|
|
702
709
|
|
|
703
|
-
if (cached?.validators?.lastModified)
|
|
710
|
+
if (cached?.validators?.lastModified) {
|
|
704
711
|
conditionalHeaders["If-Modified-Since"] = cached.validators.lastModified;
|
|
712
|
+
}
|
|
705
713
|
|
|
706
714
|
// Cookies live only for this acquisition; challenge handshakes never persist or
|
|
707
715
|
// cross into another fetch.
|
|
@@ -885,7 +893,7 @@ async function fetchDocument(
|
|
|
885
893
|
|
|
886
894
|
const markdown = extractRedditFeed(body.raw, feedUrl);
|
|
887
895
|
|
|
888
|
-
if (markdown)
|
|
896
|
+
if (markdown) {
|
|
889
897
|
return {
|
|
890
898
|
document: {
|
|
891
899
|
url: document.url,
|
|
@@ -897,6 +905,7 @@ async function fetchDocument(
|
|
|
897
905
|
},
|
|
898
906
|
revalidated: false,
|
|
899
907
|
};
|
|
908
|
+
}
|
|
900
909
|
} else feed.response.destroy();
|
|
901
910
|
} catch (error) {
|
|
902
911
|
if (controller.signal.aborted) throw error;
|
package/src/acquisition/llms.ts
CHANGED
|
@@ -21,15 +21,16 @@ 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;
|
|
33
34
|
|
|
34
35
|
/** Bounds parallel index probes while allowing substantially deeper paths than two levels. */
|
|
35
36
|
const MAX_LLMS_TXT_CANDIDATES = 16;
|
|
@@ -121,8 +122,9 @@ export function documentationMarkdownUrl(value: string): URL | undefined {
|
|
|
121
122
|
(url.hostname === "nextjs.org" || url.hostname === "vercel.com") &&
|
|
122
123
|
(url.pathname === "/docs" || url.pathname.startsWith("/docs/"))
|
|
123
124
|
)
|
|
124
|
-
)
|
|
125
|
+
) {
|
|
125
126
|
return;
|
|
127
|
+
}
|
|
126
128
|
|
|
127
129
|
if (url.pathname.endsWith(".md")) return;
|
|
128
130
|
url.pathname = `${url.pathname.replace(/\/$/, "")}.md`;
|
|
@@ -336,14 +338,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
336
338
|
if (
|
|
337
339
|
new URL(document.url).origin === "https://prod.packit.dev" &&
|
|
338
340
|
document.contentType === "application/json"
|
|
339
|
-
)
|
|
341
|
+
) {
|
|
340
342
|
return { ...document, representationFallback: "packit-api" };
|
|
343
|
+
}
|
|
341
344
|
} catch (error) {
|
|
342
345
|
if (signal?.aborted) throw error;
|
|
343
346
|
}
|
|
344
347
|
}
|
|
345
348
|
|
|
346
349
|
if (isGitHubLikeHost(url.hostname)) {
|
|
350
|
+
// oxlint-disable-next-line typescript/return-await -- fetch failures must not fall through and retry this URL
|
|
347
351
|
return fetchCompleteDocument(rawUrl, signal, dependencies);
|
|
348
352
|
}
|
|
349
353
|
} catch (error) {
|
|
@@ -368,8 +372,9 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
368
372
|
if (primarySettled.status === "rejected") {
|
|
369
373
|
// A bot-protection layer replaced the page with a challenge that carries no
|
|
370
374
|
// content; the discovered index is the only remaining pointer to that content.
|
|
371
|
-
if (indexSettled.value && primarySettled.reason instanceof ChallengeBlockedError)
|
|
375
|
+
if (indexSettled.value && primarySettled.reason instanceof ChallengeBlockedError) {
|
|
372
376
|
return { ...indexSettled.value.document, llmsTxtFallback: true };
|
|
377
|
+
}
|
|
373
378
|
|
|
374
379
|
throw primarySettled.reason;
|
|
375
380
|
}
|
|
@@ -388,8 +393,9 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
388
393
|
? await probeUsableRawText(describedBy, signal, dependencies)
|
|
389
394
|
: undefined;
|
|
390
395
|
|
|
391
|
-
if (described && describedBy && index?.url !== describedBy.href)
|
|
396
|
+
if (described && describedBy && index?.url !== describedBy.href) {
|
|
392
397
|
index = { url: describedBy.href, document: described };
|
|
398
|
+
}
|
|
393
399
|
}
|
|
394
400
|
|
|
395
401
|
if (
|
|
@@ -406,8 +412,13 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
406
412
|
false,
|
|
407
413
|
);
|
|
408
414
|
|
|
409
|
-
if (isSafeToProbe(toAbsoluteUrl(spec.url), primary.url) && spec.openapiSpec)
|
|
410
|
-
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
|
+
}
|
|
411
422
|
} catch (error) {
|
|
412
423
|
if (signal?.aborted) throw error;
|
|
413
424
|
}
|
|
@@ -442,14 +453,16 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
442
453
|
/^(text\/markdown|text\/x-markdown)(?:;|$)/i.test(alternate.contentType) &&
|
|
443
454
|
alternate.markdown.trim().length >= LLMS_TXT_MIN_MARKDOWN_CHARACTERS &&
|
|
444
455
|
!alternate.shellSuspected
|
|
445
|
-
)
|
|
456
|
+
) {
|
|
446
457
|
return {
|
|
447
458
|
...alternate,
|
|
459
|
+
fragmentTabs: primary.fragmentTabs,
|
|
448
460
|
markdownAlternateFallback: true,
|
|
449
461
|
markdownAlternateReason: advertised ? "advertised" : "preferred",
|
|
450
462
|
llmsTxtIndexUrl: index?.url,
|
|
451
463
|
llmsTxtIndexAliases: index?.aliases,
|
|
452
464
|
};
|
|
465
|
+
}
|
|
453
466
|
} catch (error) {
|
|
454
467
|
if (signal?.aborted) throw error;
|
|
455
468
|
}
|
|
@@ -473,6 +486,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
473
486
|
if (alternate && markdownAlternate) {
|
|
474
487
|
return {
|
|
475
488
|
...alternate,
|
|
489
|
+
fragmentTabs: primary.fragmentTabs,
|
|
476
490
|
markdownAlternateFallback: true,
|
|
477
491
|
markdownAlternateReason: "advertised",
|
|
478
492
|
};
|
|
@@ -488,8 +502,12 @@ export async function fetchDocumentWithLlmsTxtSupport(
|
|
|
488
502
|
(!primary.links || (primary.links.internal.length === 0 && primary.links.external.length === 0))
|
|
489
503
|
) {
|
|
490
504
|
// Preserve diagnostics for empty challenge pages and JavaScript app shells.
|
|
491
|
-
if (
|
|
505
|
+
if (
|
|
506
|
+
primary.extractionDiagnostics?.botWall ||
|
|
507
|
+
primary.extractionDiagnostics?.javascriptRequired
|
|
508
|
+
) {
|
|
492
509
|
return primary;
|
|
510
|
+
}
|
|
493
511
|
|
|
494
512
|
throw new Error("web_fetch: Page has no extractable content.");
|
|
495
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,
|