@dsh-ray/assistant-association 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/cordis.patch.yml +26 -0
- package/lib/aho-corasick.d.ts +41 -0
- package/lib/aho-corasick.d.ts.map +1 -0
- package/lib/aho-corasick.js +352 -0
- package/lib/aho-corasick.js.map +1 -0
- package/lib/bm25.d.ts +17 -0
- package/lib/bm25.d.ts.map +1 -0
- package/lib/bm25.js +73 -0
- package/lib/bm25.js.map +1 -0
- package/lib/clustering.d.ts +161 -0
- package/lib/clustering.d.ts.map +1 -0
- package/lib/clustering.js +1043 -0
- package/lib/clustering.js.map +1 -0
- package/lib/config.d.ts +67 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +834 -0
- package/lib/config.js.map +1 -0
- package/lib/cues.d.ts +134 -0
- package/lib/cues.d.ts.map +1 -0
- package/lib/cues.js +793 -0
- package/lib/cues.js.map +1 -0
- package/lib/dreaming.d.ts +211 -0
- package/lib/dreaming.d.ts.map +1 -0
- package/lib/dreaming.js +1418 -0
- package/lib/dreaming.js.map +1 -0
- package/lib/entities.d.ts +18 -0
- package/lib/entities.d.ts.map +1 -0
- package/lib/entities.js +111 -0
- package/lib/entities.js.map +1 -0
- package/lib/eval-pool.d.ts +111 -0
- package/lib/eval-pool.d.ts.map +1 -0
- package/lib/eval-pool.js +392 -0
- package/lib/eval-pool.js.map +1 -0
- package/lib/hebbian.d.ts +54 -0
- package/lib/hebbian.d.ts.map +1 -0
- package/lib/hebbian.js +226 -0
- package/lib/hebbian.js.map +1 -0
- package/lib/holdout.d.ts +18 -0
- package/lib/holdout.d.ts.map +1 -0
- package/lib/holdout.js +97 -0
- package/lib/holdout.js.map +1 -0
- package/lib/hot-path.d.ts +8 -0
- package/lib/hot-path.d.ts.map +1 -0
- package/lib/hot-path.js +503 -0
- package/lib/hot-path.js.map +1 -0
- package/lib/hysteresis.d.ts +39 -0
- package/lib/hysteresis.d.ts.map +1 -0
- package/lib/hysteresis.js +297 -0
- package/lib/hysteresis.js.map +1 -0
- package/lib/index-memory.d.ts +112 -0
- package/lib/index-memory.d.ts.map +1 -0
- package/lib/index-memory.js +391 -0
- package/lib/index-memory.js.map +1 -0
- package/lib/index.d.ts +37 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +37 -0
- package/lib/index.js.map +1 -0
- package/lib/intake-signal.d.ts +158 -0
- package/lib/intake-signal.d.ts.map +1 -0
- package/lib/intake-signal.js +366 -0
- package/lib/intake-signal.js.map +1 -0
- package/lib/param-tuning.d.ts +302 -0
- package/lib/param-tuning.d.ts.map +1 -0
- package/lib/param-tuning.js +1743 -0
- package/lib/param-tuning.js.map +1 -0
- package/lib/service.d.ts +164 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +2071 -0
- package/lib/service.js.map +1 -0
- package/lib/sources.d.ts +42 -0
- package/lib/sources.d.ts.map +1 -0
- package/lib/sources.js +2024 -0
- package/lib/sources.js.map +1 -0
- package/lib/sqlite.d.ts +88 -0
- package/lib/sqlite.d.ts.map +1 -0
- package/lib/sqlite.js +1815 -0
- package/lib/sqlite.js.map +1 -0
- package/lib/tokenize.d.ts +4 -0
- package/lib/tokenize.d.ts.map +1 -0
- package/lib/tokenize.js +35 -0
- package/lib/tokenize.js.map +1 -0
- package/lib/tools.d.ts +27 -0
- package/lib/tools.d.ts.map +1 -0
- package/lib/tools.js +126 -0
- package/lib/tools.js.map +1 -0
- package/lib/types.d.ts +551 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +163 -0
- package/lib/types.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/lib/web-fetch.d.ts +95 -0
- package/lib/web-fetch.d.ts.map +1 -0
- package/lib/web-fetch.js +833 -0
- package/lib/web-fetch.js.map +1 -0
- package/lib/web-learning-interests.d.ts +42 -0
- package/lib/web-learning-interests.d.ts.map +1 -0
- package/lib/web-learning-interests.js +4344 -0
- package/lib/web-learning-interests.js.map +1 -0
- package/lib/web-learning-runner.d.ts +43 -0
- package/lib/web-learning-runner.d.ts.map +1 -0
- package/lib/web-learning-runner.js +322 -0
- package/lib/web-learning-runner.js.map +1 -0
- package/lib/web-learning-worker.d.ts +75 -0
- package/lib/web-learning-worker.d.ts.map +1 -0
- package/lib/web-learning-worker.js +367 -0
- package/lib/web-learning-worker.js.map +1 -0
- package/lib/web-learning.d.ts +161 -0
- package/lib/web-learning.d.ts.map +1 -0
- package/lib/web-learning.js +912 -0
- package/lib/web-learning.js.map +1 -0
- package/lib/write-queue.d.ts +42 -0
- package/lib/write-queue.d.ts.map +1 -0
- package/lib/write-queue.js +439 -0
- package/lib/write-queue.js.map +1 -0
- package/package.json +156 -3
package/lib/web-fetch.js
ADDED
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
2
|
+
import { request as nodeHttpsRequest } from 'node:https';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
const MAX_DNS_ANSWERS = 16;
|
|
6
|
+
const DEFAULT_MAX_URL_LENGTH = 2_048;
|
|
7
|
+
const DEFAULT_MAX_REDIRECTS = 2;
|
|
8
|
+
const DEFAULT_MAX_HTML_TEXT_CHARS = 8_192;
|
|
9
|
+
const DEFAULT_MAX_TITLE_CHARS = 160;
|
|
10
|
+
const DEFAULT_MAX_EXTRACTED_LINKS = 16;
|
|
11
|
+
export const ALLOWED_WEB_MIME_TYPES = new Set([
|
|
12
|
+
'text/html',
|
|
13
|
+
'application/xhtml+xml',
|
|
14
|
+
'text/plain',
|
|
15
|
+
'text/markdown',
|
|
16
|
+
'application/json',
|
|
17
|
+
'application/xml',
|
|
18
|
+
'application/rss+xml',
|
|
19
|
+
'application/atom+xml',
|
|
20
|
+
]);
|
|
21
|
+
export const CREDENTIAL_HEADER_NAMES = new Set([
|
|
22
|
+
'authorization',
|
|
23
|
+
'proxy-authorization',
|
|
24
|
+
'cookie',
|
|
25
|
+
'cookie2',
|
|
26
|
+
'x-api-key',
|
|
27
|
+
'x-auth-token',
|
|
28
|
+
'x-csrf-token',
|
|
29
|
+
'x-xsrf-token',
|
|
30
|
+
]);
|
|
31
|
+
export const READ_ONLY_WEB_HEADERS = Object.freeze({
|
|
32
|
+
accept: 'text/html,application/xhtml+xml,text/plain,text/markdown,application/json;q=0.9',
|
|
33
|
+
'accept-encoding': 'identity',
|
|
34
|
+
'user-agent': 'dsh-ray-web-learning/1.0',
|
|
35
|
+
});
|
|
36
|
+
export const ALLOWED_WEB_LEARNING_ENV_KEYS = ['PATH', 'LANG', 'LC_ALL', 'TZ'];
|
|
37
|
+
export const ALLOWED_WEB_LEARNING_TOOLS = new Set([
|
|
38
|
+
'web_fetch_readonly',
|
|
39
|
+
]);
|
|
40
|
+
export const FORBIDDEN_WEB_LEARNING_TOOLS = new Set([
|
|
41
|
+
'write',
|
|
42
|
+
'edit',
|
|
43
|
+
'multi_edit',
|
|
44
|
+
'patch',
|
|
45
|
+
'delete',
|
|
46
|
+
'rm',
|
|
47
|
+
'bash',
|
|
48
|
+
'exec',
|
|
49
|
+
'shell',
|
|
50
|
+
'run_command',
|
|
51
|
+
'spawn',
|
|
52
|
+
'memory_manage',
|
|
53
|
+
'memory_write',
|
|
54
|
+
'wiki_upsert',
|
|
55
|
+
'wiki_write',
|
|
56
|
+
'goal_create',
|
|
57
|
+
'goal_update',
|
|
58
|
+
'work_item_create',
|
|
59
|
+
'work_item_update',
|
|
60
|
+
'work_item_admit',
|
|
61
|
+
'action_execute',
|
|
62
|
+
'action_propose',
|
|
63
|
+
'isolation_run',
|
|
64
|
+
'assoc_read',
|
|
65
|
+
'plugin_install',
|
|
66
|
+
'config_write',
|
|
67
|
+
]);
|
|
68
|
+
const FORBIDDEN_TOOL_PREFIXES = [
|
|
69
|
+
'write_',
|
|
70
|
+
'edit_',
|
|
71
|
+
'delete_',
|
|
72
|
+
'exec_',
|
|
73
|
+
'shell_',
|
|
74
|
+
'bash_',
|
|
75
|
+
'memory_',
|
|
76
|
+
'wiki_',
|
|
77
|
+
'goal_',
|
|
78
|
+
'work_item_',
|
|
79
|
+
'action_',
|
|
80
|
+
'isolation_',
|
|
81
|
+
'assoc_',
|
|
82
|
+
];
|
|
83
|
+
export class WebFetchError extends Error {
|
|
84
|
+
code;
|
|
85
|
+
constructor(code, message, options) {
|
|
86
|
+
super(message, options);
|
|
87
|
+
this.name = 'WebFetchError';
|
|
88
|
+
this.code = code;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function unbracketHost(host) {
|
|
92
|
+
const lower = host.toLowerCase();
|
|
93
|
+
return lower.startsWith('[') && lower.endsWith(']') ? lower.slice(1, -1) : lower;
|
|
94
|
+
}
|
|
95
|
+
function isForbiddenHostname(host) {
|
|
96
|
+
return (host === ''
|
|
97
|
+
|| host.endsWith('.')
|
|
98
|
+
|| host === 'localhost'
|
|
99
|
+
|| host.endsWith('.localhost')
|
|
100
|
+
|| host.endsWith('.local')
|
|
101
|
+
|| host.endsWith('.internal')
|
|
102
|
+
|| host.endsWith('.arpa'));
|
|
103
|
+
}
|
|
104
|
+
function normalizeAllowedDomains(domains) {
|
|
105
|
+
const normalized = [];
|
|
106
|
+
const seen = new Set();
|
|
107
|
+
for (const raw of domains) {
|
|
108
|
+
const candidate = raw.trim().toLowerCase();
|
|
109
|
+
if (candidate === '')
|
|
110
|
+
continue;
|
|
111
|
+
if (candidate.includes('://')
|
|
112
|
+
|| candidate.includes('/')
|
|
113
|
+
|| candidate.includes(':')
|
|
114
|
+
|| candidate.includes('*')
|
|
115
|
+
|| /\s/u.test(candidate)
|
|
116
|
+
|| isIP(unbracketHost(candidate)) !== 0
|
|
117
|
+
|| isForbiddenHostname(candidate)) {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (!seen.has(candidate)) {
|
|
121
|
+
seen.add(candidate);
|
|
122
|
+
normalized.push(candidate);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return normalized;
|
|
126
|
+
}
|
|
127
|
+
export function validateWhitelistedWebUrl(rawUrl, options) {
|
|
128
|
+
const allowed = normalizeAllowedDomains(options.allowedDomains);
|
|
129
|
+
if (allowed.length === 0) {
|
|
130
|
+
throw new WebFetchError('rejected-empty-whitelist', 'web-learning: domain whitelist is empty (fail-closed)');
|
|
131
|
+
}
|
|
132
|
+
const maxLen = options.maxUrlLength ?? DEFAULT_MAX_URL_LENGTH;
|
|
133
|
+
if (typeof rawUrl !== 'string' || rawUrl.trim() === '' || rawUrl.length > maxLen) {
|
|
134
|
+
throw new WebFetchError('rejected-invalid-url', 'web-learning: URL is empty or exceeds maximum length');
|
|
135
|
+
}
|
|
136
|
+
let parsed;
|
|
137
|
+
try {
|
|
138
|
+
parsed = new URL(rawUrl);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
throw new WebFetchError('rejected-invalid-url', 'web-learning: URL could not be parsed', { cause: error });
|
|
142
|
+
}
|
|
143
|
+
if (parsed.protocol !== 'https:') {
|
|
144
|
+
throw new WebFetchError('rejected-scheme', `web-learning: only https:// URLs are allowed (got ${parsed.protocol})`);
|
|
145
|
+
}
|
|
146
|
+
if (parsed.username !== '' || parsed.password !== '') {
|
|
147
|
+
throw new WebFetchError('rejected-credentials', 'web-learning: embedded URL credentials are not allowed');
|
|
148
|
+
}
|
|
149
|
+
if (parsed.port !== '' && parsed.port !== '443') {
|
|
150
|
+
throw new WebFetchError('rejected-port', `web-learning: non-443 port (${parsed.port}) is not allowed`);
|
|
151
|
+
}
|
|
152
|
+
const host = unbracketHost(parsed.hostname);
|
|
153
|
+
if (isIP(host) !== 0 || host.includes(':')) {
|
|
154
|
+
throw new WebFetchError('rejected-ip-literal', `web-learning: IP literal host (${host}) is not allowed`);
|
|
155
|
+
}
|
|
156
|
+
if (isForbiddenHostname(host)) {
|
|
157
|
+
throw new WebFetchError('rejected-forbidden-host', `web-learning: forbidden host (${host}) is not allowed`);
|
|
158
|
+
}
|
|
159
|
+
const allowSubdomains = options.allowSubdomains === true;
|
|
160
|
+
const matchedDomain = allowed.find(domain => host === domain || (allowSubdomains && host.endsWith(`.${domain}`)));
|
|
161
|
+
if (matchedDomain === undefined) {
|
|
162
|
+
throw new WebFetchError('rejected-whitelist', `web-learning: host ${host} is outside the domain whitelist`);
|
|
163
|
+
}
|
|
164
|
+
parsed.hash = '';
|
|
165
|
+
return {
|
|
166
|
+
url: parsed,
|
|
167
|
+
canonicalUrl: parsed.toString(),
|
|
168
|
+
hostname: host,
|
|
169
|
+
matchedDomain,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function ipv4Bytes(address) {
|
|
173
|
+
if (isIP(address) !== 4)
|
|
174
|
+
return undefined;
|
|
175
|
+
const parts = address.split('.').map(Number);
|
|
176
|
+
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
return parts;
|
|
180
|
+
}
|
|
181
|
+
function globalIpv4(parts) {
|
|
182
|
+
const [a, b, c] = parts;
|
|
183
|
+
return !(a === 0
|
|
184
|
+
|| a === 10
|
|
185
|
+
|| a === 127
|
|
186
|
+
|| a >= 224
|
|
187
|
+
|| (a === 100 && b >= 64 && b <= 127)
|
|
188
|
+
|| (a === 169 && b === 254)
|
|
189
|
+
|| (a === 172 && b >= 16 && b <= 31)
|
|
190
|
+
|| (a === 192 && b === 168)
|
|
191
|
+
|| (a === 192 && b === 0 && (c === 0 || c === 2))
|
|
192
|
+
|| (a === 192 && b === 88 && c === 99)
|
|
193
|
+
|| (a === 198 && (b === 18 || b === 19))
|
|
194
|
+
|| (a === 198 && b === 51 && c === 100)
|
|
195
|
+
|| (a === 203 && b === 0 && c === 113));
|
|
196
|
+
}
|
|
197
|
+
function ipv6Bytes(address) {
|
|
198
|
+
if (address.includes('%') || isIP(address) !== 6)
|
|
199
|
+
return undefined;
|
|
200
|
+
const halves = address.toLowerCase().split('::');
|
|
201
|
+
if (halves.length > 2)
|
|
202
|
+
return undefined;
|
|
203
|
+
const parseHalf = (value) => {
|
|
204
|
+
if (value === '')
|
|
205
|
+
return [];
|
|
206
|
+
const raw = value.split(':');
|
|
207
|
+
const result = [];
|
|
208
|
+
for (let index = 0; index < raw.length; index += 1) {
|
|
209
|
+
const part = raw[index];
|
|
210
|
+
if (part.includes('.')) {
|
|
211
|
+
if (index !== raw.length - 1)
|
|
212
|
+
return undefined;
|
|
213
|
+
const embedded = ipv4Bytes(part);
|
|
214
|
+
if (embedded === undefined)
|
|
215
|
+
return undefined;
|
|
216
|
+
result.push((embedded[0] << 8) | embedded[1], (embedded[2] << 8) | embedded[3]);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
if (!/^[a-f0-9]{1,4}$/u.test(part))
|
|
220
|
+
return undefined;
|
|
221
|
+
result.push(Number.parseInt(part, 16));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return result;
|
|
225
|
+
};
|
|
226
|
+
const left = parseHalf(halves[0]);
|
|
227
|
+
const right = parseHalf(halves[1] ?? '');
|
|
228
|
+
if (left === undefined || right === undefined)
|
|
229
|
+
return undefined;
|
|
230
|
+
const omitted = 8 - left.length - right.length;
|
|
231
|
+
if ((halves.length === 1 && omitted !== 0) || (halves.length === 2 && omitted < 1)) {
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
const groups = halves.length === 1
|
|
235
|
+
? left
|
|
236
|
+
: [...left, ...Array.from({ length: omitted }, () => 0), ...right];
|
|
237
|
+
if (groups.length !== 8)
|
|
238
|
+
return undefined;
|
|
239
|
+
const bytes = new Uint8Array(16);
|
|
240
|
+
groups.forEach((group, index) => {
|
|
241
|
+
bytes[index * 2] = group >>> 8;
|
|
242
|
+
bytes[index * 2 + 1] = group & 0xff;
|
|
243
|
+
});
|
|
244
|
+
return bytes;
|
|
245
|
+
}
|
|
246
|
+
function hasPrefix(value, prefix, bits) {
|
|
247
|
+
const bytes = Math.floor(bits / 8);
|
|
248
|
+
for (let index = 0; index < bytes; index += 1) {
|
|
249
|
+
if (value[index] !== prefix[index])
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
const remaining = bits % 8;
|
|
253
|
+
if (remaining === 0)
|
|
254
|
+
return true;
|
|
255
|
+
const mask = 0xff << (8 - remaining);
|
|
256
|
+
return (value[bytes] & mask) === (prefix[bytes] & mask);
|
|
257
|
+
}
|
|
258
|
+
function globalIpv6(bytes) {
|
|
259
|
+
const mapped = bytes.slice(12);
|
|
260
|
+
if (bytes.slice(0, 10).every(value => value === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {
|
|
261
|
+
return globalIpv4(mapped);
|
|
262
|
+
}
|
|
263
|
+
if (bytes[0] < 0x20 || bytes[0] > 0x3f)
|
|
264
|
+
return false;
|
|
265
|
+
if (hasPrefix(bytes, [0x20, 0x01, 0x0d, 0xb8], 32)
|
|
266
|
+
|| hasPrefix(bytes, [0x20, 0x01, 0x00, 0x00], 32)
|
|
267
|
+
|| hasPrefix(bytes, [0x20, 0x01, 0x00, 0x10], 28)
|
|
268
|
+
|| hasPrefix(bytes, [0x20, 0x01, 0x00, 0x20], 28)
|
|
269
|
+
|| hasPrefix(bytes, [0x20, 0x01, 0x00, 0x02, 0x00, 0x00], 48)
|
|
270
|
+
|| hasPrefix(bytes, [0x3f, 0xff, 0x00], 20)) {
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
if (hasPrefix(bytes, [0x20, 0x02], 16)) {
|
|
274
|
+
return globalIpv4(bytes.slice(2, 6));
|
|
275
|
+
}
|
|
276
|
+
const isatap = (bytes[8] === 0 || bytes[8] === 2)
|
|
277
|
+
&& bytes[9] === 0
|
|
278
|
+
&& bytes[10] === 0x5e
|
|
279
|
+
&& bytes[11] === 0xfe;
|
|
280
|
+
return !isatap || globalIpv4(mapped);
|
|
281
|
+
}
|
|
282
|
+
export function isGlobalPublicIp(address, allowIpv6 = false) {
|
|
283
|
+
const ipv4 = ipv4Bytes(address);
|
|
284
|
+
if (ipv4 !== undefined)
|
|
285
|
+
return globalIpv4(ipv4);
|
|
286
|
+
const ipv6 = ipv6Bytes(address);
|
|
287
|
+
if (ipv6 !== undefined)
|
|
288
|
+
return allowIpv6 && globalIpv6(ipv6);
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
function validatedAddresses(resolved, allowIpv6) {
|
|
292
|
+
if (resolved.length === 0 || resolved.length > MAX_DNS_ANSWERS) {
|
|
293
|
+
throw new WebFetchError('rejected-dns', `web-learning: DNS answer count (${resolved.length}) is outside [1, ${MAX_DNS_ANSWERS}]`);
|
|
294
|
+
}
|
|
295
|
+
const seen = new Set();
|
|
296
|
+
const addresses = [];
|
|
297
|
+
for (const item of resolved) {
|
|
298
|
+
const ipv4 = ipv4Bytes(item.address);
|
|
299
|
+
const ipv6 = ipv6Bytes(item.address);
|
|
300
|
+
const family = ipv4 === undefined ? (ipv6 === undefined ? 0 : 6) : 4;
|
|
301
|
+
if ((family !== 4 && family !== 6)
|
|
302
|
+
|| family !== item.family
|
|
303
|
+
|| (ipv4 !== undefined ? !globalIpv4(ipv4) : ipv6 === undefined || !globalIpv6(ipv6))) {
|
|
304
|
+
throw new WebFetchError('rejected-ssrf', `web-learning: host resolved to unsafe or invalid address (${item.address})`);
|
|
305
|
+
}
|
|
306
|
+
if (family === 6 && !allowIpv6) {
|
|
307
|
+
throw new WebFetchError('rejected-ssrf', `web-learning: IPv6 address (${item.address}) is blocked unless allowIpv6 is enabled`);
|
|
308
|
+
}
|
|
309
|
+
const key = `${family}:${Buffer.from(ipv4 ?? ipv6).toString('hex')}`;
|
|
310
|
+
if (seen.has(key))
|
|
311
|
+
continue;
|
|
312
|
+
seen.add(key);
|
|
313
|
+
addresses.push(Object.freeze({ address: item.address, family }));
|
|
314
|
+
}
|
|
315
|
+
return Object.freeze(addresses);
|
|
316
|
+
}
|
|
317
|
+
export async function defaultWebLookup(hostname) {
|
|
318
|
+
return dnsLookup(hostname, { all: true, verbatim: true });
|
|
319
|
+
}
|
|
320
|
+
function abortError(signal) {
|
|
321
|
+
if (signal.reason instanceof WebFetchError)
|
|
322
|
+
return signal.reason;
|
|
323
|
+
if (signal.reason instanceof Error)
|
|
324
|
+
return signal.reason;
|
|
325
|
+
return new WebFetchError('rejected-aborted', 'web-learning: request was aborted');
|
|
326
|
+
}
|
|
327
|
+
async function raceWithAbort(operation, signal) {
|
|
328
|
+
if (signal.aborted)
|
|
329
|
+
throw abortError(signal);
|
|
330
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
331
|
+
const aborted = () => {
|
|
332
|
+
cleanup();
|
|
333
|
+
rejectPromise(abortError(signal));
|
|
334
|
+
};
|
|
335
|
+
const cleanup = () => signal.removeEventListener('abort', aborted);
|
|
336
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
337
|
+
void operation.then(value => {
|
|
338
|
+
cleanup();
|
|
339
|
+
resolvePromise(value);
|
|
340
|
+
}, error => {
|
|
341
|
+
cleanup();
|
|
342
|
+
rejectPromise(error);
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
export async function resolveAndValidatePublicAddresses(hostname, options) {
|
|
347
|
+
const cleanHost = unbracketHost(hostname);
|
|
348
|
+
if (isIP(cleanHost) !== 0 || cleanHost.includes(':')) {
|
|
349
|
+
throw new WebFetchError('rejected-ip-literal', `web-learning: IP literal (${cleanHost}) cannot be resolved`);
|
|
350
|
+
}
|
|
351
|
+
if (isForbiddenHostname(cleanHost)) {
|
|
352
|
+
throw new WebFetchError('rejected-forbidden-host', `web-learning: forbidden host (${cleanHost})`);
|
|
353
|
+
}
|
|
354
|
+
const lookup = options?.lookup ?? defaultWebLookup;
|
|
355
|
+
const resolving = lookup(cleanHost);
|
|
356
|
+
const resolved = options?.signal
|
|
357
|
+
? await raceWithAbort(resolving, options.signal)
|
|
358
|
+
: await resolving;
|
|
359
|
+
return validatedAddresses(resolved, options?.allowIpv6 ?? false);
|
|
360
|
+
}
|
|
361
|
+
export function assertReadOnlyRequestSafety(method, extraHeaders) {
|
|
362
|
+
if (method !== undefined && method.toUpperCase() !== 'GET') {
|
|
363
|
+
throw new WebFetchError('rejected-method', `web-learning: HTTP method ${method} is forbidden; only GET is allowed`);
|
|
364
|
+
}
|
|
365
|
+
if (extraHeaders !== undefined) {
|
|
366
|
+
for (const key of Object.keys(extraHeaders)) {
|
|
367
|
+
const normalized = key.trim().toLowerCase();
|
|
368
|
+
if (CREDENTIAL_HEADER_NAMES.has(normalized)
|
|
369
|
+
|| normalized.includes('auth')
|
|
370
|
+
|| normalized.includes('cookie')
|
|
371
|
+
|| normalized.includes('token')
|
|
372
|
+
|| normalized.includes('secret')
|
|
373
|
+
|| normalized.includes('password')
|
|
374
|
+
|| normalized.includes('credential')) {
|
|
375
|
+
throw new WebFetchError('rejected-header', `web-learning: credential header "${key}" is forbidden`);
|
|
376
|
+
}
|
|
377
|
+
if (!(normalized in READ_ONLY_WEB_HEADERS)) {
|
|
378
|
+
throw new WebFetchError('rejected-header', `web-learning: non-allowlisted header "${key}" is forbidden`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
function createPinnedHttpsFetcher(httpsRequestImpl) {
|
|
384
|
+
return async (urlValue, init, route) => {
|
|
385
|
+
const url = new URL(urlValue);
|
|
386
|
+
const certificateHost = unbracketHost(url.hostname);
|
|
387
|
+
const selected = route.addresses[0];
|
|
388
|
+
if (selected === undefined) {
|
|
389
|
+
throw new WebFetchError('rejected-ssrf', 'web-learning: validated route has no pinned address');
|
|
390
|
+
}
|
|
391
|
+
const lookup = (_hostname, options, callback) => {
|
|
392
|
+
if (options.all)
|
|
393
|
+
callback(null, [selected]);
|
|
394
|
+
else
|
|
395
|
+
callback(null, selected.address, selected.family);
|
|
396
|
+
};
|
|
397
|
+
return new Promise((resolveResponse, rejectResponse) => {
|
|
398
|
+
const request = httpsRequestImpl(url, {
|
|
399
|
+
agent: false,
|
|
400
|
+
method: 'GET',
|
|
401
|
+
headers: { ...READ_ONLY_WEB_HEADERS },
|
|
402
|
+
lookup,
|
|
403
|
+
servername: certificateHost,
|
|
404
|
+
rejectUnauthorized: true,
|
|
405
|
+
...(init.signal ? { signal: init.signal } : {}),
|
|
406
|
+
}, response => {
|
|
407
|
+
try {
|
|
408
|
+
const headers = new Headers();
|
|
409
|
+
for (const [name, value] of Object.entries(response.headers)) {
|
|
410
|
+
if (name.toLowerCase() === 'set-cookie')
|
|
411
|
+
continue;
|
|
412
|
+
if (Array.isArray(value)) {
|
|
413
|
+
for (const item of value)
|
|
414
|
+
headers.append(name, item);
|
|
415
|
+
}
|
|
416
|
+
else if (value !== undefined) {
|
|
417
|
+
headers.set(name, value);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const status = response.statusCode ?? 500;
|
|
421
|
+
const hasNullBody = status === 204 || status === 205 || status === 304;
|
|
422
|
+
const body = hasNullBody ? null : Readable.toWeb(response);
|
|
423
|
+
if (hasNullBody)
|
|
424
|
+
response.destroy();
|
|
425
|
+
resolveResponse(new Response(body, { status, headers }));
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
response.destroy();
|
|
429
|
+
rejectResponse(error);
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
request.once('error', error => {
|
|
433
|
+
if (init.signal?.aborted) {
|
|
434
|
+
rejectResponse(abortError(init.signal));
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
rejectResponse(error);
|
|
438
|
+
});
|
|
439
|
+
request.end();
|
|
440
|
+
});
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
async function cancelBody(response, signal) {
|
|
444
|
+
if (response.body === null)
|
|
445
|
+
return;
|
|
446
|
+
try {
|
|
447
|
+
await raceWithAbort(response.body.cancel(), signal);
|
|
448
|
+
}
|
|
449
|
+
catch {
|
|
450
|
+
// Ignore uncooperative cancel failures; caller already rejects.
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function cancelReader(reader) {
|
|
454
|
+
try {
|
|
455
|
+
void reader.cancel().catch(() => { });
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
// Ignore synchronous cancel error.
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async function boundedBody(response, maximum, signal) {
|
|
462
|
+
const declared = response.headers.get('content-length');
|
|
463
|
+
if (declared !== null && declared.trim() !== '') {
|
|
464
|
+
const parsedLength = Number(declared);
|
|
465
|
+
if (Number.isFinite(parsedLength) && parsedLength > maximum) {
|
|
466
|
+
await cancelBody(response, signal);
|
|
467
|
+
throw new WebFetchError('rejected-size', `web-learning: declared Content-Length (${parsedLength}) exceeds cap (${maximum})`);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (response.body === null)
|
|
471
|
+
return Buffer.alloc(0);
|
|
472
|
+
const reader = response.body.getReader();
|
|
473
|
+
const chunks = [];
|
|
474
|
+
let total = 0;
|
|
475
|
+
while (true) {
|
|
476
|
+
let chunkResult;
|
|
477
|
+
try {
|
|
478
|
+
chunkResult = await raceWithAbort(reader.read(), signal);
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
cancelReader(reader);
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
if (chunkResult.done)
|
|
485
|
+
break;
|
|
486
|
+
total += chunkResult.value.byteLength;
|
|
487
|
+
if (total > maximum) {
|
|
488
|
+
cancelReader(reader);
|
|
489
|
+
throw new WebFetchError('rejected-size', `web-learning: response body exceeded byte cap (${maximum})`);
|
|
490
|
+
}
|
|
491
|
+
chunks.push(Buffer.from(chunkResult.value));
|
|
492
|
+
}
|
|
493
|
+
return Buffer.concat(chunks, total);
|
|
494
|
+
}
|
|
495
|
+
function parseMimeEssence(contentTypeHeader) {
|
|
496
|
+
if (contentTypeHeader === null)
|
|
497
|
+
return '';
|
|
498
|
+
const essence = contentTypeHeader.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
|
499
|
+
return essence;
|
|
500
|
+
}
|
|
501
|
+
function decodeBodyText(buffer, contentTypeHeader) {
|
|
502
|
+
const match = contentTypeHeader?.match(/;\s*charset\s*=\s*"?([a-zA-Z0-9._-]+)"?/iu);
|
|
503
|
+
const charset = match?.[1]?.toLowerCase();
|
|
504
|
+
if (charset === 'utf-8' || charset === 'utf8' || charset === undefined) {
|
|
505
|
+
return buffer.toString('utf8');
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
return new TextDecoder(charset, { fatal: false }).decode(buffer);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return buffer.toString('utf8');
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function mapRedirectValidationError(error, nextUrl) {
|
|
515
|
+
if (error instanceof WebFetchError) {
|
|
516
|
+
if (error.code === 'rejected-ip-literal' || error.code === 'rejected-forbidden-host' || error.code === 'rejected-ssrf') {
|
|
517
|
+
return new WebFetchError('rejected-ssrf', `web-learning: redirect target blocked by SSRF policy (${nextUrl})`, { cause: error });
|
|
518
|
+
}
|
|
519
|
+
return new WebFetchError('rejected-redirect', `web-learning: redirect target rejected (${error.code})`, { cause: error });
|
|
520
|
+
}
|
|
521
|
+
return new WebFetchError('rejected-redirect', `web-learning: redirect target rejected (${nextUrl})`, { cause: error });
|
|
522
|
+
}
|
|
523
|
+
export async function fetchWebPageReadOnly(input, deps) {
|
|
524
|
+
assertReadOnlyRequestSafety(input.method, input.extraHeaders);
|
|
525
|
+
if (!Number.isInteger(input.maxBytes) || input.maxBytes <= 0) {
|
|
526
|
+
throw new WebFetchError('rejected-size', 'web-learning: maxBytes must be a positive integer');
|
|
527
|
+
}
|
|
528
|
+
if (!Number.isFinite(input.requestTimeoutMs) || input.requestTimeoutMs <= 0) {
|
|
529
|
+
throw new WebFetchError('rejected-timeout', 'web-learning: requestTimeoutMs must be positive');
|
|
530
|
+
}
|
|
531
|
+
const maxRedirects = input.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
|
|
532
|
+
if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
|
|
533
|
+
throw new WebFetchError('rejected-redirect', 'web-learning: maxRedirects must be a non-negative integer');
|
|
534
|
+
}
|
|
535
|
+
const now = deps?.now ?? Date.now;
|
|
536
|
+
const fetcher = deps?.fetcher ?? createPinnedHttpsFetcher(deps?.httpsRequest ?? nodeHttpsRequest);
|
|
537
|
+
const controller = new AbortController();
|
|
538
|
+
const forwardAbort = () => {
|
|
539
|
+
const reason = input.signal?.reason;
|
|
540
|
+
controller.abort(reason instanceof WebFetchError
|
|
541
|
+
? reason
|
|
542
|
+
: new WebFetchError('rejected-aborted', 'web-learning: fetch aborted by caller', { cause: reason }));
|
|
543
|
+
};
|
|
544
|
+
if (input.signal?.aborted) {
|
|
545
|
+
forwardAbort();
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
input.signal?.addEventListener('abort', forwardAbort, { once: true });
|
|
549
|
+
}
|
|
550
|
+
const timer = setTimeout(() => {
|
|
551
|
+
controller.abort(new WebFetchError('rejected-timeout', `web-learning: request timed out after ${input.requestTimeoutMs}ms`));
|
|
552
|
+
}, input.requestTimeoutMs);
|
|
553
|
+
timer.unref?.();
|
|
554
|
+
let currentUrl = input.url;
|
|
555
|
+
let initialCanonicalUrl;
|
|
556
|
+
const redirectChain = [];
|
|
557
|
+
let requestsUsed = 0;
|
|
558
|
+
try {
|
|
559
|
+
for (let hop = 0; hop <= maxRedirects; hop += 1) {
|
|
560
|
+
let validated;
|
|
561
|
+
try {
|
|
562
|
+
validated = validateWhitelistedWebUrl(currentUrl, {
|
|
563
|
+
allowedDomains: input.allowedDomains,
|
|
564
|
+
...(input.allowSubdomains === undefined ? {} : { allowSubdomains: input.allowSubdomains }),
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
if (hop > 0)
|
|
569
|
+
throw mapRedirectValidationError(error, currentUrl);
|
|
570
|
+
throw error;
|
|
571
|
+
}
|
|
572
|
+
if (initialCanonicalUrl === undefined) {
|
|
573
|
+
initialCanonicalUrl = validated.canonicalUrl;
|
|
574
|
+
}
|
|
575
|
+
let addresses;
|
|
576
|
+
try {
|
|
577
|
+
addresses = await resolveAndValidatePublicAddresses(validated.hostname, {
|
|
578
|
+
...(input.allowIpv6 === undefined ? {} : { allowIpv6: input.allowIpv6 }),
|
|
579
|
+
...(deps?.lookup === undefined ? {} : { lookup: deps.lookup }),
|
|
580
|
+
signal: controller.signal,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
catch (error) {
|
|
584
|
+
if (hop > 0)
|
|
585
|
+
throw mapRedirectValidationError(error, validated.canonicalUrl);
|
|
586
|
+
throw error;
|
|
587
|
+
}
|
|
588
|
+
if (controller.signal.aborted) {
|
|
589
|
+
throw abortError(controller.signal);
|
|
590
|
+
}
|
|
591
|
+
input.onBeforeRequest?.(validated.canonicalUrl, hop);
|
|
592
|
+
requestsUsed += 1;
|
|
593
|
+
const response = await raceWithAbort(fetcher(validated.canonicalUrl, {
|
|
594
|
+
method: 'GET',
|
|
595
|
+
redirect: 'manual',
|
|
596
|
+
signal: controller.signal,
|
|
597
|
+
headers: { ...READ_ONLY_WEB_HEADERS },
|
|
598
|
+
}, { addresses }), controller.signal);
|
|
599
|
+
if (response.status >= 300 && response.status < 400) {
|
|
600
|
+
await cancelBody(response, controller.signal);
|
|
601
|
+
if (hop >= maxRedirects) {
|
|
602
|
+
throw new WebFetchError('rejected-redirect', `web-learning: redirect count exceeded maxRedirects (${maxRedirects})`);
|
|
603
|
+
}
|
|
604
|
+
const location = response.headers.get('location');
|
|
605
|
+
if (location === null || location.trim() === '') {
|
|
606
|
+
throw new WebFetchError('rejected-redirect', 'web-learning: redirect response missing Location header');
|
|
607
|
+
}
|
|
608
|
+
let resolvedNext;
|
|
609
|
+
try {
|
|
610
|
+
resolvedNext = new URL(location, validated.canonicalUrl);
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
throw new WebFetchError('rejected-redirect', 'web-learning: invalid redirect Location URL', { cause: error });
|
|
614
|
+
}
|
|
615
|
+
redirectChain.push(validated.canonicalUrl);
|
|
616
|
+
currentUrl = resolvedNext.toString();
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
if (!response.ok) {
|
|
620
|
+
await cancelBody(response, controller.signal);
|
|
621
|
+
throw new WebFetchError('rejected-http-status', `web-learning: HTTP status ${response.status} rejected`);
|
|
622
|
+
}
|
|
623
|
+
const rawContentType = response.headers.get('content-type');
|
|
624
|
+
const mimeEssence = parseMimeEssence(rawContentType);
|
|
625
|
+
if (!ALLOWED_WEB_MIME_TYPES.has(mimeEssence)) {
|
|
626
|
+
await cancelBody(response, controller.signal);
|
|
627
|
+
throw new WebFetchError('rejected-content-type', `web-learning: MIME type "${mimeEssence || 'missing'}" is not allowlisted`);
|
|
628
|
+
}
|
|
629
|
+
const bodyBuffer = await boundedBody(response, input.maxBytes, controller.signal);
|
|
630
|
+
const bodyText = decodeBodyText(bodyBuffer, rawContentType);
|
|
631
|
+
return {
|
|
632
|
+
sourceUrl: initialCanonicalUrl,
|
|
633
|
+
finalUrl: validated.canonicalUrl,
|
|
634
|
+
status: response.status,
|
|
635
|
+
contentType: mimeEssence,
|
|
636
|
+
bytesFetched: bodyBuffer.byteLength,
|
|
637
|
+
bodyBuffer,
|
|
638
|
+
bodyText,
|
|
639
|
+
requestsUsed,
|
|
640
|
+
redirectChain: Object.freeze([...redirectChain]),
|
|
641
|
+
fetchedAt: now(),
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
throw new WebFetchError('rejected-redirect', `web-learning: redirect count exceeded maxRedirects (${maxRedirects})`);
|
|
645
|
+
}
|
|
646
|
+
finally {
|
|
647
|
+
clearTimeout(timer);
|
|
648
|
+
input.signal?.removeEventListener('abort', forwardAbort);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
function decodeHtmlEntities(input) {
|
|
652
|
+
return input
|
|
653
|
+
.replace(/&#(\d{1,7});/gu, (_full, dec) => {
|
|
654
|
+
const code = Number.parseInt(dec, 10);
|
|
655
|
+
if (!Number.isInteger(code) || code <= 0 || code > 0x10ffff)
|
|
656
|
+
return '';
|
|
657
|
+
if (code < 0x20 && code !== 0x09 && code !== 0x0a)
|
|
658
|
+
return ' ';
|
|
659
|
+
return String.fromCodePoint(code);
|
|
660
|
+
})
|
|
661
|
+
.replace(/&#x([0-9a-fA-F]{1,6});/gu, (_full, hex) => {
|
|
662
|
+
const code = Number.parseInt(hex, 16);
|
|
663
|
+
if (!Number.isInteger(code) || code <= 0 || code > 0x10ffff)
|
|
664
|
+
return '';
|
|
665
|
+
if (code < 0x20 && code !== 0x09 && code !== 0x0a)
|
|
666
|
+
return ' ';
|
|
667
|
+
return String.fromCodePoint(code);
|
|
668
|
+
})
|
|
669
|
+
.replace(/ /giu, ' ')
|
|
670
|
+
.replace(/"/giu, '"')
|
|
671
|
+
.replace(/'|'/giu, '\'')
|
|
672
|
+
.replace(/</giu, '<')
|
|
673
|
+
.replace(/>/giu, '>')
|
|
674
|
+
.replace(/&/giu, '&');
|
|
675
|
+
}
|
|
676
|
+
function stripControlChars(input) {
|
|
677
|
+
let out = '';
|
|
678
|
+
for (let i = 0; i < input.length; i += 1) {
|
|
679
|
+
const code = input.charCodeAt(i);
|
|
680
|
+
if (code === 0x09 || code === 0x0a || (code >= 0x20 && code !== 0x7f)) {
|
|
681
|
+
out += input[i];
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return out;
|
|
685
|
+
}
|
|
686
|
+
function normalizeWhitespace(input) {
|
|
687
|
+
return stripControlChars(input.replace(/\r\n?/gu, '\n'))
|
|
688
|
+
.replace(/[^\S\n]+/gu, ' ')
|
|
689
|
+
.replace(/ *\n */gu, '\n')
|
|
690
|
+
.replace(/\n{3,}/gu, '\n\n')
|
|
691
|
+
.trim();
|
|
692
|
+
}
|
|
693
|
+
function truncateChars(input, maxChars) {
|
|
694
|
+
if (input.length <= maxChars)
|
|
695
|
+
return input;
|
|
696
|
+
const chars = [...input];
|
|
697
|
+
if (chars.length <= maxChars)
|
|
698
|
+
return input;
|
|
699
|
+
return chars.slice(0, maxChars).join('');
|
|
700
|
+
}
|
|
701
|
+
function extractSameWhitelistLinks(rawHtml, options) {
|
|
702
|
+
if (options.baseUrl === undefined
|
|
703
|
+
|| options.allowedDomains === undefined
|
|
704
|
+
|| options.allowedDomains.length === 0) {
|
|
705
|
+
return [];
|
|
706
|
+
}
|
|
707
|
+
const maxLinks = options.maxLinks ?? DEFAULT_MAX_EXTRACTED_LINKS;
|
|
708
|
+
if (maxLinks <= 0)
|
|
709
|
+
return [];
|
|
710
|
+
const results = [];
|
|
711
|
+
const seen = new Set();
|
|
712
|
+
const hrefPattern = /<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/giu;
|
|
713
|
+
let match;
|
|
714
|
+
while ((match = hrefPattern.exec(rawHtml)) !== null) {
|
|
715
|
+
if (results.length >= maxLinks)
|
|
716
|
+
break;
|
|
717
|
+
const rawHref = (match[1] ?? match[2] ?? match[3] ?? '').trim();
|
|
718
|
+
if (rawHref === '' || rawHref.startsWith('#'))
|
|
719
|
+
continue;
|
|
720
|
+
const decodedHref = decodeHtmlEntities(rawHref);
|
|
721
|
+
let resolvedUrl;
|
|
722
|
+
try {
|
|
723
|
+
resolvedUrl = new URL(decodedHref, options.baseUrl).toString();
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
try {
|
|
729
|
+
const validated = validateWhitelistedWebUrl(resolvedUrl, {
|
|
730
|
+
allowedDomains: options.allowedDomains,
|
|
731
|
+
...(options.allowSubdomains === undefined ? {} : { allowSubdomains: options.allowSubdomains }),
|
|
732
|
+
});
|
|
733
|
+
if (!seen.has(validated.canonicalUrl)) {
|
|
734
|
+
seen.add(validated.canonicalUrl);
|
|
735
|
+
results.push(validated.canonicalUrl);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
catch {
|
|
739
|
+
// Ignore off-whitelist, non-https, or unsafe links.
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
return Object.freeze(results);
|
|
743
|
+
}
|
|
744
|
+
function stripCommentsAndRawBlocks(raw) {
|
|
745
|
+
let cleaned = raw;
|
|
746
|
+
let previous = '';
|
|
747
|
+
while (cleaned !== previous) {
|
|
748
|
+
previous = cleaned;
|
|
749
|
+
cleaned = cleaned
|
|
750
|
+
.replace(/<!--[\s\S]*?-->/gu, ' ')
|
|
751
|
+
.replace(/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>/giu, '')
|
|
752
|
+
.replace(/<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>/giu, '')
|
|
753
|
+
.replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript\b[^>]*>/giu, '')
|
|
754
|
+
.replace(/<svg\b[^>]*>[\s\S]*?<\/svg\b[^>]*>/giu, '');
|
|
755
|
+
}
|
|
756
|
+
return cleaned
|
|
757
|
+
.replace(/<!--[\s\S]*$/gu, ' ')
|
|
758
|
+
.replace(/<(?:script|style|noscript|svg)\b[^>]*>[\s\S]*$/giu, '');
|
|
759
|
+
}
|
|
760
|
+
function stripRemainingHtmlTags(sanitizedHtml) {
|
|
761
|
+
const cleaned = sanitizedHtml
|
|
762
|
+
.replace(/<\/?(?:p|div|li|br|hr|tr|h[1-6]|article|section|header|footer|main|blockquote|pre)\b[^>]*>/giu, '\n')
|
|
763
|
+
.replace(/<\/?[a-zA-Z!?][^<>]*>/gu, ' ');
|
|
764
|
+
return normalizeWhitespace(decodeHtmlEntities(cleaned));
|
|
765
|
+
}
|
|
766
|
+
function stripRawTagsForText(raw) {
|
|
767
|
+
return stripRemainingHtmlTags(stripCommentsAndRawBlocks(raw));
|
|
768
|
+
}
|
|
769
|
+
export function extractPlainTextFromHtml(rawContent, options) {
|
|
770
|
+
const maxTextChars = options?.maxTextChars ?? DEFAULT_MAX_HTML_TEXT_CHARS;
|
|
771
|
+
const maxTitleChars = options?.maxTitleChars ?? DEFAULT_MAX_TITLE_CHARS;
|
|
772
|
+
const contentType = options?.contentType?.toLowerCase() ?? 'text/html';
|
|
773
|
+
if (contentType === 'text/plain' || contentType === 'text/markdown') {
|
|
774
|
+
const normalized = truncateChars(normalizeWhitespace(rawContent), maxTextChars);
|
|
775
|
+
const firstLine = normalized.split('\n', 1)[0]?.replace(/^#+\s*/u, '').trim() ?? '';
|
|
776
|
+
return {
|
|
777
|
+
title: truncateChars(firstLine, maxTitleChars),
|
|
778
|
+
text: normalized,
|
|
779
|
+
links: [],
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
if (contentType === 'application/json') {
|
|
783
|
+
let text = normalizeWhitespace(rawContent);
|
|
784
|
+
try {
|
|
785
|
+
const parsed = JSON.parse(rawContent);
|
|
786
|
+
text = normalizeWhitespace(JSON.stringify(parsed));
|
|
787
|
+
}
|
|
788
|
+
catch {
|
|
789
|
+
// Preserve raw normalized text if JSON parsing fails.
|
|
790
|
+
}
|
|
791
|
+
return {
|
|
792
|
+
title: '',
|
|
793
|
+
text: truncateChars(text, maxTextChars),
|
|
794
|
+
links: [],
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
const sanitizedHtml = stripCommentsAndRawBlocks(rawContent);
|
|
798
|
+
const titleMatch = sanitizedHtml.match(/<title\b[^>]*>([\s\S]*?)<\/title\b[^>]*>/iu);
|
|
799
|
+
const h1Match = sanitizedHtml.match(/<h1\b[^>]*>([\s\S]*?)<\/h1\b[^>]*>/iu);
|
|
800
|
+
const rawTitle = titleMatch?.[1] ?? h1Match?.[1] ?? '';
|
|
801
|
+
const title = truncateChars(stripRawTagsForText(rawTitle).replace(/\n+/gu, ' '), maxTitleChars);
|
|
802
|
+
const links = extractSameWhitelistLinks(sanitizedHtml, options ?? {});
|
|
803
|
+
const text = truncateChars(stripRemainingHtmlTags(sanitizedHtml), maxTextChars);
|
|
804
|
+
return {
|
|
805
|
+
title,
|
|
806
|
+
text,
|
|
807
|
+
links,
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
export function sanitizeWebLearningEnv(sourceEnv = process.env) {
|
|
811
|
+
const sanitized = {};
|
|
812
|
+
for (const key of ALLOWED_WEB_LEARNING_ENV_KEYS) {
|
|
813
|
+
const value = sourceEnv[key];
|
|
814
|
+
if (typeof value === 'string' && value.length > 0 && !value.includes('\0') && !value.includes('\r') && !value.includes('\n')) {
|
|
815
|
+
sanitized[key] = value;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return sanitized;
|
|
819
|
+
}
|
|
820
|
+
export function assertReadOnlyWebToolSurface(toolNames, allowedTools = ALLOWED_WEB_LEARNING_TOOLS) {
|
|
821
|
+
for (const rawName of toolNames) {
|
|
822
|
+
const normalized = rawName.trim().toLowerCase();
|
|
823
|
+
if (normalized === '') {
|
|
824
|
+
throw new Error('web-learning: empty tool name is forbidden in read-only tool surface');
|
|
825
|
+
}
|
|
826
|
+
if (FORBIDDEN_WEB_LEARNING_TOOLS.has(normalized)
|
|
827
|
+
|| FORBIDDEN_TOOL_PREFIXES.some(prefix => normalized.startsWith(prefix))
|
|
828
|
+
|| !allowedTools.has(normalized)) {
|
|
829
|
+
throw new Error(`web-learning: tool "${rawName}" is forbidden in isolated read-only surface`);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
//# sourceMappingURL=web-fetch.js.map
|