@arabold/docs-mcp-server 2.2.2 → 2.3.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/README.md +1 -0
- package/dist/assets/main.css +1 -1
- package/dist/assets/main.js +708 -705
- package/dist/assets/main.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{main-DPijzQ1K.js → main-CCLTqj8g.js} +1079 -303
- package/dist/main-CCLTqj8g.js.map +1 -0
- package/dist/{utils-ntayxPjd.js → utils-CUTutkx-.js} +12 -12
- package/dist/{utils-ntayxPjd.js.map → utils-CUTutkx-.js.map} +1 -1
- package/package.json +17 -17
- package/public/assets/main.css +1 -1
- package/public/assets/main.js +708 -705
- package/public/assets/main.js.map +1 -1
- package/dist/main-DPijzQ1K.js.map +0 -1
|
@@ -9,7 +9,7 @@ import path from "node:path";
|
|
|
9
9
|
import { URL as URL$1 } from "node:url";
|
|
10
10
|
import envPaths from "env-paths";
|
|
11
11
|
import { l as logger, n as normalizeEnvValue, g as getLogLevelFromEnv, a as setLogLevel, L as LogLevel } from "./logger-CLtABTNb.js";
|
|
12
|
-
import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus,
|
|
12
|
+
import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-CUTutkx-.js";
|
|
13
13
|
import yargs from "yargs";
|
|
14
14
|
import { hideBin } from "yargs/helpers";
|
|
15
15
|
import yaml from "yaml";
|
|
@@ -28,9 +28,14 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
|
|
|
28
28
|
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
29
29
|
import { z as z$1 } from "zod/v3";
|
|
30
30
|
import { chromium } from "playwright";
|
|
31
|
+
import { lookup } from "node:dns/promises";
|
|
32
|
+
import fs$1 from "node:fs/promises";
|
|
33
|
+
import net from "node:net";
|
|
34
|
+
import os from "node:os";
|
|
35
|
+
import { minimatch } from "minimatch";
|
|
31
36
|
import mime from "mime";
|
|
32
37
|
import { HeaderGenerator } from "header-generator";
|
|
33
|
-
import
|
|
38
|
+
import https from "node:https";
|
|
34
39
|
import axios from "axios";
|
|
35
40
|
import { extractBytes } from "@kreuzberg/node";
|
|
36
41
|
import { VirtualConsole, JSDOM } from "jsdom";
|
|
@@ -63,13 +68,11 @@ import DOMPurify from "dompurify";
|
|
|
63
68
|
import { escapeHtml } from "@kitajs/html";
|
|
64
69
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
65
70
|
import { v4 } from "uuid";
|
|
66
|
-
import { minimatch } from "minimatch";
|
|
67
71
|
import { exec } from "node:child_process";
|
|
68
72
|
import { promisify } from "node:util";
|
|
69
73
|
import { Readable } from "node:stream";
|
|
70
74
|
import * as tar from "tar";
|
|
71
75
|
import yauzl from "yauzl";
|
|
72
|
-
import os from "node:os";
|
|
73
76
|
class StoreError extends Error {
|
|
74
77
|
constructor(message, cause) {
|
|
75
78
|
super(cause ? `${message} caused by ${cause}` : message);
|
|
@@ -80,6 +83,7 @@ class StoreError extends Error {
|
|
|
80
83
|
this.stack = causeError.stack;
|
|
81
84
|
}
|
|
82
85
|
}
|
|
86
|
+
cause;
|
|
83
87
|
}
|
|
84
88
|
class LibraryNotFoundInStoreError extends StoreError {
|
|
85
89
|
constructor(library, similarLibraries = []) {
|
|
@@ -91,6 +95,8 @@ class LibraryNotFoundInStoreError extends StoreError {
|
|
|
91
95
|
this.library = library;
|
|
92
96
|
this.similarLibraries = similarLibraries;
|
|
93
97
|
}
|
|
98
|
+
library;
|
|
99
|
+
similarLibraries;
|
|
94
100
|
}
|
|
95
101
|
class VersionNotFoundInStoreError extends StoreError {
|
|
96
102
|
constructor(library, version, availableVersions) {
|
|
@@ -104,6 +110,9 @@ class VersionNotFoundInStoreError extends StoreError {
|
|
|
104
110
|
this.version = version;
|
|
105
111
|
this.availableVersions = availableVersions;
|
|
106
112
|
}
|
|
113
|
+
library;
|
|
114
|
+
version;
|
|
115
|
+
availableVersions;
|
|
107
116
|
}
|
|
108
117
|
class DimensionError extends StoreError {
|
|
109
118
|
constructor(modelName, modelDimension, dbDimension) {
|
|
@@ -114,6 +123,9 @@ class DimensionError extends StoreError {
|
|
|
114
123
|
this.modelDimension = modelDimension;
|
|
115
124
|
this.dbDimension = dbDimension;
|
|
116
125
|
}
|
|
126
|
+
modelName;
|
|
127
|
+
modelDimension;
|
|
128
|
+
dbDimension;
|
|
117
129
|
}
|
|
118
130
|
class ConnectionError extends StoreError {
|
|
119
131
|
}
|
|
@@ -133,6 +145,10 @@ and follow the prompts.`
|
|
|
133
145
|
this.currentModel = currentModel;
|
|
134
146
|
this.currentDimension = currentDimension;
|
|
135
147
|
}
|
|
148
|
+
previousModel;
|
|
149
|
+
previousDimension;
|
|
150
|
+
currentModel;
|
|
151
|
+
currentDimension;
|
|
136
152
|
}
|
|
137
153
|
class MissingCredentialsError extends StoreError {
|
|
138
154
|
constructor(provider, missingCredentials) {
|
|
@@ -141,6 +157,7 @@ class MissingCredentialsError extends StoreError {
|
|
|
141
157
|
);
|
|
142
158
|
this.provider = provider;
|
|
143
159
|
}
|
|
160
|
+
provider;
|
|
144
161
|
}
|
|
145
162
|
class FixedDimensionEmbeddings extends Embeddings {
|
|
146
163
|
constructor(embeddings, targetDimension, providerAndModel, allowTruncate = false) {
|
|
@@ -152,6 +169,9 @@ class FixedDimensionEmbeddings extends Embeddings {
|
|
|
152
169
|
this.provider = modelName ? providerOrModel : "openai";
|
|
153
170
|
this.model = modelName || providerOrModel;
|
|
154
171
|
}
|
|
172
|
+
embeddings;
|
|
173
|
+
targetDimension;
|
|
174
|
+
allowTruncate;
|
|
155
175
|
provider;
|
|
156
176
|
model;
|
|
157
177
|
/**
|
|
@@ -336,6 +356,16 @@ function createEmbeddingModel(providerAndModel, runtime) {
|
|
|
336
356
|
throw new UnsupportedProviderError(provider);
|
|
337
357
|
}
|
|
338
358
|
}
|
|
359
|
+
const envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
|
|
360
|
+
if (Array.isArray(value)) {
|
|
361
|
+
return value;
|
|
362
|
+
}
|
|
363
|
+
const parsed = yaml.parse(value);
|
|
364
|
+
if (Array.isArray(parsed)) {
|
|
365
|
+
return parsed.map((item) => String(item));
|
|
366
|
+
}
|
|
367
|
+
return [value];
|
|
368
|
+
}).pipe(z.array(z.string()));
|
|
339
369
|
const envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
|
|
340
370
|
if (typeof val === "boolean") return val;
|
|
341
371
|
const lower = val.toLowerCase().trim();
|
|
@@ -370,6 +400,7 @@ const DEFAULT_CONFIG = {
|
|
|
370
400
|
maxConcurrency: 3,
|
|
371
401
|
abortOnFailureRate: 0.5,
|
|
372
402
|
preserveHashes: false,
|
|
403
|
+
skipKnownTrackers: true,
|
|
373
404
|
pageTimeoutMs: 5e3,
|
|
374
405
|
browserTimeoutMs: 3e4,
|
|
375
406
|
fetcher: {
|
|
@@ -381,6 +412,21 @@ const DEFAULT_CONFIG = {
|
|
|
381
412
|
document: {
|
|
382
413
|
maxSize: 10 * 1024 * 1024
|
|
383
414
|
// 10MB max size for PDF/Office documents
|
|
415
|
+
},
|
|
416
|
+
security: {
|
|
417
|
+
network: {
|
|
418
|
+
mode: "open",
|
|
419
|
+
allowPrivateNetworks: false,
|
|
420
|
+
allowedHosts: [],
|
|
421
|
+
allowedCidrs: [],
|
|
422
|
+
allowInvalidTls: false
|
|
423
|
+
},
|
|
424
|
+
fileAccess: {
|
|
425
|
+
mode: "allowedRoots",
|
|
426
|
+
allowedRoots: ["$DOCUMENTS"],
|
|
427
|
+
followSymlinks: false,
|
|
428
|
+
includeHidden: false
|
|
429
|
+
}
|
|
384
430
|
}
|
|
385
431
|
},
|
|
386
432
|
splitter: {
|
|
@@ -450,6 +496,7 @@ const AppConfigSchema = z.object({
|
|
|
450
496
|
maxConcurrency: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxConcurrency),
|
|
451
497
|
abortOnFailureRate: z.coerce.number().min(0).max(1).default(DEFAULT_CONFIG.scraper.abortOnFailureRate),
|
|
452
498
|
preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),
|
|
499
|
+
skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
|
|
453
500
|
pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
|
|
454
501
|
browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
|
|
455
502
|
fetcher: z.object({
|
|
@@ -460,7 +507,36 @@ const AppConfigSchema = z.object({
|
|
|
460
507
|
}).default(DEFAULT_CONFIG.scraper.fetcher),
|
|
461
508
|
document: z.object({
|
|
462
509
|
maxSize: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.document.maxSize)
|
|
463
|
-
}).default(DEFAULT_CONFIG.scraper.document)
|
|
510
|
+
}).default(DEFAULT_CONFIG.scraper.document),
|
|
511
|
+
security: z.object({
|
|
512
|
+
network: z.object({
|
|
513
|
+
mode: z.enum(["open", "allowlist"]).default(DEFAULT_CONFIG.scraper.security.network.mode),
|
|
514
|
+
allowPrivateNetworks: envBoolean.default(
|
|
515
|
+
DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks
|
|
516
|
+
),
|
|
517
|
+
allowedHosts: envStringArray.default(
|
|
518
|
+
DEFAULT_CONFIG.scraper.security.network.allowedHosts
|
|
519
|
+
),
|
|
520
|
+
allowedCidrs: envStringArray.default(
|
|
521
|
+
DEFAULT_CONFIG.scraper.security.network.allowedCidrs
|
|
522
|
+
),
|
|
523
|
+
allowInvalidTls: envBoolean.default(
|
|
524
|
+
DEFAULT_CONFIG.scraper.security.network.allowInvalidTls
|
|
525
|
+
)
|
|
526
|
+
}).default(DEFAULT_CONFIG.scraper.security.network),
|
|
527
|
+
fileAccess: z.object({
|
|
528
|
+
mode: z.enum(["disabled", "allowedRoots", "unrestricted"]).default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),
|
|
529
|
+
allowedRoots: envStringArray.default(
|
|
530
|
+
DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots
|
|
531
|
+
),
|
|
532
|
+
followSymlinks: envBoolean.default(
|
|
533
|
+
DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks
|
|
534
|
+
),
|
|
535
|
+
includeHidden: envBoolean.default(
|
|
536
|
+
DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden
|
|
537
|
+
)
|
|
538
|
+
}).default(DEFAULT_CONFIG.scraper.security.fileAccess)
|
|
539
|
+
}).default(DEFAULT_CONFIG.scraper.security)
|
|
464
540
|
}).default(DEFAULT_CONFIG.scraper),
|
|
465
541
|
splitter: z.object({
|
|
466
542
|
minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),
|
|
@@ -578,7 +654,43 @@ function loadConfig(cliArgs = {}, options = {}) {
|
|
|
578
654
|
if (!getAtPath(mergedInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
|
|
579
655
|
setAtPath(mergedInput, ["app", "embeddingModel"], "text-embedding-3-small");
|
|
580
656
|
}
|
|
581
|
-
|
|
657
|
+
const parseResult = AppConfigSchema.safeParse(mergedInput);
|
|
658
|
+
if (parseResult.success) {
|
|
659
|
+
return parseResult.data;
|
|
660
|
+
}
|
|
661
|
+
if (!isReadOnlyConfig && fs.existsSync(configPath)) {
|
|
662
|
+
const quarantinePath = `${configPath}.invalid-${Date.now()}`;
|
|
663
|
+
try {
|
|
664
|
+
fs.renameSync(configPath, quarantinePath);
|
|
665
|
+
logger.warn(
|
|
666
|
+
`Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`
|
|
667
|
+
);
|
|
668
|
+
} catch (renameError) {
|
|
669
|
+
logger.warn(
|
|
670
|
+
`Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
} else {
|
|
674
|
+
logger.warn(
|
|
675
|
+
`Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
const fallbackInput = deepMerge(
|
|
679
|
+
defaults,
|
|
680
|
+
deepMerge(envConfig, cliConfig)
|
|
681
|
+
);
|
|
682
|
+
if (!getAtPath(fallbackInput, ["app", "embeddingModel"]) && process.env.OPENAI_API_KEY) {
|
|
683
|
+
setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
|
|
684
|
+
}
|
|
685
|
+
const fallback = AppConfigSchema.parse(fallbackInput);
|
|
686
|
+
if (!isReadOnlyConfig) {
|
|
687
|
+
try {
|
|
688
|
+
saveConfigFile(configPath, fallback);
|
|
689
|
+
} catch (error) {
|
|
690
|
+
logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
return fallback;
|
|
582
694
|
}
|
|
583
695
|
function loadConfigFile(filePath) {
|
|
584
696
|
if (!fs.existsSync(filePath)) return null;
|
|
@@ -681,13 +793,14 @@ function getAtPath(obj, pathArr) {
|
|
|
681
793
|
function deepMerge(target, source) {
|
|
682
794
|
if (typeof target !== "object" || target === null) return source;
|
|
683
795
|
if (typeof source !== "object" || source === null) return target;
|
|
796
|
+
if (Array.isArray(target) || Array.isArray(source)) return source;
|
|
684
797
|
const t2 = target;
|
|
685
798
|
const s = source;
|
|
686
799
|
const output = { ...t2 };
|
|
687
800
|
for (const key of Object.keys(s)) {
|
|
688
801
|
const sValue = s[key];
|
|
689
802
|
const tValue = t2[key];
|
|
690
|
-
if (typeof sValue === "object" && sValue !== null && typeof tValue === "object" && tValue !== null && key in t2) {
|
|
803
|
+
if (typeof sValue === "object" && sValue !== null && !Array.isArray(sValue) && typeof tValue === "object" && tValue !== null && !Array.isArray(tValue) && key in t2) {
|
|
691
804
|
output[key] = deepMerge(tValue, sValue);
|
|
692
805
|
} else {
|
|
693
806
|
output[key] = sValue;
|
|
@@ -965,6 +1078,7 @@ class ProxyAuthManager {
|
|
|
965
1078
|
constructor(config) {
|
|
966
1079
|
this.config = config;
|
|
967
1080
|
}
|
|
1081
|
+
config;
|
|
968
1082
|
proxyProvider = null;
|
|
969
1083
|
discoveredEndpoints = null;
|
|
970
1084
|
jwks = null;
|
|
@@ -1365,6 +1479,8 @@ class RemoteEventProxy {
|
|
|
1365
1479
|
this.remoteWorkerUrl = remoteWorkerUrl;
|
|
1366
1480
|
this.localEventBus = localEventBus;
|
|
1367
1481
|
}
|
|
1482
|
+
remoteWorkerUrl;
|
|
1483
|
+
localEventBus;
|
|
1368
1484
|
trpcClient = null;
|
|
1369
1485
|
wsClient = null;
|
|
1370
1486
|
subscription = null;
|
|
@@ -1461,6 +1577,7 @@ class ToolError extends Error {
|
|
|
1461
1577
|
this.toolName = toolName;
|
|
1462
1578
|
this.name = this.constructor.name;
|
|
1463
1579
|
}
|
|
1580
|
+
toolName;
|
|
1464
1581
|
}
|
|
1465
1582
|
class ValidationError extends ToolError {
|
|
1466
1583
|
}
|
|
@@ -2012,6 +2129,8 @@ class ScraperError extends Error {
|
|
|
2012
2129
|
Caused by: ${cause.stack}`;
|
|
2013
2130
|
}
|
|
2014
2131
|
}
|
|
2132
|
+
isRetryable;
|
|
2133
|
+
cause;
|
|
2015
2134
|
}
|
|
2016
2135
|
class InvalidUrlError extends ScraperError {
|
|
2017
2136
|
constructor(url, cause) {
|
|
@@ -2028,6 +2147,9 @@ class RedirectError extends ScraperError {
|
|
|
2028
2147
|
this.redirectUrl = redirectUrl;
|
|
2029
2148
|
this.statusCode = statusCode;
|
|
2030
2149
|
}
|
|
2150
|
+
originalUrl;
|
|
2151
|
+
redirectUrl;
|
|
2152
|
+
statusCode;
|
|
2031
2153
|
}
|
|
2032
2154
|
class ChallengeError extends ScraperError {
|
|
2033
2155
|
constructor(url, statusCode, challengeType) {
|
|
@@ -2039,6 +2161,9 @@ class ChallengeError extends ScraperError {
|
|
|
2039
2161
|
this.statusCode = statusCode;
|
|
2040
2162
|
this.challengeType = challengeType;
|
|
2041
2163
|
}
|
|
2164
|
+
url;
|
|
2165
|
+
statusCode;
|
|
2166
|
+
challengeType;
|
|
2042
2167
|
}
|
|
2043
2168
|
class TlsCertificateError extends ScraperError {
|
|
2044
2169
|
constructor(url, code, cause) {
|
|
@@ -2050,6 +2175,499 @@ class TlsCertificateError extends ScraperError {
|
|
|
2050
2175
|
this.url = url;
|
|
2051
2176
|
this.code = code;
|
|
2052
2177
|
}
|
|
2178
|
+
url;
|
|
2179
|
+
code;
|
|
2180
|
+
}
|
|
2181
|
+
class AccessPolicyError extends ScraperError {
|
|
2182
|
+
constructor(message) {
|
|
2183
|
+
super(message, false);
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
const DEFAULT_FILE_EXCLUSIONS = [
|
|
2187
|
+
// CHANGELOG files (case variations)
|
|
2188
|
+
"**/CHANGELOG.md",
|
|
2189
|
+
"**/changelog.md",
|
|
2190
|
+
"**/CHANGELOG.mdx",
|
|
2191
|
+
"**/changelog.mdx",
|
|
2192
|
+
// LICENSE files (case variations)
|
|
2193
|
+
"**/LICENSE",
|
|
2194
|
+
"**/LICENSE.md",
|
|
2195
|
+
"**/license.md",
|
|
2196
|
+
// CODE_OF_CONDUCT files (case variations)
|
|
2197
|
+
"**/CODE_OF_CONDUCT.md",
|
|
2198
|
+
"**/code_of_conduct.md",
|
|
2199
|
+
// Test files
|
|
2200
|
+
"**/*.test.*",
|
|
2201
|
+
"**/*.spec.*",
|
|
2202
|
+
"**/*_test.py",
|
|
2203
|
+
"**/*_test.go",
|
|
2204
|
+
// Package manager lock files
|
|
2205
|
+
"**/*.lock",
|
|
2206
|
+
"**/package-lock.json",
|
|
2207
|
+
"**/yarn.lock",
|
|
2208
|
+
"**/pnpm-lock.yaml",
|
|
2209
|
+
"**/go.sum",
|
|
2210
|
+
// Build artifacts
|
|
2211
|
+
"**/*.min.js",
|
|
2212
|
+
"**/*.min.css",
|
|
2213
|
+
"**/*.map",
|
|
2214
|
+
"**/*.d.ts",
|
|
2215
|
+
// IDE/System files
|
|
2216
|
+
"**/.DS_Store",
|
|
2217
|
+
"**/Thumbs.db",
|
|
2218
|
+
"**/*.swp",
|
|
2219
|
+
"**/*.swo",
|
|
2220
|
+
// Internal config files (using regex pattern)
|
|
2221
|
+
"/.*\\.(ini|cfg|conf|log|pid)$/"
|
|
2222
|
+
];
|
|
2223
|
+
const DEFAULT_FOLDER_EXCLUSIONS = [
|
|
2224
|
+
// Archive and deprecated content (matches anywhere in path)
|
|
2225
|
+
"**/archive/**",
|
|
2226
|
+
"**/archived/**",
|
|
2227
|
+
"**/deprecated/**",
|
|
2228
|
+
"**/legacy/**",
|
|
2229
|
+
"**/old/**",
|
|
2230
|
+
"**/outdated/**",
|
|
2231
|
+
"**/previous/**",
|
|
2232
|
+
"**/superseded/**",
|
|
2233
|
+
// Specific paths that don't follow the general pattern
|
|
2234
|
+
"docs/old/**",
|
|
2235
|
+
// Test directories
|
|
2236
|
+
"**/test/**",
|
|
2237
|
+
"**/tests/**",
|
|
2238
|
+
"**/__tests__/**",
|
|
2239
|
+
"**/spec/**",
|
|
2240
|
+
// Build output directories
|
|
2241
|
+
"**/dist/**",
|
|
2242
|
+
"**/build/**",
|
|
2243
|
+
"**/out/**",
|
|
2244
|
+
"**/target/**",
|
|
2245
|
+
"**/.next/**",
|
|
2246
|
+
"**/.nuxt/**",
|
|
2247
|
+
// IDE directories
|
|
2248
|
+
"**/.vscode/**",
|
|
2249
|
+
"**/.idea/**",
|
|
2250
|
+
// Internationalization folders - non-English locales
|
|
2251
|
+
"**/i18n/ar*/**",
|
|
2252
|
+
"**/i18n/de*/**",
|
|
2253
|
+
"**/i18n/es*/**",
|
|
2254
|
+
"**/i18n/fr*/**",
|
|
2255
|
+
"**/i18n/hi*/**",
|
|
2256
|
+
"**/i18n/it*/**",
|
|
2257
|
+
"**/i18n/ja*/**",
|
|
2258
|
+
"**/i18n/ko*/**",
|
|
2259
|
+
"**/i18n/nl*/**",
|
|
2260
|
+
"**/i18n/pl*/**",
|
|
2261
|
+
"**/i18n/pt*/**",
|
|
2262
|
+
"**/i18n/ru*/**",
|
|
2263
|
+
"**/i18n/sv*/**",
|
|
2264
|
+
"**/i18n/th*/**",
|
|
2265
|
+
"**/i18n/tr*/**",
|
|
2266
|
+
"**/i18n/vi*/**",
|
|
2267
|
+
"**/i18n/zh*/**",
|
|
2268
|
+
// Common locale folder patterns
|
|
2269
|
+
"**/zh-cn/**",
|
|
2270
|
+
"**/zh-hk/**",
|
|
2271
|
+
"**/zh-mo/**",
|
|
2272
|
+
"**/zh-sg/**",
|
|
2273
|
+
"**/zh-tw/**"
|
|
2274
|
+
];
|
|
2275
|
+
const DEFAULT_EXCLUSION_PATTERNS = [
|
|
2276
|
+
...DEFAULT_FILE_EXCLUSIONS,
|
|
2277
|
+
...DEFAULT_FOLDER_EXCLUSIONS
|
|
2278
|
+
];
|
|
2279
|
+
function getEffectiveExclusionPatterns(userPatterns) {
|
|
2280
|
+
if (userPatterns !== void 0) {
|
|
2281
|
+
return userPatterns;
|
|
2282
|
+
}
|
|
2283
|
+
return DEFAULT_EXCLUSION_PATTERNS;
|
|
2284
|
+
}
|
|
2285
|
+
function isRegexPattern(pattern) {
|
|
2286
|
+
return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
|
|
2287
|
+
}
|
|
2288
|
+
function patternToRegExp(pattern) {
|
|
2289
|
+
if (isRegexPattern(pattern)) {
|
|
2290
|
+
return new RegExp(pattern.slice(1, -1));
|
|
2291
|
+
}
|
|
2292
|
+
const re = minimatch.makeRe(pattern, { dot: true });
|
|
2293
|
+
if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
|
|
2294
|
+
return re;
|
|
2295
|
+
}
|
|
2296
|
+
const URL_WITH_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
2297
|
+
function matchesAnyPattern(path2, patterns) {
|
|
2298
|
+
if (!patterns || patterns.length === 0) return false;
|
|
2299
|
+
const isFullUrl = URL_WITH_PROTOCOL_RE.test(path2);
|
|
2300
|
+
const normalizedPath = isFullUrl || path2.startsWith("/") ? path2 : `/${path2}`;
|
|
2301
|
+
return patterns.some((pattern) => {
|
|
2302
|
+
if (isRegexPattern(pattern)) {
|
|
2303
|
+
return patternToRegExp(pattern).test(normalizedPath);
|
|
2304
|
+
}
|
|
2305
|
+
const pathForMatch = normalizedPath.replace(/^\//, "");
|
|
2306
|
+
const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
|
|
2307
|
+
return minimatch(pathForMatch, patternForMatch, { dot: true });
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
function matchesAnyHostPattern(value, patterns) {
|
|
2311
|
+
if (!patterns || patterns.length === 0) return false;
|
|
2312
|
+
const normalized = value.toLowerCase();
|
|
2313
|
+
return patterns.some((pattern) => {
|
|
2314
|
+
if (isRegexPattern(pattern)) {
|
|
2315
|
+
return patternToRegExp(pattern).test(value);
|
|
2316
|
+
}
|
|
2317
|
+
return minimatch(normalized, pattern.toLowerCase(), { dot: true });
|
|
2318
|
+
});
|
|
2319
|
+
}
|
|
2320
|
+
function extractPathAndQuery(url) {
|
|
2321
|
+
try {
|
|
2322
|
+
const u = new URL(url);
|
|
2323
|
+
return u.pathname + (u.search || "");
|
|
2324
|
+
} catch {
|
|
2325
|
+
return url;
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
function shouldIncludeUrl(url, includePatterns, excludePatterns) {
|
|
2329
|
+
const path2 = extractPathAndQuery(url);
|
|
2330
|
+
const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
|
|
2331
|
+
let basename;
|
|
2332
|
+
if (url.startsWith("file://")) {
|
|
2333
|
+
try {
|
|
2334
|
+
const u = new URL(url);
|
|
2335
|
+
basename = u.pathname ? u.pathname.split("/").pop() : void 0;
|
|
2336
|
+
} catch {
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
|
|
2340
|
+
const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
|
|
2341
|
+
if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
|
|
2342
|
+
return false;
|
|
2343
|
+
if (!includePatterns || includePatterns.length === 0) return true;
|
|
2344
|
+
return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
|
|
2345
|
+
}
|
|
2346
|
+
const SPECIAL_USE_IPV4_CIDRS = [
|
|
2347
|
+
"0.0.0.0/8",
|
|
2348
|
+
"10.0.0.0/8",
|
|
2349
|
+
"100.64.0.0/10",
|
|
2350
|
+
"127.0.0.0/8",
|
|
2351
|
+
"169.254.0.0/16",
|
|
2352
|
+
"172.16.0.0/12",
|
|
2353
|
+
"192.0.0.0/24",
|
|
2354
|
+
"192.0.2.0/24",
|
|
2355
|
+
"192.168.0.0/16",
|
|
2356
|
+
"198.18.0.0/15",
|
|
2357
|
+
"198.51.100.0/24",
|
|
2358
|
+
"203.0.113.0/24",
|
|
2359
|
+
"224.0.0.0/4",
|
|
2360
|
+
"240.0.0.0/4"
|
|
2361
|
+
];
|
|
2362
|
+
const SPECIAL_USE_IPV6_CIDRS = ["::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8"];
|
|
2363
|
+
const ARCHIVE_EXTENSIONS = /* @__PURE__ */ new Set([".zip", ".tar", ".gz", ".tgz"]);
|
|
2364
|
+
class ScraperAccessPolicy {
|
|
2365
|
+
constructor(security) {
|
|
2366
|
+
this.security = security;
|
|
2367
|
+
this.allowedHosts = security.network.allowedHosts;
|
|
2368
|
+
for (const cidr of security.network.allowedCidrs) {
|
|
2369
|
+
this.addCidr(this.allowedCidrs, cidr);
|
|
2370
|
+
}
|
|
2371
|
+
for (const cidr of SPECIAL_USE_IPV4_CIDRS) {
|
|
2372
|
+
this.addCidr(this.specialUseCidrs, cidr);
|
|
2373
|
+
}
|
|
2374
|
+
for (const cidr of SPECIAL_USE_IPV6_CIDRS) {
|
|
2375
|
+
this.addCidr(this.specialUseCidrs, cidr);
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
security;
|
|
2379
|
+
allowedCidrs = new net.BlockList();
|
|
2380
|
+
specialUseCidrs = new net.BlockList();
|
|
2381
|
+
allowedHosts;
|
|
2382
|
+
/**
|
|
2383
|
+
* Checks whether a network URL is allowed before connecting.
|
|
2384
|
+
*/
|
|
2385
|
+
async assertNetworkUrlAllowed(url) {
|
|
2386
|
+
const parsed = new URL(url);
|
|
2387
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
2388
|
+
return;
|
|
2389
|
+
}
|
|
2390
|
+
const hostname = normalizeHostname(parsed.hostname);
|
|
2391
|
+
const ipFamily = net.isIP(hostname);
|
|
2392
|
+
if (this.security.network.mode === "allowlist") {
|
|
2393
|
+
if (ipFamily !== 0) {
|
|
2394
|
+
const family = ipFamily === 6 ? "ipv6" : "ipv4";
|
|
2395
|
+
if (this.allowedCidrs.check(hostname, family)) return;
|
|
2396
|
+
throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
|
|
2397
|
+
}
|
|
2398
|
+
if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
|
|
2399
|
+
return;
|
|
2400
|
+
}
|
|
2401
|
+
const addresses2 = await resolveAddresses(hostname);
|
|
2402
|
+
const allAllowedByCidr = addresses2.length > 0 && addresses2.every((address) => {
|
|
2403
|
+
const family = net.isIP(address.address);
|
|
2404
|
+
if (family === 0) return false;
|
|
2405
|
+
return this.allowedCidrs.check(address.address, family === 6 ? "ipv6" : "ipv4");
|
|
2406
|
+
});
|
|
2407
|
+
if (allAllowedByCidr) return;
|
|
2408
|
+
throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
|
|
2409
|
+
}
|
|
2410
|
+
if (this.security.network.allowPrivateNetworks) {
|
|
2411
|
+
return;
|
|
2412
|
+
}
|
|
2413
|
+
if (ipFamily !== 0) {
|
|
2414
|
+
this.assertSpecialUseAddressAllowed(hostname, url);
|
|
2415
|
+
return;
|
|
2416
|
+
}
|
|
2417
|
+
if (looksLikeIpLiteral(hostname)) {
|
|
2418
|
+
throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
|
|
2419
|
+
}
|
|
2420
|
+
if (matchesAnyHostPattern(hostname, this.allowedHosts)) {
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
const addresses = await resolveAddresses(hostname);
|
|
2424
|
+
for (const address of addresses) {
|
|
2425
|
+
this.assertSpecialUseAddressAllowed(address.address, url);
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* Checks whether TLS certificate validation may be bypassed for a URL.
|
|
2430
|
+
*/
|
|
2431
|
+
shouldAllowInvalidTls(url) {
|
|
2432
|
+
try {
|
|
2433
|
+
const parsed = new URL(url);
|
|
2434
|
+
return parsed.protocol === "https:" && this.security.network.allowInvalidTls;
|
|
2435
|
+
} catch {
|
|
2436
|
+
return false;
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Resolves and validates a file URL against the configured file access policy.
|
|
2441
|
+
*/
|
|
2442
|
+
async resolveFileAccess(url, additionalAllowedRoots = []) {
|
|
2443
|
+
const filePath = fileUrlToPathLoose(url);
|
|
2444
|
+
const resolved = await resolveArchiveAwarePath(filePath);
|
|
2445
|
+
const accessPath = resolved.archivePath ?? filePath;
|
|
2446
|
+
const bypassRoots = await this.expandRoots(additionalAllowedRoots);
|
|
2447
|
+
const matchedBypassRoot = await this.findContainingRoot(
|
|
2448
|
+
accessPath,
|
|
2449
|
+
bypassRoots,
|
|
2450
|
+
false
|
|
2451
|
+
);
|
|
2452
|
+
let matchedRoot = matchedBypassRoot;
|
|
2453
|
+
if (this.security.fileAccess.mode === "disabled" && !matchedBypassRoot) {
|
|
2454
|
+
throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
|
|
2455
|
+
}
|
|
2456
|
+
if (this.security.fileAccess.mode === "allowedRoots" && !matchedBypassRoot) {
|
|
2457
|
+
const configuredRoots = await this.expandRoots(
|
|
2458
|
+
this.security.fileAccess.allowedRoots
|
|
2459
|
+
);
|
|
2460
|
+
if (configuredRoots.length === 0) {
|
|
2461
|
+
throw new AccessPolicyError(
|
|
2462
|
+
`Security policy blocked local file access for ${url}`
|
|
2463
|
+
);
|
|
2464
|
+
}
|
|
2465
|
+
matchedRoot = await this.findContainingRoot(
|
|
2466
|
+
accessPath,
|
|
2467
|
+
configuredRoots,
|
|
2468
|
+
this.security.fileAccess.followSymlinks
|
|
2469
|
+
);
|
|
2470
|
+
if (!matchedRoot) {
|
|
2471
|
+
throw new AccessPolicyError(
|
|
2472
|
+
`Security policy blocked local file access for ${url}`
|
|
2473
|
+
);
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
if (!this.security.fileAccess.followSymlinks && !matchedBypassRoot) {
|
|
2477
|
+
const symlinkPath = await findSymlinkInPath(accessPath);
|
|
2478
|
+
if (symlinkPath) {
|
|
2479
|
+
throw new AccessPolicyError(`Security policy blocked symlink access for ${url}`);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
if (!this.security.fileAccess.includeHidden) {
|
|
2483
|
+
if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) {
|
|
2484
|
+
throw new AccessPolicyError(
|
|
2485
|
+
`Security policy blocked hidden file access for ${url}`
|
|
2486
|
+
);
|
|
2487
|
+
}
|
|
2488
|
+
if (resolved.virtualArchivePath && hasHiddenArchiveSegment(resolved.virtualArchivePath)) {
|
|
2489
|
+
throw new AccessPolicyError(
|
|
2490
|
+
`Security policy blocked hidden archive entry access for ${url}`
|
|
2491
|
+
);
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
return {
|
|
2495
|
+
filePath,
|
|
2496
|
+
accessPath,
|
|
2497
|
+
virtualArchivePath: resolved.virtualArchivePath
|
|
2498
|
+
};
|
|
2499
|
+
}
|
|
2500
|
+
/**
|
|
2501
|
+
* Throws if `address` falls inside a blocked special-use range and is not
|
|
2502
|
+
* explicitly permitted by `allowedCidrs`. Used both for direct-IP targets
|
|
2503
|
+
* and for revalidating DNS-resolved addresses (open mode) and allowlisted
|
|
2504
|
+
* hostnames (allowlist mode, to close DNS-rebinding gaps).
|
|
2505
|
+
*/
|
|
2506
|
+
assertSpecialUseAddressAllowed(address, url) {
|
|
2507
|
+
const family = net.isIP(address);
|
|
2508
|
+
if (family === 0) {
|
|
2509
|
+
return;
|
|
2510
|
+
}
|
|
2511
|
+
const type = family === 6 ? "ipv6" : "ipv4";
|
|
2512
|
+
if (!this.specialUseCidrs.check(address, type)) {
|
|
2513
|
+
return;
|
|
2514
|
+
}
|
|
2515
|
+
if (this.allowedCidrs.check(address, type)) {
|
|
2516
|
+
return;
|
|
2517
|
+
}
|
|
2518
|
+
throw new AccessPolicyError(`Security policy blocked network access to ${url}`);
|
|
2519
|
+
}
|
|
2520
|
+
addCidr(blockList, cidr) {
|
|
2521
|
+
const [network, prefix] = cidr.split("/");
|
|
2522
|
+
const family = net.isIP(network);
|
|
2523
|
+
if (family === 0 || prefix === void 0) {
|
|
2524
|
+
return;
|
|
2525
|
+
}
|
|
2526
|
+
blockList.addSubnet(
|
|
2527
|
+
network,
|
|
2528
|
+
Number.parseInt(prefix, 10),
|
|
2529
|
+
family === 6 ? "ipv6" : "ipv4"
|
|
2530
|
+
);
|
|
2531
|
+
}
|
|
2532
|
+
async expandRoots(roots) {
|
|
2533
|
+
const expanded = [];
|
|
2534
|
+
for (const root of roots) {
|
|
2535
|
+
const value = await expandConfiguredRoot(root);
|
|
2536
|
+
if (value) {
|
|
2537
|
+
expanded.push(value);
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
return expanded;
|
|
2541
|
+
}
|
|
2542
|
+
async findContainingRoot(accessPath, roots, followSymlinks) {
|
|
2543
|
+
const resolvedAccessPath = await resolveContainmentPath(accessPath, followSymlinks);
|
|
2544
|
+
for (const root of roots) {
|
|
2545
|
+
const resolvedRoot = await resolveContainmentPath(root, followSymlinks);
|
|
2546
|
+
if (pathContains(resolvedRoot, resolvedAccessPath)) {
|
|
2547
|
+
return resolvedRoot;
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
return null;
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
async function resolveAddresses(hostname) {
|
|
2554
|
+
try {
|
|
2555
|
+
const result = await lookup(hostname, { all: true, verbatim: true });
|
|
2556
|
+
return Array.isArray(result) ? result : [];
|
|
2557
|
+
} catch {
|
|
2558
|
+
return [];
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
function normalizeHostname(hostname) {
|
|
2562
|
+
return hostname.toLowerCase().replace(/^\[(.*)]$/, "$1");
|
|
2563
|
+
}
|
|
2564
|
+
function looksLikeIpLiteral(hostname) {
|
|
2565
|
+
return hostname.includes(":") || /^\d+(?:\.\d+){0,3}$/.test(hostname);
|
|
2566
|
+
}
|
|
2567
|
+
async function findSymlinkInPath(targetPath) {
|
|
2568
|
+
const resolved = path.resolve(targetPath);
|
|
2569
|
+
const root = path.parse(resolved).root;
|
|
2570
|
+
const relative = path.relative(root, resolved);
|
|
2571
|
+
const segments = relative.split(path.sep).filter(Boolean);
|
|
2572
|
+
let current = root;
|
|
2573
|
+
for (const segment of segments) {
|
|
2574
|
+
current = path.join(current, segment);
|
|
2575
|
+
const stats = await fs$1.lstat(current).catch(() => null);
|
|
2576
|
+
if (stats?.isSymbolicLink()) {
|
|
2577
|
+
return current;
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
return null;
|
|
2581
|
+
}
|
|
2582
|
+
function fileUrlToPathLoose(url) {
|
|
2583
|
+
let filePath = url.replace(/^file:\/\/\/?/, "");
|
|
2584
|
+
filePath = decodeURIComponent(filePath);
|
|
2585
|
+
if (!filePath.startsWith("/") && process.platform !== "win32") {
|
|
2586
|
+
filePath = `/${filePath}`;
|
|
2587
|
+
}
|
|
2588
|
+
return filePath;
|
|
2589
|
+
}
|
|
2590
|
+
const USER_DIR_TOKENS = {
|
|
2591
|
+
$DOCUMENTS: "Documents",
|
|
2592
|
+
$DOWNLOADS: "Downloads",
|
|
2593
|
+
$DESKTOP: "Desktop"
|
|
2594
|
+
};
|
|
2595
|
+
async function expandConfiguredRoot(root) {
|
|
2596
|
+
if (root === "$HOME") {
|
|
2597
|
+
const homeDir = os.homedir();
|
|
2598
|
+
return homeDir ? path.resolve(homeDir) : null;
|
|
2599
|
+
}
|
|
2600
|
+
if (root === "$CWD") {
|
|
2601
|
+
return path.resolve(process.cwd());
|
|
2602
|
+
}
|
|
2603
|
+
const subdir = USER_DIR_TOKENS[root];
|
|
2604
|
+
if (subdir !== void 0) {
|
|
2605
|
+
const homeDir = os.homedir();
|
|
2606
|
+
if (!homeDir) {
|
|
2607
|
+
return null;
|
|
2608
|
+
}
|
|
2609
|
+
const candidate = path.join(homeDir, subdir);
|
|
2610
|
+
const stats = await fs$1.stat(candidate).catch(() => null);
|
|
2611
|
+
if (!stats?.isDirectory()) {
|
|
2612
|
+
return null;
|
|
2613
|
+
}
|
|
2614
|
+
return path.resolve(candidate);
|
|
2615
|
+
}
|
|
2616
|
+
return path.resolve(root);
|
|
2617
|
+
}
|
|
2618
|
+
async function resolveArchiveAwarePath(filePath) {
|
|
2619
|
+
let currentPath = filePath;
|
|
2620
|
+
while (currentPath !== "/" && currentPath !== "." && path.dirname(currentPath) !== currentPath) {
|
|
2621
|
+
const stats = await fs$1.lstat(currentPath).catch(() => null);
|
|
2622
|
+
if (stats?.isFile() && looksLikeArchivePath(currentPath)) {
|
|
2623
|
+
const virtualArchivePath = filePath.substring(currentPath.length).replace(/^\/+/, "").replace(/^\\+/, "");
|
|
2624
|
+
return {
|
|
2625
|
+
archivePath: currentPath,
|
|
2626
|
+
virtualArchivePath: virtualArchivePath || null
|
|
2627
|
+
};
|
|
2628
|
+
}
|
|
2629
|
+
if (stats) {
|
|
2630
|
+
return { archivePath: null, virtualArchivePath: null };
|
|
2631
|
+
}
|
|
2632
|
+
currentPath = path.dirname(currentPath);
|
|
2633
|
+
}
|
|
2634
|
+
return { archivePath: null, virtualArchivePath: null };
|
|
2635
|
+
}
|
|
2636
|
+
async function resolveContainmentPath(targetPath, followSymlinks) {
|
|
2637
|
+
if (!followSymlinks) {
|
|
2638
|
+
return path.resolve(targetPath);
|
|
2639
|
+
}
|
|
2640
|
+
return fs$1.realpath(targetPath).catch(() => path.resolve(targetPath));
|
|
2641
|
+
}
|
|
2642
|
+
function looksLikeArchivePath(filePath) {
|
|
2643
|
+
return ARCHIVE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
2644
|
+
}
|
|
2645
|
+
function pathContains(root, candidate) {
|
|
2646
|
+
if (root === candidate) {
|
|
2647
|
+
return true;
|
|
2648
|
+
}
|
|
2649
|
+
const relative = path.relative(root, candidate);
|
|
2650
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
2651
|
+
}
|
|
2652
|
+
function hasHiddenSegmentBelowRoot(targetPath, matchedRoot) {
|
|
2653
|
+
const resolved = path.resolve(targetPath);
|
|
2654
|
+
let segments;
|
|
2655
|
+
if (matchedRoot) {
|
|
2656
|
+
const resolvedRoot = path.resolve(matchedRoot);
|
|
2657
|
+
if (resolved === resolvedRoot) return false;
|
|
2658
|
+
const relative = path.relative(resolvedRoot, resolved);
|
|
2659
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
2660
|
+
segments = resolved.split(path.sep).filter(Boolean);
|
|
2661
|
+
} else {
|
|
2662
|
+
segments = relative.split(path.sep).filter(Boolean);
|
|
2663
|
+
}
|
|
2664
|
+
} else {
|
|
2665
|
+
segments = resolved.split(path.sep).filter(Boolean);
|
|
2666
|
+
}
|
|
2667
|
+
return segments.some((segment) => segment.startsWith("."));
|
|
2668
|
+
}
|
|
2669
|
+
function hasHiddenArchiveSegment(archivePath) {
|
|
2670
|
+
return archivePath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
|
|
2053
2671
|
}
|
|
2054
2672
|
class MimeTypeUtils {
|
|
2055
2673
|
/**
|
|
@@ -2560,28 +3178,53 @@ var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
|
|
|
2560
3178
|
})(FetchStatus || {});
|
|
2561
3179
|
class BrowserFetcher {
|
|
2562
3180
|
browser = null;
|
|
2563
|
-
page = null;
|
|
2564
3181
|
fingerprintGenerator;
|
|
2565
3182
|
defaultTimeoutMs;
|
|
3183
|
+
accessPolicy;
|
|
2566
3184
|
constructor(scraperConfig) {
|
|
2567
3185
|
this.defaultTimeoutMs = scraperConfig.browserTimeoutMs;
|
|
2568
3186
|
this.fingerprintGenerator = new FingerprintGenerator();
|
|
3187
|
+
this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
|
|
2569
3188
|
}
|
|
2570
3189
|
canFetch(source) {
|
|
2571
3190
|
return source.startsWith("http://") || source.startsWith("https://");
|
|
2572
3191
|
}
|
|
3192
|
+
async isRequestAllowed(url) {
|
|
3193
|
+
try {
|
|
3194
|
+
await this.accessPolicy.assertNetworkUrlAllowed(url);
|
|
3195
|
+
return true;
|
|
3196
|
+
} catch {
|
|
3197
|
+
return false;
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
2573
3200
|
async fetch(source, options) {
|
|
3201
|
+
let page = null;
|
|
3202
|
+
let browserContext = null;
|
|
2574
3203
|
try {
|
|
2575
|
-
await this.
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
3204
|
+
await this.accessPolicy.assertNetworkUrlAllowed(source);
|
|
3205
|
+
const browser = await this.ensureBrowserReady();
|
|
3206
|
+
const fingerprintHeaders = this.fingerprintGenerator.generateHeaders();
|
|
3207
|
+
browserContext = await browser.newContext({
|
|
3208
|
+
ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
|
|
3209
|
+
"https://browser-context.local"
|
|
3210
|
+
)
|
|
3211
|
+
});
|
|
3212
|
+
page = await browserContext.newPage();
|
|
3213
|
+
await page.setViewportSize({ width: 1920, height: 1080 });
|
|
3214
|
+
await page.route("**/*", async (route) => {
|
|
3215
|
+
const requestUrl = route.request().url();
|
|
3216
|
+
if (!await this.isRequestAllowed(requestUrl)) {
|
|
3217
|
+
return await route.abort("blockedbyclient");
|
|
3218
|
+
}
|
|
3219
|
+
return await route.continue();
|
|
3220
|
+
});
|
|
3221
|
+
await page.setExtraHTTPHeaders({
|
|
3222
|
+
...fingerprintHeaders,
|
|
3223
|
+
...options?.headers
|
|
3224
|
+
});
|
|
2582
3225
|
const timeout = options?.timeout || this.defaultTimeoutMs;
|
|
2583
3226
|
logger.debug(`Navigating to ${source} with browser...`);
|
|
2584
|
-
const response = await
|
|
3227
|
+
const response = await page.goto(source, {
|
|
2585
3228
|
waitUntil: "networkidle",
|
|
2586
3229
|
timeout
|
|
2587
3230
|
});
|
|
@@ -2594,8 +3237,9 @@ class BrowserFetcher {
|
|
|
2594
3237
|
throw new ScraperError(`Redirect blocked: ${source} -> ${location}`, false);
|
|
2595
3238
|
}
|
|
2596
3239
|
}
|
|
2597
|
-
const finalUrl =
|
|
2598
|
-
|
|
3240
|
+
const finalUrl = page.url();
|
|
3241
|
+
await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
|
|
3242
|
+
const content = await page.content();
|
|
2599
3243
|
const contentBuffer = Buffer.from(content, "utf-8");
|
|
2600
3244
|
const contentType = response.headers()["content-type"] || "text/html";
|
|
2601
3245
|
const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);
|
|
@@ -2620,6 +3264,10 @@ class BrowserFetcher {
|
|
|
2620
3264
|
false,
|
|
2621
3265
|
error instanceof Error ? error : void 0
|
|
2622
3266
|
);
|
|
3267
|
+
} finally {
|
|
3268
|
+
await page?.unroute("**/*").catch(() => void 0);
|
|
3269
|
+
await page?.close().catch(() => void 0);
|
|
3270
|
+
await browserContext?.close().catch(() => void 0);
|
|
2623
3271
|
}
|
|
2624
3272
|
}
|
|
2625
3273
|
static async launchBrowser() {
|
|
@@ -2634,27 +3282,13 @@ class BrowserFetcher {
|
|
|
2634
3282
|
logger.debug("Launching browser...");
|
|
2635
3283
|
this.browser = await BrowserFetcher.launchBrowser();
|
|
2636
3284
|
}
|
|
2637
|
-
|
|
2638
|
-
this.page = await this.browser.newPage();
|
|
2639
|
-
const dynamicHeaders = this.fingerprintGenerator.generateHeaders();
|
|
2640
|
-
await this.page.setExtraHTTPHeaders(dynamicHeaders);
|
|
2641
|
-
await this.page.setViewportSize({ width: 1920, height: 1080 });
|
|
2642
|
-
}
|
|
3285
|
+
return this.browser;
|
|
2643
3286
|
}
|
|
2644
3287
|
/**
|
|
2645
3288
|
* Close the browser and clean up resources.
|
|
2646
3289
|
* Always attempts cleanup even if browser is disconnected to reap zombie processes.
|
|
2647
3290
|
*/
|
|
2648
3291
|
async close() {
|
|
2649
|
-
if (this.page) {
|
|
2650
|
-
try {
|
|
2651
|
-
await this.page.close();
|
|
2652
|
-
} catch (error) {
|
|
2653
|
-
logger.warn(`⚠️ Error closing browser page: ${error}`);
|
|
2654
|
-
} finally {
|
|
2655
|
-
this.page = null;
|
|
2656
|
-
}
|
|
2657
|
-
}
|
|
2658
3292
|
if (this.browser) {
|
|
2659
3293
|
try {
|
|
2660
3294
|
await this.browser.close();
|
|
@@ -2668,6 +3302,10 @@ class BrowserFetcher {
|
|
|
2668
3302
|
}
|
|
2669
3303
|
}
|
|
2670
3304
|
class FileFetcher {
|
|
3305
|
+
accessPolicy;
|
|
3306
|
+
constructor(scraperConfig) {
|
|
3307
|
+
this.accessPolicy = scraperConfig ? new ScraperAccessPolicy(scraperConfig.security) : null;
|
|
3308
|
+
}
|
|
2671
3309
|
canFetch(source) {
|
|
2672
3310
|
return source.startsWith("file://");
|
|
2673
3311
|
}
|
|
@@ -2677,11 +3315,10 @@ class FileFetcher {
|
|
|
2677
3315
|
* Supports conditional fetching via ETag comparison for efficient refresh operations.
|
|
2678
3316
|
*/
|
|
2679
3317
|
async fetch(source, options) {
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
}
|
|
3318
|
+
const filePath = this.accessPolicy ? (await this.accessPolicy.resolveFileAccess(
|
|
3319
|
+
source,
|
|
3320
|
+
options?.internalAllowedFileRoots
|
|
3321
|
+
)).filePath : fileUrlToPathLoose(source);
|
|
2685
3322
|
try {
|
|
2686
3323
|
const stats = await fs$1.stat(filePath);
|
|
2687
3324
|
const currentEtag = crypto.createHash("md5").update(stats.mtime.toISOString()).digest("hex");
|
|
@@ -2734,6 +3371,7 @@ class PipelineError extends Error {
|
|
|
2734
3371
|
Caused by: ${cause.stack}`;
|
|
2735
3372
|
}
|
|
2736
3373
|
}
|
|
3374
|
+
cause;
|
|
2737
3375
|
}
|
|
2738
3376
|
class PipelineStateError extends PipelineError {
|
|
2739
3377
|
}
|
|
@@ -2742,6 +3380,7 @@ class CancellationError extends PipelineError {
|
|
|
2742
3380
|
super(message);
|
|
2743
3381
|
}
|
|
2744
3382
|
}
|
|
3383
|
+
const MAX_REDIRECTS = 5;
|
|
2745
3384
|
class HttpFetcher {
|
|
2746
3385
|
maxRetriesDefault;
|
|
2747
3386
|
baseDelayDefaultMs;
|
|
@@ -2789,10 +3428,12 @@ class HttpFetcher {
|
|
|
2789
3428
|
"UNABLE_TO_VERIFY_LEAF_SIGNATURE"
|
|
2790
3429
|
];
|
|
2791
3430
|
fingerprintGenerator;
|
|
3431
|
+
accessPolicy;
|
|
2792
3432
|
constructor(scraperConfig) {
|
|
2793
3433
|
this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
|
|
2794
3434
|
this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
|
|
2795
3435
|
this.fingerprintGenerator = new FingerprintGenerator();
|
|
3436
|
+
this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
|
|
2796
3437
|
}
|
|
2797
3438
|
canFetch(source) {
|
|
2798
3439
|
return source.startsWith("http://") || source.startsWith("https://");
|
|
@@ -2817,85 +3458,126 @@ class HttpFetcher {
|
|
|
2817
3458
|
return result;
|
|
2818
3459
|
}
|
|
2819
3460
|
async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
|
|
3461
|
+
await this.accessPolicy.assertNetworkUrlAllowed(source);
|
|
2820
3462
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
2821
3463
|
try {
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
3464
|
+
let currentUrl = source;
|
|
3465
|
+
let redirectCount = 0;
|
|
3466
|
+
while (true) {
|
|
3467
|
+
const fingerprint = this.fingerprintGenerator.generateHeaders();
|
|
3468
|
+
const headers = {
|
|
3469
|
+
...fingerprint,
|
|
3470
|
+
...options?.headers
|
|
3471
|
+
// User-provided headers override generated ones
|
|
3472
|
+
};
|
|
3473
|
+
if (options?.etag) {
|
|
3474
|
+
headers["If-None-Match"] = options.etag;
|
|
3475
|
+
logger.debug(
|
|
3476
|
+
`Conditional request for ${source} with If-None-Match: ${options.etag}`
|
|
3477
|
+
);
|
|
3478
|
+
}
|
|
3479
|
+
const config = {
|
|
3480
|
+
responseType: "arraybuffer",
|
|
3481
|
+
headers: {
|
|
3482
|
+
...headers,
|
|
3483
|
+
// Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically
|
|
3484
|
+
// This prevents servers from sending zstd-compressed content that would appear as binary garbage
|
|
3485
|
+
"Accept-Encoding": "gzip, deflate, br"
|
|
3486
|
+
},
|
|
3487
|
+
timeout: options?.timeout,
|
|
3488
|
+
signal: options?.signal,
|
|
3489
|
+
// Pass signal to axios
|
|
3490
|
+
// Redirects are handled manually so every target can be revalidated before connect.
|
|
3491
|
+
maxRedirects: 0,
|
|
3492
|
+
decompress: true,
|
|
3493
|
+
// Allow 304 responses to be handled as successful responses
|
|
3494
|
+
validateStatus: (status) => {
|
|
3495
|
+
return status >= 200 && status < 400 || status === 304;
|
|
3496
|
+
}
|
|
3497
|
+
};
|
|
3498
|
+
if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) {
|
|
3499
|
+
config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
|
3500
|
+
}
|
|
3501
|
+
const response = await axios.get(currentUrl, config);
|
|
3502
|
+
if (response.status === 304) {
|
|
3503
|
+
logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
|
|
3504
|
+
return {
|
|
3505
|
+
content: Buffer.from(""),
|
|
3506
|
+
mimeType: "text/plain",
|
|
3507
|
+
source: currentUrl,
|
|
3508
|
+
status: FetchStatus.NOT_MODIFIED
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
if (response.status >= 300 && response.status < 400) {
|
|
3512
|
+
const location = response.headers.location;
|
|
3513
|
+
if (!location) {
|
|
3514
|
+
throw new ScraperError(
|
|
3515
|
+
`Redirect response for ${currentUrl} did not include a location header`,
|
|
3516
|
+
false
|
|
3517
|
+
);
|
|
3518
|
+
}
|
|
3519
|
+
if (!followRedirects) {
|
|
3520
|
+
throw new RedirectError(currentUrl, location, response.status);
|
|
3521
|
+
}
|
|
3522
|
+
if (redirectCount >= MAX_REDIRECTS) {
|
|
3523
|
+
throw new ScraperError(
|
|
3524
|
+
`Too many redirects while fetching ${source}`,
|
|
3525
|
+
false
|
|
3526
|
+
);
|
|
3527
|
+
}
|
|
3528
|
+
const redirectUrl = new URL(location, currentUrl).href;
|
|
3529
|
+
await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
|
|
3530
|
+
currentUrl = redirectUrl;
|
|
3531
|
+
redirectCount += 1;
|
|
3532
|
+
continue;
|
|
3533
|
+
}
|
|
3534
|
+
const contentTypeHeader = response.headers["content-type"];
|
|
3535
|
+
const { mimeType, charset } = MimeTypeUtils.parseContentType(
|
|
3536
|
+
typeof contentTypeHeader === "string" ? contentTypeHeader : void 0
|
|
2832
3537
|
);
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
// Pass signal to axios
|
|
2845
|
-
// Axios follows redirects by default, we need to explicitly disable it if needed
|
|
2846
|
-
maxRedirects: followRedirects ? 5 : 0,
|
|
2847
|
-
decompress: true,
|
|
2848
|
-
// Allow 304 responses to be handled as successful responses
|
|
2849
|
-
validateStatus: (status) => {
|
|
2850
|
-
return status >= 200 && status < 300 || status === 304;
|
|
3538
|
+
const rawContentEncoding = response.headers["content-encoding"];
|
|
3539
|
+
const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
|
|
3540
|
+
let content;
|
|
3541
|
+
if (response.data instanceof ArrayBuffer) {
|
|
3542
|
+
content = Buffer.from(response.data);
|
|
3543
|
+
} else if (Buffer.isBuffer(response.data)) {
|
|
3544
|
+
content = response.data;
|
|
3545
|
+
} else if (typeof response.data === "string") {
|
|
3546
|
+
content = Buffer.from(response.data, "utf-8");
|
|
3547
|
+
} else {
|
|
3548
|
+
content = Buffer.from(response.data);
|
|
2851
3549
|
}
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
3550
|
+
const finalUrl = (
|
|
3551
|
+
// Node follow-redirects style
|
|
3552
|
+
response.request?.res?.responseUrl || // Some adapters may expose directly
|
|
3553
|
+
response.request?.responseUrl || // Fallback to axios recorded config URL
|
|
3554
|
+
response.config?.url || currentUrl
|
|
3555
|
+
);
|
|
3556
|
+
await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
|
|
3557
|
+
const etag = response.headers.etag || response.headers.ETag;
|
|
3558
|
+
if (etag) {
|
|
3559
|
+
logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
|
|
3560
|
+
}
|
|
3561
|
+
const lastModified = response.headers["last-modified"];
|
|
3562
|
+
const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
|
|
2856
3563
|
return {
|
|
2857
|
-
content
|
|
2858
|
-
mimeType
|
|
2859
|
-
|
|
2860
|
-
|
|
3564
|
+
content,
|
|
3565
|
+
mimeType,
|
|
3566
|
+
charset,
|
|
3567
|
+
encoding: contentEncoding,
|
|
3568
|
+
source: finalUrl,
|
|
3569
|
+
etag,
|
|
3570
|
+
lastModified: lastModifiedISO,
|
|
3571
|
+
status: FetchStatus.SUCCESS
|
|
2861
3572
|
};
|
|
2862
3573
|
}
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
let content;
|
|
2867
|
-
if (response.data instanceof ArrayBuffer) {
|
|
2868
|
-
content = Buffer.from(response.data);
|
|
2869
|
-
} else if (Buffer.isBuffer(response.data)) {
|
|
2870
|
-
content = response.data;
|
|
2871
|
-
} else if (typeof response.data === "string") {
|
|
2872
|
-
content = Buffer.from(response.data, "utf-8");
|
|
2873
|
-
} else {
|
|
2874
|
-
content = Buffer.from(response.data);
|
|
3574
|
+
} catch (error) {
|
|
3575
|
+
if (error instanceof RedirectError || error instanceof ChallengeError) {
|
|
3576
|
+
throw error;
|
|
2875
3577
|
}
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
response.request?.res?.responseUrl || // Some adapters may expose directly
|
|
2879
|
-
response.request?.responseUrl || // Fallback to axios recorded config URL
|
|
2880
|
-
response.config?.url || source
|
|
2881
|
-
);
|
|
2882
|
-
const etag = response.headers.etag || response.headers.ETag;
|
|
2883
|
-
if (etag) {
|
|
2884
|
-
logger.debug(`Received ETag for ${source}: ${etag}`);
|
|
3578
|
+
if (error instanceof ScraperError && !error.isRetryable) {
|
|
3579
|
+
throw error;
|
|
2885
3580
|
}
|
|
2886
|
-
const lastModified = response.headers["last-modified"];
|
|
2887
|
-
const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
|
|
2888
|
-
return {
|
|
2889
|
-
content,
|
|
2890
|
-
mimeType,
|
|
2891
|
-
charset,
|
|
2892
|
-
encoding: contentEncoding,
|
|
2893
|
-
source: finalUrl,
|
|
2894
|
-
etag,
|
|
2895
|
-
lastModified: lastModifiedISO,
|
|
2896
|
-
status: FetchStatus.SUCCESS
|
|
2897
|
-
};
|
|
2898
|
-
} catch (error) {
|
|
2899
3581
|
const axiosError = error;
|
|
2900
3582
|
const status = axiosError.response?.status;
|
|
2901
3583
|
const code = axiosError.code;
|
|
@@ -2966,10 +3648,11 @@ class HttpFetcher {
|
|
|
2966
3648
|
class AutoDetectFetcher {
|
|
2967
3649
|
httpFetcher;
|
|
2968
3650
|
browserFetcher;
|
|
2969
|
-
fileFetcher
|
|
3651
|
+
fileFetcher;
|
|
2970
3652
|
constructor(scraperConfig) {
|
|
2971
3653
|
this.httpFetcher = new HttpFetcher(scraperConfig);
|
|
2972
3654
|
this.browserFetcher = new BrowserFetcher(scraperConfig);
|
|
3655
|
+
this.fileFetcher = new FileFetcher(scraperConfig);
|
|
2973
3656
|
}
|
|
2974
3657
|
/**
|
|
2975
3658
|
* Check if this fetcher can handle the given source.
|
|
@@ -3353,6 +4036,7 @@ class CodeContentSplitter {
|
|
|
3353
4036
|
constructor(options) {
|
|
3354
4037
|
this.options = options;
|
|
3355
4038
|
}
|
|
4039
|
+
options;
|
|
3356
4040
|
async split(content) {
|
|
3357
4041
|
const language = content.match(/^```(\w+)\n/)?.[1];
|
|
3358
4042
|
const strippedContent = content.replace(/^```(\w*)\n/, "").replace(/```\s*$/, "");
|
|
@@ -3388,6 +4072,7 @@ class TextContentSplitter {
|
|
|
3388
4072
|
constructor(options) {
|
|
3389
4073
|
this.options = options;
|
|
3390
4074
|
}
|
|
4075
|
+
options;
|
|
3391
4076
|
/**
|
|
3392
4077
|
* Splits text content into chunks while trying to preserve semantic boundaries.
|
|
3393
4078
|
* Prefers paragraph breaks, then line breaks, finally falling back to word boundaries.
|
|
@@ -3515,6 +4200,7 @@ class ListContentSplitter {
|
|
|
3515
4200
|
this.options = options;
|
|
3516
4201
|
this.textSplitter = new TextContentSplitter(options);
|
|
3517
4202
|
}
|
|
4203
|
+
options;
|
|
3518
4204
|
textSplitter;
|
|
3519
4205
|
async split(content) {
|
|
3520
4206
|
if (content.length <= this.options.chunkSize) {
|
|
@@ -3584,6 +4270,7 @@ class TableContentSplitter {
|
|
|
3584
4270
|
constructor(options) {
|
|
3585
4271
|
this.options = options;
|
|
3586
4272
|
}
|
|
4273
|
+
options;
|
|
3587
4274
|
/**
|
|
3588
4275
|
* Splits table content into chunks while preserving table structure
|
|
3589
4276
|
*/
|
|
@@ -3698,6 +4385,8 @@ class SemanticMarkdownSplitter {
|
|
|
3698
4385
|
// Lists prefer to stay together, so use preferred size
|
|
3699
4386
|
});
|
|
3700
4387
|
}
|
|
4388
|
+
preferredChunkSize;
|
|
4389
|
+
maxChunkSize;
|
|
3701
4390
|
turndownService;
|
|
3702
4391
|
textSplitter;
|
|
3703
4392
|
codeSplitter;
|
|
@@ -4581,15 +5270,122 @@ class SimpleMemoryCache {
|
|
|
4581
5270
|
this.cache.clear();
|
|
4582
5271
|
}
|
|
4583
5272
|
}
|
|
5273
|
+
const BLOCKLIST_NOT_BLOCKED = Object.freeze({ blocked: false });
|
|
5274
|
+
const SUBRESOURCE_BLOCKLIST = Object.freeze([
|
|
5275
|
+
// Analytics — page-view and event tracking SDKs; no content.
|
|
5276
|
+
{ host: "google-analytics.com", category: "Analytics" },
|
|
5277
|
+
{ host: "googletagmanager.com", category: "Analytics" },
|
|
5278
|
+
{ host: "segment.io", category: "Analytics" },
|
|
5279
|
+
{ host: "segment.com", category: "Analytics" },
|
|
5280
|
+
{ host: "mixpanel.com", category: "Analytics" },
|
|
5281
|
+
{ host: "amplitude.com", category: "Analytics" },
|
|
5282
|
+
{ host: "plausible.io", category: "Analytics" },
|
|
5283
|
+
{ host: "matomo.cloud", category: "Analytics" },
|
|
5284
|
+
{ host: "stats.wp.com", category: "Analytics" },
|
|
5285
|
+
// Session Replay — record user interactions; never content.
|
|
5286
|
+
{ host: "hotjar.com", category: "Session Replay" },
|
|
5287
|
+
{ host: "fullstory.com", category: "Session Replay" },
|
|
5288
|
+
{ host: "logrocket.com", category: "Session Replay" },
|
|
5289
|
+
{ host: "lr-ingest.io", category: "Session Replay" },
|
|
5290
|
+
{ host: "smartlook.com", category: "Session Replay" },
|
|
5291
|
+
// Chat Widgets — UI overlays the sanitizer strips post-fetch anyway.
|
|
5292
|
+
{ host: "intercom.io", category: "Chat Widget" },
|
|
5293
|
+
{ host: "intercomcdn.com", category: "Chat Widget" },
|
|
5294
|
+
{ host: "widget.kapa.ai", category: "Chat Widget" },
|
|
5295
|
+
{ host: "drift.com", category: "Chat Widget" },
|
|
5296
|
+
{ host: "driftt.com", category: "Chat Widget" },
|
|
5297
|
+
{ host: "crisp.chat", category: "Chat Widget" },
|
|
5298
|
+
{ host: "tawk.to", category: "Chat Widget" },
|
|
5299
|
+
{ host: "zdassets.com", category: "Chat Widget" },
|
|
5300
|
+
// Captcha — challenge runtimes; documentation pages don't need them.
|
|
5301
|
+
{ host: "hcaptcha.com", category: "Captcha" },
|
|
5302
|
+
{ host: "recaptcha.net", category: "Captcha" },
|
|
5303
|
+
// Social Embed runtimes — the embed-document iframe is allowed (document type
|
|
5304
|
+
// is exempt at the route handler); only the runtime JS is blocked.
|
|
5305
|
+
{
|
|
5306
|
+
host: "youtube-nocookie.com",
|
|
5307
|
+
pathPrefix: "/s/_/ytembeds/",
|
|
5308
|
+
category: "Social Embed"
|
|
5309
|
+
},
|
|
5310
|
+
{ host: "platform.twitter.com", category: "Social Embed" },
|
|
5311
|
+
{ host: "connect.facebook.net", category: "Social Embed" },
|
|
5312
|
+
{ host: "platform.linkedin.com", category: "Social Embed" }
|
|
5313
|
+
]);
|
|
5314
|
+
for (const entry of SUBRESOURCE_BLOCKLIST) {
|
|
5315
|
+
if (!entry.host || entry.host.includes("/") || entry.host.includes(":")) {
|
|
5316
|
+
throw new Error(
|
|
5317
|
+
`Invalid blocklist entry: host must be a bare hostname (got "${entry.host}")`
|
|
5318
|
+
);
|
|
5319
|
+
}
|
|
5320
|
+
if ("pathPrefix" in entry && !entry.pathPrefix.startsWith("/")) {
|
|
5321
|
+
throw new Error(
|
|
5322
|
+
`Invalid blocklist entry for "${entry.host}": pathPrefix must start with "/" (got "${entry.pathPrefix}")`
|
|
5323
|
+
);
|
|
5324
|
+
}
|
|
5325
|
+
}
|
|
5326
|
+
function hostMatches(requestHost, entryHost) {
|
|
5327
|
+
if (requestHost === entryHost) return true;
|
|
5328
|
+
return requestHost.endsWith(`.${entryHost}`);
|
|
5329
|
+
}
|
|
5330
|
+
function isBlockedSubresource(url) {
|
|
5331
|
+
let parsed;
|
|
5332
|
+
try {
|
|
5333
|
+
parsed = new URL(url);
|
|
5334
|
+
} catch {
|
|
5335
|
+
return BLOCKLIST_NOT_BLOCKED;
|
|
5336
|
+
}
|
|
5337
|
+
const host = parsed.hostname;
|
|
5338
|
+
for (const entry of SUBRESOURCE_BLOCKLIST) {
|
|
5339
|
+
if (!hostMatches(host, entry.host)) continue;
|
|
5340
|
+
if ("pathPrefix" in entry && !parsed.pathname.startsWith(entry.pathPrefix)) {
|
|
5341
|
+
continue;
|
|
5342
|
+
}
|
|
5343
|
+
return { blocked: true, category: entry.category };
|
|
5344
|
+
}
|
|
5345
|
+
return BLOCKLIST_NOT_BLOCKED;
|
|
5346
|
+
}
|
|
4584
5347
|
class HtmlPlaywrightMiddleware {
|
|
4585
5348
|
browser = null;
|
|
4586
5349
|
config;
|
|
5350
|
+
accessPolicy;
|
|
4587
5351
|
// Static LRU cache for all fetched resources, shared across instances
|
|
4588
5352
|
static resourceCache = new SimpleMemoryCache(
|
|
4589
5353
|
defaults.scraper.fetcher.maxCacheItems
|
|
4590
5354
|
);
|
|
4591
5355
|
constructor(config) {
|
|
4592
5356
|
this.config = config;
|
|
5357
|
+
this.accessPolicy = new ScraperAccessPolicy(config.security);
|
|
5358
|
+
}
|
|
5359
|
+
async isRequestAllowed(url) {
|
|
5360
|
+
try {
|
|
5361
|
+
await this.accessPolicy.assertNetworkUrlAllowed(url);
|
|
5362
|
+
return true;
|
|
5363
|
+
} catch {
|
|
5364
|
+
return false;
|
|
5365
|
+
}
|
|
5366
|
+
}
|
|
5367
|
+
/**
|
|
5368
|
+
* Returns true if the request was handled (aborted) by the built-in tracker
|
|
5369
|
+
* blocklist; the caller should bail out of further processing in that case.
|
|
5370
|
+
* Returns false when the blocklist is disabled, when the request is a
|
|
5371
|
+
* top-level/iframe document navigation, or when no entry matches.
|
|
5372
|
+
*/
|
|
5373
|
+
async tryBlocklistAbort(route, reqUrl) {
|
|
5374
|
+
if (!this.config.skipKnownTrackers) return false;
|
|
5375
|
+
if (route.request().resourceType() === "document") return false;
|
|
5376
|
+
const match = isBlockedSubresource(reqUrl);
|
|
5377
|
+
if (!match.blocked) return false;
|
|
5378
|
+
logger.debug(`Blocked sub-resource (${match.category}): ${reqUrl}`);
|
|
5379
|
+
try {
|
|
5380
|
+
await route.abort("blockedbyclient");
|
|
5381
|
+
} catch (error) {
|
|
5382
|
+
if (this.isRouteAlreadyHandledError(error)) {
|
|
5383
|
+
logger.debug(`Route already handled (blocklist abort): ${reqUrl}`);
|
|
5384
|
+
return true;
|
|
5385
|
+
}
|
|
5386
|
+
throw error;
|
|
5387
|
+
}
|
|
5388
|
+
return true;
|
|
4593
5389
|
}
|
|
4594
5390
|
/**
|
|
4595
5391
|
* Initializes the Playwright browser instance.
|
|
@@ -4985,6 +5781,12 @@ class HtmlPlaywrightMiddleware {
|
|
|
4985
5781
|
}
|
|
4986
5782
|
})();
|
|
4987
5783
|
const resourceType = route.request().resourceType();
|
|
5784
|
+
if (!await this.isRequestAllowed(reqUrl)) {
|
|
5785
|
+
return await route.abort("blockedbyclient");
|
|
5786
|
+
}
|
|
5787
|
+
if (await this.tryBlocklistAbort(route, reqUrl)) {
|
|
5788
|
+
return;
|
|
5789
|
+
}
|
|
4988
5790
|
if (["image", "font", "media"].includes(resourceType)) {
|
|
4989
5791
|
try {
|
|
4990
5792
|
return await route.abort();
|
|
@@ -5109,6 +5911,9 @@ class HtmlPlaywrightMiddleware {
|
|
|
5109
5911
|
logger.debug(`Cache miss for frame: ${resolvedUrl}`);
|
|
5110
5912
|
let framePage = null;
|
|
5111
5913
|
try {
|
|
5914
|
+
if (!await this.isRequestAllowed(resolvedUrl)) {
|
|
5915
|
+
return "";
|
|
5916
|
+
}
|
|
5112
5917
|
framePage = await parentPage.context().newPage();
|
|
5113
5918
|
await this.setupCachingRouteInterception(framePage);
|
|
5114
5919
|
logger.debug(`Fetching frame content from: ${resolvedUrl}`);
|
|
@@ -5230,9 +6035,18 @@ ${frame.content}
|
|
|
5230
6035
|
try {
|
|
5231
6036
|
const browser = await this.ensureBrowser();
|
|
5232
6037
|
if (credentials) {
|
|
5233
|
-
browserContext = await browser.newContext({
|
|
6038
|
+
browserContext = await browser.newContext({
|
|
6039
|
+
httpCredentials: credentials,
|
|
6040
|
+
ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
|
|
6041
|
+
"https://browser-context.local"
|
|
6042
|
+
)
|
|
6043
|
+
});
|
|
5234
6044
|
} else {
|
|
5235
|
-
browserContext = await browser.newContext(
|
|
6045
|
+
browserContext = await browser.newContext({
|
|
6046
|
+
ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(
|
|
6047
|
+
"https://browser-context.local"
|
|
6048
|
+
)
|
|
6049
|
+
});
|
|
5236
6050
|
}
|
|
5237
6051
|
page = await browserContext.newPage();
|
|
5238
6052
|
logger.debug(`Playwright: Processing ${context.source}`);
|
|
@@ -5271,6 +6085,12 @@ ${frame.content}
|
|
|
5271
6085
|
}
|
|
5272
6086
|
})();
|
|
5273
6087
|
const resourceType = route.request().resourceType();
|
|
6088
|
+
if (!await this.isRequestAllowed(reqUrl)) {
|
|
6089
|
+
return await route.abort("blockedbyclient");
|
|
6090
|
+
}
|
|
6091
|
+
if (await this.tryBlocklistAbort(route, reqUrl)) {
|
|
6092
|
+
return;
|
|
6093
|
+
}
|
|
5274
6094
|
if (["image", "font", "media"].includes(resourceType)) {
|
|
5275
6095
|
try {
|
|
5276
6096
|
return await route.abort();
|
|
@@ -6468,6 +7288,7 @@ class PythonParser {
|
|
|
6468
7288
|
constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
|
|
6469
7289
|
this.treeSitterSizeLimit = treeSitterSizeLimit;
|
|
6470
7290
|
}
|
|
7291
|
+
treeSitterSizeLimit;
|
|
6471
7292
|
name = "python";
|
|
6472
7293
|
fileExtensions = [".py", ".pyi", ".pyw"];
|
|
6473
7294
|
mimeTypes = [
|
|
@@ -6881,6 +7702,7 @@ class TypeScriptParser {
|
|
|
6881
7702
|
constructor(treeSitterSizeLimit = defaults.splitter.treeSitterSizeLimit) {
|
|
6882
7703
|
this.treeSitterSizeLimit = treeSitterSizeLimit;
|
|
6883
7704
|
}
|
|
7705
|
+
treeSitterSizeLimit;
|
|
6884
7706
|
// Unified extensions: TS + JS
|
|
6885
7707
|
fileExtensions = [
|
|
6886
7708
|
".ts",
|
|
@@ -7987,6 +8809,8 @@ class RemoveTool {
|
|
|
7987
8809
|
this.documentManagementService = documentManagementService;
|
|
7988
8810
|
this.pipeline = pipeline;
|
|
7989
8811
|
}
|
|
8812
|
+
documentManagementService;
|
|
8813
|
+
pipeline;
|
|
7990
8814
|
/**
|
|
7991
8815
|
* Executes the tool to remove the specified library version completely.
|
|
7992
8816
|
* Aborts any QUEUED/RUNNING job for the same library+version before deleting.
|
|
@@ -8205,6 +9029,7 @@ class HierarchicalAssemblyStrategy {
|
|
|
8205
9029
|
constructor(config) {
|
|
8206
9030
|
this.config = config;
|
|
8207
9031
|
}
|
|
9032
|
+
config;
|
|
8208
9033
|
/**
|
|
8209
9034
|
* Determines if this strategy can handle the given content type.
|
|
8210
9035
|
* Handles structured content like source code, JSON, configuration files.
|
|
@@ -8623,6 +9448,7 @@ class MarkdownAssemblyStrategy {
|
|
|
8623
9448
|
constructor(config) {
|
|
8624
9449
|
this.config = config;
|
|
8625
9450
|
}
|
|
9451
|
+
config;
|
|
8626
9452
|
/**
|
|
8627
9453
|
* Determines if this strategy can handle the given content type.
|
|
8628
9454
|
* Handles markdown, HTML, plain text, and serves as fallback for unknown types.
|
|
@@ -10271,7 +11097,7 @@ class DocumentStore {
|
|
|
10271
11097
|
if (!versionRow) {
|
|
10272
11098
|
return [];
|
|
10273
11099
|
}
|
|
10274
|
-
const { id: versionId
|
|
11100
|
+
const { id: versionId } = versionRow;
|
|
10275
11101
|
if (this.isVectorSearchEnabled) {
|
|
10276
11102
|
const rawEmbedding = await this.embeddings.embedQuery(query);
|
|
10277
11103
|
const embedding = this.padVector(rawEmbedding);
|
|
@@ -10283,8 +11109,12 @@ class DocumentStore {
|
|
|
10283
11109
|
dv.rowid as id,
|
|
10284
11110
|
dv.distance as vec_distance
|
|
10285
11111
|
FROM documents_vec dv
|
|
10286
|
-
|
|
10287
|
-
|
|
11112
|
+
JOIN documents d ON dv.rowid = d.id
|
|
11113
|
+
JOIN pages p ON d.page_id = p.id
|
|
11114
|
+
JOIN versions v ON p.version_id = v.id
|
|
11115
|
+
JOIN libraries l ON v.library_id = l.id
|
|
11116
|
+
WHERE l.name = ?
|
|
11117
|
+
AND COALESCE(v.name, '') = COALESCE(?, '')
|
|
10288
11118
|
AND dv.embedding MATCH ?
|
|
10289
11119
|
AND dv.k = ?
|
|
10290
11120
|
ORDER BY dv.distance
|
|
@@ -10322,8 +11152,8 @@ class DocumentStore {
|
|
|
10322
11152
|
)
|
|
10323
11153
|
`);
|
|
10324
11154
|
const rawResults = stmt.all(
|
|
10325
|
-
|
|
10326
|
-
|
|
11155
|
+
library.toLowerCase(),
|
|
11156
|
+
normalizedVersion,
|
|
10327
11157
|
JSON.stringify(embedding),
|
|
10328
11158
|
vectorSearchK,
|
|
10329
11159
|
versionId,
|
|
@@ -11790,7 +12620,7 @@ const Layout = ({
|
|
|
11790
12620
|
children,
|
|
11791
12621
|
eventClientConfig
|
|
11792
12622
|
}) => {
|
|
11793
|
-
const versionString = version || "2.
|
|
12623
|
+
const versionString = version || "2.3.0";
|
|
11794
12624
|
const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
|
|
11795
12625
|
return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
|
|
11796
12626
|
/* @__PURE__ */ jsxs("head", { children: [
|
|
@@ -13139,105 +13969,6 @@ const ScrapeForm = ({
|
|
|
13139
13969
|
scraperConfig
|
|
13140
13970
|
}
|
|
13141
13971
|
) });
|
|
13142
|
-
const DEFAULT_FILE_EXCLUSIONS = [
|
|
13143
|
-
// CHANGELOG files (case variations)
|
|
13144
|
-
"**/CHANGELOG.md",
|
|
13145
|
-
"**/changelog.md",
|
|
13146
|
-
"**/CHANGELOG.mdx",
|
|
13147
|
-
"**/changelog.mdx",
|
|
13148
|
-
// LICENSE files (case variations)
|
|
13149
|
-
"**/LICENSE",
|
|
13150
|
-
"**/LICENSE.md",
|
|
13151
|
-
"**/license.md",
|
|
13152
|
-
// CODE_OF_CONDUCT files (case variations)
|
|
13153
|
-
"**/CODE_OF_CONDUCT.md",
|
|
13154
|
-
"**/code_of_conduct.md",
|
|
13155
|
-
// Test files
|
|
13156
|
-
"**/*.test.*",
|
|
13157
|
-
"**/*.spec.*",
|
|
13158
|
-
"**/*_test.py",
|
|
13159
|
-
"**/*_test.go",
|
|
13160
|
-
// Package manager lock files
|
|
13161
|
-
"**/*.lock",
|
|
13162
|
-
"**/package-lock.json",
|
|
13163
|
-
"**/yarn.lock",
|
|
13164
|
-
"**/pnpm-lock.yaml",
|
|
13165
|
-
"**/go.sum",
|
|
13166
|
-
// Build artifacts
|
|
13167
|
-
"**/*.min.js",
|
|
13168
|
-
"**/*.min.css",
|
|
13169
|
-
"**/*.map",
|
|
13170
|
-
"**/*.d.ts",
|
|
13171
|
-
// IDE/System files
|
|
13172
|
-
"**/.DS_Store",
|
|
13173
|
-
"**/Thumbs.db",
|
|
13174
|
-
"**/*.swp",
|
|
13175
|
-
"**/*.swo",
|
|
13176
|
-
// Internal config files (using regex pattern)
|
|
13177
|
-
"/.*\\.(ini|cfg|conf|log|pid)$/"
|
|
13178
|
-
];
|
|
13179
|
-
const DEFAULT_FOLDER_EXCLUSIONS = [
|
|
13180
|
-
// Archive and deprecated content (matches anywhere in path)
|
|
13181
|
-
"**/archive/**",
|
|
13182
|
-
"**/archived/**",
|
|
13183
|
-
"**/deprecated/**",
|
|
13184
|
-
"**/legacy/**",
|
|
13185
|
-
"**/old/**",
|
|
13186
|
-
"**/outdated/**",
|
|
13187
|
-
"**/previous/**",
|
|
13188
|
-
"**/superseded/**",
|
|
13189
|
-
// Specific paths that don't follow the general pattern
|
|
13190
|
-
"docs/old/**",
|
|
13191
|
-
// Test directories
|
|
13192
|
-
"**/test/**",
|
|
13193
|
-
"**/tests/**",
|
|
13194
|
-
"**/__tests__/**",
|
|
13195
|
-
"**/spec/**",
|
|
13196
|
-
// Build output directories
|
|
13197
|
-
"**/dist/**",
|
|
13198
|
-
"**/build/**",
|
|
13199
|
-
"**/out/**",
|
|
13200
|
-
"**/target/**",
|
|
13201
|
-
"**/.next/**",
|
|
13202
|
-
"**/.nuxt/**",
|
|
13203
|
-
// IDE directories
|
|
13204
|
-
"**/.vscode/**",
|
|
13205
|
-
"**/.idea/**",
|
|
13206
|
-
// Internationalization folders - non-English locales
|
|
13207
|
-
"**/i18n/ar*/**",
|
|
13208
|
-
"**/i18n/de*/**",
|
|
13209
|
-
"**/i18n/es*/**",
|
|
13210
|
-
"**/i18n/fr*/**",
|
|
13211
|
-
"**/i18n/hi*/**",
|
|
13212
|
-
"**/i18n/it*/**",
|
|
13213
|
-
"**/i18n/ja*/**",
|
|
13214
|
-
"**/i18n/ko*/**",
|
|
13215
|
-
"**/i18n/nl*/**",
|
|
13216
|
-
"**/i18n/pl*/**",
|
|
13217
|
-
"**/i18n/pt*/**",
|
|
13218
|
-
"**/i18n/ru*/**",
|
|
13219
|
-
"**/i18n/sv*/**",
|
|
13220
|
-
"**/i18n/th*/**",
|
|
13221
|
-
"**/i18n/tr*/**",
|
|
13222
|
-
"**/i18n/vi*/**",
|
|
13223
|
-
"**/i18n/zh*/**",
|
|
13224
|
-
// Common locale folder patterns
|
|
13225
|
-
"**/zh-cn/**",
|
|
13226
|
-
"**/zh-hk/**",
|
|
13227
|
-
"**/zh-mo/**",
|
|
13228
|
-
"**/zh-sg/**",
|
|
13229
|
-
"**/zh-tw/**"
|
|
13230
|
-
];
|
|
13231
|
-
const DEFAULT_EXCLUSION_PATTERNS = [
|
|
13232
|
-
...DEFAULT_FILE_EXCLUSIONS,
|
|
13233
|
-
...DEFAULT_FOLDER_EXCLUSIONS
|
|
13234
|
-
];
|
|
13235
|
-
function getEffectiveExclusionPatterns(userPatterns) {
|
|
13236
|
-
if (userPatterns !== void 0) {
|
|
13237
|
-
return userPatterns;
|
|
13238
|
-
}
|
|
13239
|
-
return DEFAULT_EXCLUSION_PATTERNS;
|
|
13240
|
-
}
|
|
13241
13972
|
function registerNewJobRoutes(server, scrapeTool, scraperConfig) {
|
|
13242
13973
|
server.get("/web/jobs/new", async () => {
|
|
13243
13974
|
return /* @__PURE__ */ jsx(
|
|
@@ -14136,6 +14867,9 @@ class AppServer {
|
|
|
14136
14867
|
// Use our own logger
|
|
14137
14868
|
});
|
|
14138
14869
|
}
|
|
14870
|
+
docService;
|
|
14871
|
+
pipeline;
|
|
14872
|
+
eventBus;
|
|
14139
14873
|
server;
|
|
14140
14874
|
mcpServer = null;
|
|
14141
14875
|
authManager = null;
|
|
@@ -14172,7 +14906,7 @@ class AppServer {
|
|
|
14172
14906
|
try {
|
|
14173
14907
|
if (telemetry.isEnabled()) {
|
|
14174
14908
|
telemetry.setGlobalContext({
|
|
14175
|
-
appVersion: "2.
|
|
14909
|
+
appVersion: "2.3.0",
|
|
14176
14910
|
appPlatform: process.platform,
|
|
14177
14911
|
appNodeVersion: process.version,
|
|
14178
14912
|
appServicesEnabled: this.getActiveServicesList(),
|
|
@@ -14695,82 +15429,49 @@ class PipelineClient {
|
|
|
14695
15429
|
logger.debug("PipelineClient.setCallbacks called - no-op for external worker");
|
|
14696
15430
|
}
|
|
14697
15431
|
}
|
|
14698
|
-
|
|
14699
|
-
return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
|
|
14700
|
-
}
|
|
14701
|
-
function patternToRegExp(pattern) {
|
|
14702
|
-
if (isRegexPattern(pattern)) {
|
|
14703
|
-
return new RegExp(pattern.slice(1, -1));
|
|
14704
|
-
}
|
|
14705
|
-
const re = minimatch.makeRe(pattern, { dot: true });
|
|
14706
|
-
if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
|
|
14707
|
-
return re;
|
|
14708
|
-
}
|
|
14709
|
-
function matchesAnyPattern(path2, patterns) {
|
|
14710
|
-
if (!patterns || patterns.length === 0) return false;
|
|
14711
|
-
const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
|
|
14712
|
-
return patterns.some((pattern) => {
|
|
14713
|
-
if (isRegexPattern(pattern)) {
|
|
14714
|
-
return patternToRegExp(pattern).test(normalizedPath);
|
|
14715
|
-
}
|
|
14716
|
-
const pathForMatch = normalizedPath.replace(/^\//, "");
|
|
14717
|
-
const patternForMatch = pattern.startsWith("/") ? pattern.slice(1) : pattern;
|
|
14718
|
-
return minimatch(pathForMatch, patternForMatch, { dot: true });
|
|
14719
|
-
});
|
|
14720
|
-
}
|
|
14721
|
-
function extractPathAndQuery(url) {
|
|
14722
|
-
try {
|
|
14723
|
-
const u = new URL(url);
|
|
14724
|
-
return u.pathname + (u.search || "");
|
|
14725
|
-
} catch {
|
|
14726
|
-
return url;
|
|
14727
|
-
}
|
|
14728
|
-
}
|
|
14729
|
-
function shouldIncludeUrl(url, includePatterns, excludePatterns) {
|
|
14730
|
-
const path2 = extractPathAndQuery(url);
|
|
14731
|
-
const normalizedPath = path2.startsWith("/") ? path2 : `/${path2}`;
|
|
14732
|
-
let basename;
|
|
14733
|
-
if (url.startsWith("file://")) {
|
|
14734
|
-
try {
|
|
14735
|
-
const u = new URL(url);
|
|
14736
|
-
basename = u.pathname ? u.pathname.split("/").pop() : void 0;
|
|
14737
|
-
} catch {
|
|
14738
|
-
}
|
|
14739
|
-
}
|
|
14740
|
-
const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
|
|
14741
|
-
const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
|
|
14742
|
-
if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))
|
|
14743
|
-
return false;
|
|
14744
|
-
if (!includePatterns || includePatterns.length === 0) return true;
|
|
14745
|
-
return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
|
|
14746
|
-
}
|
|
15432
|
+
const INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
|
|
14747
15433
|
function computeBaseDirectory(pathname) {
|
|
14748
|
-
if (pathname === "") return "/";
|
|
15434
|
+
if (pathname === "" || pathname === "/") return "/";
|
|
14749
15435
|
if (pathname.endsWith("/")) return pathname;
|
|
14750
15436
|
const lastSegment = pathname.split("/").at(-1) || "";
|
|
14751
|
-
|
|
14752
|
-
if (looksLikeFile) {
|
|
15437
|
+
if (INDEX_FILE_PATTERN.test(lastSegment)) {
|
|
14753
15438
|
return pathname.replace(/\/[^/]*$/, "/");
|
|
14754
15439
|
}
|
|
14755
15440
|
return `${pathname}/`;
|
|
14756
15441
|
}
|
|
15442
|
+
function isPathDescendant(parentPath, childPath) {
|
|
15443
|
+
const normalizedParent = parentPath.endsWith("/") ? parentPath : `${parentPath}/`;
|
|
15444
|
+
if (childPath === normalizedParent) return true;
|
|
15445
|
+
if (`${childPath}/` === normalizedParent) return true;
|
|
15446
|
+
return childPath.startsWith(normalizedParent);
|
|
15447
|
+
}
|
|
15448
|
+
function stripTrailingDot(hostname) {
|
|
15449
|
+
return hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
|
|
15450
|
+
}
|
|
14757
15451
|
function isInScope(baseUrl, targetUrl, scope) {
|
|
14758
15452
|
if (baseUrl.protocol !== targetUrl.protocol) return false;
|
|
15453
|
+
const baseHostNoDot = normalizeHost(baseUrl.host, baseUrl.hostname);
|
|
15454
|
+
const targetHostNoDot = normalizeHost(targetUrl.host, targetUrl.hostname);
|
|
14759
15455
|
switch (scope) {
|
|
14760
15456
|
case "subpages": {
|
|
14761
|
-
if (
|
|
15457
|
+
if (baseHostNoDot !== targetHostNoDot) return false;
|
|
14762
15458
|
const baseDir = computeBaseDirectory(baseUrl.pathname);
|
|
14763
15459
|
return targetUrl.pathname.startsWith(baseDir);
|
|
14764
15460
|
}
|
|
14765
15461
|
case "hostname":
|
|
14766
|
-
return
|
|
15462
|
+
return baseHostNoDot === targetHostNoDot;
|
|
14767
15463
|
case "domain": {
|
|
14768
|
-
return extractPrimaryDomain(baseUrl.hostname) === extractPrimaryDomain(targetUrl.hostname);
|
|
15464
|
+
return extractPrimaryDomain(stripTrailingDot(baseUrl.hostname)) === extractPrimaryDomain(stripTrailingDot(targetUrl.hostname));
|
|
14769
15465
|
}
|
|
14770
15466
|
default:
|
|
14771
15467
|
return false;
|
|
14772
15468
|
}
|
|
14773
15469
|
}
|
|
15470
|
+
function normalizeHost(host, hostname) {
|
|
15471
|
+
const stripped = stripTrailingDot(hostname);
|
|
15472
|
+
if (stripped === hostname) return host;
|
|
15473
|
+
return host.replace(hostname, stripped);
|
|
15474
|
+
}
|
|
14774
15475
|
class FailureThresholdExceededError extends ScraperError {
|
|
14775
15476
|
}
|
|
14776
15477
|
class BaseScraperStrategy {
|
|
@@ -14816,13 +15517,26 @@ class BaseScraperStrategy {
|
|
|
14816
15517
|
/**
|
|
14817
15518
|
* Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
|
|
14818
15519
|
* Scope is checked first, then patterns.
|
|
14819
|
-
|
|
14820
|
-
|
|
14821
|
-
|
|
15520
|
+
*
|
|
15521
|
+
* `internalAllowedFileRoots` opts a queue item out of the protocol-strict
|
|
15522
|
+
* scope check: when a web URL has been accepted as an archive root and the
|
|
15523
|
+
* archive expands into `file://` members, those members are continuations of
|
|
15524
|
+
* the same accepted scrape and should not be rejected because they crossed
|
|
15525
|
+
* from `https:` to `file:`. The bypass is intentionally narrow — the
|
|
15526
|
+
* `file://` target must resolve inside one of the internal roots — so
|
|
15527
|
+
* arbitrary links injected into archive content cannot escape the archive
|
|
15528
|
+
* sandbox via this path. Downstream `resolveFileAccess` enforces the same
|
|
15529
|
+
* rule, but rejecting early here keeps unrelated `file://` URLs out of the
|
|
15530
|
+
* crawl queue entirely.
|
|
15531
|
+
*/
|
|
15532
|
+
shouldProcessUrl(url, options, context = {}) {
|
|
15533
|
+
const isInternalArchiveMember = url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots);
|
|
15534
|
+
if (!isInternalArchiveMember) {
|
|
15535
|
+
const scope = options.scope ?? "subpages";
|
|
14822
15536
|
try {
|
|
14823
15537
|
const base = this.canonicalBaseUrl ?? new URL$1(options.url);
|
|
14824
15538
|
const target = new URL$1(url);
|
|
14825
|
-
if (!isInScope(base, target,
|
|
15539
|
+
if (!isInScope(base, target, scope)) return false;
|
|
14826
15540
|
} catch {
|
|
14827
15541
|
return false;
|
|
14828
15542
|
}
|
|
@@ -14979,18 +15693,22 @@ class BaseScraperStrategy {
|
|
|
14979
15693
|
}
|
|
14980
15694
|
const nextItems = result.links || [];
|
|
14981
15695
|
const linkBaseUrl = finalUrl ? new URL$1(finalUrl) : baseUrl;
|
|
15696
|
+
const internalAllowedFileRoots = result.internalAllowedFileRoots ?? item.internalAllowedFileRoots;
|
|
14982
15697
|
this.recordChildPageCompletion(item, result);
|
|
14983
15698
|
ensureFailureRateWithinThreshold();
|
|
14984
15699
|
throwIfBatchAborted();
|
|
14985
15700
|
return nextItems.map((value) => {
|
|
14986
15701
|
try {
|
|
14987
15702
|
const targetUrl = new URL$1(value, linkBaseUrl);
|
|
14988
|
-
if (!this.shouldProcessUrl(targetUrl.href, options
|
|
15703
|
+
if (!this.shouldProcessUrl(targetUrl.href, options, {
|
|
15704
|
+
internalAllowedFileRoots
|
|
15705
|
+
})) {
|
|
14989
15706
|
return null;
|
|
14990
15707
|
}
|
|
14991
15708
|
return {
|
|
14992
15709
|
url: targetUrl.href,
|
|
14993
|
-
depth: item.depth + 1
|
|
15710
|
+
depth: item.depth + 1,
|
|
15711
|
+
...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
|
|
14994
15712
|
};
|
|
14995
15713
|
} catch (_error) {
|
|
14996
15714
|
logger.warn(`❌ Invalid URL: ${value}`);
|
|
@@ -15100,6 +15818,21 @@ class BaseScraperStrategy {
|
|
|
15100
15818
|
async cleanup() {
|
|
15101
15819
|
}
|
|
15102
15820
|
}
|
|
15821
|
+
function isFileUrlInsideRoots(url, roots) {
|
|
15822
|
+
if (!roots || roots.length === 0) return false;
|
|
15823
|
+
let target;
|
|
15824
|
+
try {
|
|
15825
|
+
target = path.resolve(fileUrlToPathLoose(url));
|
|
15826
|
+
} catch {
|
|
15827
|
+
return false;
|
|
15828
|
+
}
|
|
15829
|
+
return roots.some((root) => {
|
|
15830
|
+
const resolvedRoot = path.resolve(root);
|
|
15831
|
+
if (resolvedRoot === target) return true;
|
|
15832
|
+
const relative = path.relative(resolvedRoot, target);
|
|
15833
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
15834
|
+
});
|
|
15835
|
+
}
|
|
15103
15836
|
class GitHubRepoProcessor {
|
|
15104
15837
|
httpFetcher;
|
|
15105
15838
|
pipelines;
|
|
@@ -16070,21 +16803,24 @@ async function getArchiveAdapter(filePath) {
|
|
|
16070
16803
|
return null;
|
|
16071
16804
|
}
|
|
16072
16805
|
class LocalFileStrategy extends BaseScraperStrategy {
|
|
16073
|
-
fileFetcher
|
|
16806
|
+
fileFetcher;
|
|
16074
16807
|
pipelines;
|
|
16808
|
+
accessPolicy;
|
|
16075
16809
|
constructor(config) {
|
|
16076
16810
|
super(config);
|
|
16811
|
+
this.fileFetcher = new FileFetcher(config.scraper);
|
|
16077
16812
|
this.pipelines = PipelineFactory$1.createStandardPipelines(config);
|
|
16813
|
+
this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
|
|
16078
16814
|
}
|
|
16079
16815
|
canHandle(url) {
|
|
16080
16816
|
return url.startsWith("file://");
|
|
16081
16817
|
}
|
|
16082
16818
|
async processItem(item, options, _signal) {
|
|
16083
|
-
|
|
16084
|
-
|
|
16085
|
-
|
|
16086
|
-
|
|
16087
|
-
|
|
16819
|
+
const resolvedAccess = await this.accessPolicy.resolveFileAccess(
|
|
16820
|
+
item.url,
|
|
16821
|
+
options.internalAllowedFileRoots
|
|
16822
|
+
);
|
|
16823
|
+
const filePath = resolvedAccess.filePath;
|
|
16088
16824
|
let stats = null;
|
|
16089
16825
|
let archivePath = null;
|
|
16090
16826
|
let innerPath = null;
|
|
@@ -16114,16 +16850,25 @@ class LocalFileStrategy extends BaseScraperStrategy {
|
|
|
16114
16850
|
}
|
|
16115
16851
|
if (stats?.isDirectory()) {
|
|
16116
16852
|
const contents = await fs$1.readdir(filePath);
|
|
16117
|
-
const
|
|
16118
|
-
|
|
16119
|
-
|
|
16120
|
-
|
|
16121
|
-
|
|
16122
|
-
|
|
16123
|
-
|
|
16124
|
-
|
|
16125
|
-
|
|
16126
|
-
|
|
16853
|
+
const visibleContents = this.config.scraper.security.fileAccess.includeHidden ? contents : contents.filter((name) => !name.startsWith("."));
|
|
16854
|
+
const linkEntries = await Promise.all(
|
|
16855
|
+
visibleContents.map(async (name) => {
|
|
16856
|
+
const entryPath = path.join(filePath, name);
|
|
16857
|
+
if (!this.config.scraper.security.fileAccess.followSymlinks) {
|
|
16858
|
+
const entryStats = await fs$1.lstat(entryPath).catch(() => null);
|
|
16859
|
+
if (entryStats?.isSymbolicLink()) {
|
|
16860
|
+
return null;
|
|
16861
|
+
}
|
|
16862
|
+
}
|
|
16863
|
+
const url = new URL(`file://${entryPath.replace(/\\/g, "/")}`);
|
|
16864
|
+
if (url.hostname !== "") {
|
|
16865
|
+
url.pathname = `/${url.hostname}${url.pathname}`;
|
|
16866
|
+
url.hostname = "";
|
|
16867
|
+
}
|
|
16868
|
+
return url.href;
|
|
16869
|
+
})
|
|
16870
|
+
);
|
|
16871
|
+
const links = linkEntries.filter((url) => Boolean(url)).filter((url) => {
|
|
16127
16872
|
const allowed = this.shouldProcessUrl(url, options);
|
|
16128
16873
|
if (!allowed) {
|
|
16129
16874
|
logger.debug(`Skipping out-of-scope link: ${url}`);
|
|
@@ -16131,7 +16876,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
|
|
|
16131
16876
|
return allowed;
|
|
16132
16877
|
});
|
|
16133
16878
|
logger.debug(
|
|
16134
|
-
`Found ${links.length} files in ${filePath} (from ${
|
|
16879
|
+
`Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`
|
|
16135
16880
|
);
|
|
16136
16881
|
return { url: item.url, links, status: FetchStatus.SUCCESS };
|
|
16137
16882
|
}
|
|
@@ -16153,7 +16898,7 @@ class LocalFileStrategy extends BaseScraperStrategy {
|
|
|
16153
16898
|
virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;
|
|
16154
16899
|
virtualUrl.hostname = "";
|
|
16155
16900
|
}
|
|
16156
|
-
if (this.shouldProcessUrl(virtualUrl.href, options)) {
|
|
16901
|
+
if (this.shouldProcessUrl(virtualUrl.href, options) && this.isVisibleArchiveEntry(entry.path)) {
|
|
16157
16902
|
links.push(virtualUrl.href);
|
|
16158
16903
|
}
|
|
16159
16904
|
}
|
|
@@ -16221,6 +16966,12 @@ class LocalFileStrategy extends BaseScraperStrategy {
|
|
|
16221
16966
|
}
|
|
16222
16967
|
return { archive: null, inner: null, adapter: null };
|
|
16223
16968
|
}
|
|
16969
|
+
isVisibleArchiveEntry(entryPath) {
|
|
16970
|
+
if (this.config.scraper.security.fileAccess.includeHidden) {
|
|
16971
|
+
return true;
|
|
16972
|
+
}
|
|
16973
|
+
return !entryPath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
|
|
16974
|
+
}
|
|
16224
16975
|
async processArchiveEntry(item, archivePath, innerPath, adapter, options) {
|
|
16225
16976
|
logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);
|
|
16226
16977
|
try {
|
|
@@ -16301,6 +17052,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
|
|
|
16301
17052
|
pipelines;
|
|
16302
17053
|
localFileStrategy;
|
|
16303
17054
|
tempFiles = [];
|
|
17055
|
+
siblingwiseRedirectWarned = false;
|
|
16304
17056
|
constructor(config, options = {}) {
|
|
16305
17057
|
super(config, { urlNormalizerOptions: options.urlNormalizerOptions });
|
|
16306
17058
|
this.shouldFollowLinkFn = options.shouldFollowLink;
|
|
@@ -16359,8 +17111,9 @@ class WebScraperStrategy extends BaseScraperStrategy {
|
|
|
16359
17111
|
followRedirects: options.followRedirects,
|
|
16360
17112
|
headers: options.headers,
|
|
16361
17113
|
// Forward custom headers
|
|
16362
|
-
etag: item.etag
|
|
17114
|
+
etag: item.etag,
|
|
16363
17115
|
// Pass ETag for conditional requests
|
|
17116
|
+
...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
|
|
16364
17117
|
};
|
|
16365
17118
|
const rawContent = await this.fetcher.fetch(url, fetchOptions);
|
|
16366
17119
|
const effectiveSource = options.preserveHashes ? this.restorePreservedHash(url, rawContent.source) : rawContent.source;
|
|
@@ -16406,7 +17159,20 @@ class WebScraperStrategy extends BaseScraperStrategy {
|
|
|
16406
17159
|
};
|
|
16407
17160
|
}
|
|
16408
17161
|
if (item.depth === 0) {
|
|
16409
|
-
|
|
17162
|
+
const final = new URL(effectiveSource);
|
|
17163
|
+
const userPath = new URL(options.url).pathname;
|
|
17164
|
+
if (isPathDescendant(userPath, final.pathname)) {
|
|
17165
|
+
this.canonicalBaseUrl = final;
|
|
17166
|
+
} else {
|
|
17167
|
+
if (!this.siblingwiseRedirectWarned) {
|
|
17168
|
+
logger.warn(
|
|
17169
|
+
`⚠️ Depth-0 redirect changed path siblingwise. Scope anchor remains the user-provided path; discovered links under the redirected path will not be in scope. Requested: ${options.url} → Final: ${effectiveSource} → Scope anchor: ${userPath}. If the redirected path is intended, resubmit with that URL.`
|
|
17170
|
+
);
|
|
17171
|
+
this.siblingwiseRedirectWarned = true;
|
|
17172
|
+
}
|
|
17173
|
+
final.pathname = userPath;
|
|
17174
|
+
this.canonicalBaseUrl = final;
|
|
17175
|
+
}
|
|
16410
17176
|
}
|
|
16411
17177
|
const filteredLinks = processed.links?.filter((link) => {
|
|
16412
17178
|
try {
|
|
@@ -16460,11 +17226,21 @@ class WebScraperStrategy extends BaseScraperStrategy {
|
|
|
16460
17226
|
await fs$1.writeFile(tempFile, buffer);
|
|
16461
17227
|
const localUrl = `file://${tempFile}`;
|
|
16462
17228
|
const localItem = { ...item, url: localUrl };
|
|
16463
|
-
const
|
|
17229
|
+
const localOptions = {
|
|
17230
|
+
...options,
|
|
17231
|
+
internalAllowedFileRoots: [...options.internalAllowedFileRoots ?? [], tempFile]
|
|
17232
|
+
};
|
|
17233
|
+
const result = await this.localFileStrategy.processItem(
|
|
17234
|
+
localItem,
|
|
17235
|
+
localOptions,
|
|
17236
|
+
signal
|
|
17237
|
+
);
|
|
16464
17238
|
return {
|
|
16465
17239
|
...result,
|
|
16466
|
-
url: item.url
|
|
17240
|
+
url: item.url,
|
|
16467
17241
|
// Keep original URL as the source of this item
|
|
17242
|
+
links: result.links,
|
|
17243
|
+
internalAllowedFileRoots: [tempFile]
|
|
16468
17244
|
// links are file://...
|
|
16469
17245
|
};
|
|
16470
17246
|
}
|
|
@@ -18500,7 +19276,7 @@ function createCli(argv) {
|
|
|
18500
19276
|
let globalEventBus = null;
|
|
18501
19277
|
let globalTelemetryService = null;
|
|
18502
19278
|
const commandStartTimes = /* @__PURE__ */ new Map();
|
|
18503
|
-
const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.
|
|
19279
|
+
const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.3.0").option("verbose", {
|
|
18504
19280
|
type: "boolean",
|
|
18505
19281
|
description: "Enable verbose (debug) logging",
|
|
18506
19282
|
default: false
|
|
@@ -18561,7 +19337,7 @@ function createCli(argv) {
|
|
|
18561
19337
|
if (shouldEnableTelemetry() && telemetry.isEnabled()) {
|
|
18562
19338
|
const commandName = argv2._[0]?.toString() || "default";
|
|
18563
19339
|
telemetry.setGlobalContext({
|
|
18564
|
-
appVersion: "2.
|
|
19340
|
+
appVersion: "2.3.0",
|
|
18565
19341
|
appPlatform: process.platform,
|
|
18566
19342
|
appNodeVersion: process.version,
|
|
18567
19343
|
appInterface: "cli",
|
|
@@ -18707,4 +19483,4 @@ export {
|
|
|
18707
19483
|
cleanupCliCommand,
|
|
18708
19484
|
runCli
|
|
18709
19485
|
};
|
|
18710
|
-
//# sourceMappingURL=main-
|
|
19486
|
+
//# sourceMappingURL=main-CCLTqj8g.js.map
|