@nitpicker/crawler 0.22.2 → 0.24.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/lib/archive/archive.d.ts +13 -5
- package/lib/archive/archive.js +16 -7
- package/lib/archive/cache/extract-archive-to-cache.d.ts +6 -1
- package/lib/archive/cache/extract-archive-to-cache.js +13 -6
- package/lib/archive/create-adjunct-tables.d.ts +0 -7
- package/lib/archive/create-adjunct-tables.js +0 -50
- package/lib/archive/create-template-tables.d.ts +30 -0
- package/lib/archive/create-template-tables.js +95 -0
- package/lib/archive/database.d.ts +1 -1
- package/lib/archive/database.js +1 -1
- package/lib/archive/db-ops/config/get-config.d.ts +1 -1
- package/lib/archive/db-ops/config/get-config.js +2 -1
- package/lib/archive/db-ops/config/info-column-allowlist.js +1 -0
- package/lib/archive/db-ops/config/info-json-columns.js +1 -0
- package/lib/archive/db-ops/lifecycle/init.js +2 -0
- package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
- package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
- package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
- package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
- package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
- package/lib/archive/init-schema.d.ts +5 -1
- package/lib/archive/init-schema.js +14 -2
- package/lib/archive/migrate-info-request-header-names.d.ts +16 -0
- package/lib/archive/migrate-info-request-header-names.js +35 -0
- package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
- package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
- package/lib/archive/transfer/attach-source-database.d.ts +31 -0
- package/lib/archive/transfer/attach-source-database.js +40 -0
- package/lib/archive/transfer/build-split-config.d.ts +30 -0
- package/lib/archive/transfer/build-split-config.js +42 -0
- package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
- package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
- package/lib/archive/transfer/concat-archives.d.ts +55 -0
- package/lib/archive/transfer/concat-archives.js +95 -0
- package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
- package/lib/archive/transfer/content-item-rank-sql.js +23 -0
- package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
- package/lib/archive/transfer/copy-analysis-violations.js +43 -0
- package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
- package/lib/archive/transfer/copy-anchor-edges.js +42 -0
- package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
- package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
- package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
- package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
- package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
- package/lib/archive/transfer/copy-header-set-children.js +51 -0
- package/lib/archive/transfer/copy-image-items.d.ts +21 -0
- package/lib/archive/transfer/copy-image-items.js +62 -0
- package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
- package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
- package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
- package/lib/archive/transfer/copy-journal-tables.js +56 -0
- package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
- package/lib/archive/transfer/copy-page-console-logs.js +27 -0
- package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
- package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
- package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
- package/lib/archive/transfer/copy-page-meta.js +68 -0
- package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
- package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
- package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
- package/lib/archive/transfer/copy-page-template-labels.js +88 -0
- package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
- package/lib/archive/transfer/copy-resource-items.js +89 -0
- package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
- package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
- package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
- package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
- package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
- package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
- package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
- package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
- package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
- package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
- package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
- package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
- package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
- package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
- package/lib/archive/transfer/insert-content-items.d.ts +35 -0
- package/lib/archive/transfer/insert-content-items.js +116 -0
- package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
- package/lib/archive/transfer/list-transfer-columns.js +45 -0
- package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
- package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
- package/lib/archive/transfer/merge-archive-configs.d.ts +51 -0
- package/lib/archive/transfer/merge-archive-configs.js +85 -0
- package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
- package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
- package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
- package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
- package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
- package/lib/archive/transfer/plan-resource-items.js +69 -0
- package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
- package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
- package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
- package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
- package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
- package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
- package/lib/archive/transfer/replace-content-items.d.ts +39 -0
- package/lib/archive/transfer/replace-content-items.js +83 -0
- package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
- package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
- package/lib/archive/transfer/split-archive.d.ts +55 -0
- package/lib/archive/transfer/split-archive.js +98 -0
- package/lib/archive/transfer/transfer-action.d.ts +34 -0
- package/lib/archive/transfer/transfer-action.js +32 -0
- package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
- package/lib/archive/transfer/transfer-archive-rows.js +158 -0
- package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
- package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
- package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
- package/lib/archive/transfer/transfer-source-alias.js +9 -0
- package/lib/archive/transfer/types.d.ts +111 -0
- package/lib/archive/transfer/types.js +35 -0
- package/lib/archive/types.d.ts +10 -0
- package/lib/concat-source-transfer-phases.d.ts +10 -0
- package/lib/concat-source-transfer-phases.js +17 -0
- package/lib/crawler/apply-request-header-interception.d.ts +22 -0
- package/lib/crawler/apply-request-header-interception.js +28 -0
- package/lib/crawler/build-scope-map.d.ts +21 -0
- package/lib/crawler/build-scope-map.js +32 -0
- package/lib/crawler/crawler.js +34 -0
- package/lib/crawler/create-scoped-header-request-handler.d.ts +40 -0
- package/lib/crawler/create-scoped-header-request-handler.js +64 -0
- package/lib/crawler/create-strip-headers-on-redirect.d.ts +41 -0
- package/lib/crawler/create-strip-headers-on-redirect.js +67 -0
- package/lib/crawler/fetch-destination.d.ts +14 -0
- package/lib/crawler/fetch-destination.js +56 -9
- package/lib/crawler/fetch-robots-txt.d.ts +7 -0
- package/lib/crawler/fetch-robots-txt.js +7 -0
- package/lib/crawler/scan-js-resource-for-license-comment.d.ts +6 -0
- package/lib/crawler/scan-js-resource-for-license-comment.js +6 -0
- package/lib/crawler/types.d.ts +44 -0
- package/lib/crawler-orchestrator.d.ts +6 -0
- package/lib/crawler-orchestrator.js +17 -17
- package/lib/crawler.d.ts +14 -1
- package/lib/crawler.js +23 -0
- package/lib/split-source-transfer-phases.d.ts +11 -0
- package/lib/split-source-transfer-phases.js +18 -0
- package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
- package/lib/template-classification/classify-archive-page-templates.js +79 -0
- package/lib/template-classification/classify-page-templates.d.ts +37 -0
- package/lib/template-classification/classify-page-templates.js +69 -0
- package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
- package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
- package/lib/template-classification/create-content-root-hint.d.ts +36 -0
- package/lib/template-classification/create-content-root-hint.js +47 -0
- package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
- package/lib/template-classification/create-page-cluster-factory.js +98 -0
- package/lib/template-classification/types.d.ts +108 -0
- package/lib/template-classification/types.js +1 -0
- package/lib/transfer-post-phases.d.ts +10 -0
- package/lib/transfer-post-phases.js +13 -0
- package/lib/utils/object/redact-request-headers.d.ts +15 -0
- package/lib/utils/object/redact-request-headers.js +27 -0
- package/package.json +4 -3
- package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
- /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
package/lib/crawler/crawler.js
CHANGED
|
@@ -12,6 +12,7 @@ import { computeBodyHash } from '../archive/body-hash/compute-body-hash.js';
|
|
|
12
12
|
import { classifyErrorKind } from '../classify-error-kind.js';
|
|
13
13
|
import { crawlerLog } from '../debug.js';
|
|
14
14
|
import { applyCrawlRuntimeOptionsPatch } from './apply-crawl-runtime-options-patch.js';
|
|
15
|
+
import { applyRequestHeaderInterception } from './apply-request-header-interception.js';
|
|
15
16
|
import { buildJsRedirectEdge } from './build-js-redirect-edge.js';
|
|
16
17
|
import { buildRedirectEvent } from './build-redirect-event.js';
|
|
17
18
|
import { captureCustomElements } from './capture-custom-elements.js';
|
|
@@ -270,6 +271,7 @@ export default class Crawler extends EventEmitter {
|
|
|
270
271
|
disableQueries: options?.disableQueries ?? false,
|
|
271
272
|
verbose: options?.verbose ?? false,
|
|
272
273
|
userAgent: options?.userAgent || `Nitpicker/${pkg.version}`,
|
|
274
|
+
requestHeaders: options?.requestHeaders,
|
|
273
275
|
ignoreRobots: options?.ignoreRobots ?? false,
|
|
274
276
|
mainContentSelector: options?.mainContentSelector ?? null,
|
|
275
277
|
lookupResource: options?.lookupResource ?? null,
|
|
@@ -898,6 +900,19 @@ export default class Crawler extends EventEmitter {
|
|
|
898
900
|
}
|
|
899
901
|
}
|
|
900
902
|
}
|
|
903
|
+
/**
|
|
904
|
+
* Whether an absolute URL falls inside the crawl scope. The predicate
|
|
905
|
+
* behind every "may the extra request headers go here?" decision: HEAD/GET
|
|
906
|
+
* redirect hops and the browser's per-request interception both use it, so
|
|
907
|
+
* there is a single definition of the boundary (`findScopeEntry`).
|
|
908
|
+
* An unparseable URL is treated as out of scope (fail closed).
|
|
909
|
+
* @param href - Absolute URL to classify.
|
|
910
|
+
* @returns `true` when the URL belongs to a scope entry.
|
|
911
|
+
*/
|
|
912
|
+
#isInScope(href) {
|
|
913
|
+
const parsed = parseUrl(href);
|
|
914
|
+
return parsed !== null && findScopeEntry(parsed, this.#scope, this.#options) !== null;
|
|
915
|
+
}
|
|
901
916
|
/**
|
|
902
917
|
* Undo cache damage from the outage window `[startedAt, endedAt]`:
|
|
903
918
|
* evict `destinationCache` entries whose cached error looks
|
|
@@ -1715,6 +1730,8 @@ export default class Crawler extends EventEmitter {
|
|
|
1715
1730
|
method: 'GET',
|
|
1716
1731
|
options: { titleBytesLimit: 16_384 },
|
|
1717
1732
|
userAgent: this.#options.userAgent,
|
|
1733
|
+
requestHeaders: this.#options.requestHeaders,
|
|
1734
|
+
isInScope: (href) => this.#isInScope(href),
|
|
1718
1735
|
});
|
|
1719
1736
|
return {
|
|
1720
1737
|
type: 'success',
|
|
@@ -1911,6 +1928,8 @@ export default class Crawler extends EventEmitter {
|
|
|
1911
1928
|
url,
|
|
1912
1929
|
isExternal,
|
|
1913
1930
|
userAgent: this.#options.userAgent,
|
|
1931
|
+
requestHeaders: this.#options.requestHeaders,
|
|
1932
|
+
isInScope: (href) => this.#isInScope(href),
|
|
1914
1933
|
timeout: timeoutMs,
|
|
1915
1934
|
});
|
|
1916
1935
|
// Mark host alive the MOMENT an HTTP response is observed,
|
|
@@ -2005,6 +2024,21 @@ export default class Crawler extends EventEmitter {
|
|
|
2005
2024
|
update('Creating page%dots%');
|
|
2006
2025
|
page = await browser.newPage();
|
|
2007
2026
|
await page.setUserAgent(this.#options.userAgent);
|
|
2027
|
+
// Extra request headers (`--header` / `--authorization`) ride on a
|
|
2028
|
+
// per-request interception, NOT `page.setExtraHTTPHeaders`: the latter
|
|
2029
|
+
// stamps every request the page issues — third-party sub-resources and
|
|
2030
|
+
// external redirect targets included — and would hand a bearer token to
|
|
2031
|
+
// every CDN the page touches. Interception is enabled only when headers
|
|
2032
|
+
// were given AND the page is in scope: an external page has nothing in
|
|
2033
|
+
// scope to attach to, so interception would only add a CDP round-trip
|
|
2034
|
+
// per request.
|
|
2035
|
+
if (!isExternal) {
|
|
2036
|
+
await applyRequestHeaderInterception(page, {
|
|
2037
|
+
requestHeaders: this.#options.requestHeaders,
|
|
2038
|
+
isInScope: (href) => this.#isInScope(href),
|
|
2039
|
+
onError: (error) => crawlerLog('Request header interception failed: %O', error),
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2008
2042
|
// HTTP-auth handling — two cooperating pieces, BOTH required:
|
|
2009
2043
|
//
|
|
2010
2044
|
// 1. `page.authenticate({user, pass})` (always, even with empty
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { CreateScopedHeaderRequestHandlerParams } from './types.js';
|
|
2
|
+
import type { HTTPRequest } from 'puppeteer';
|
|
3
|
+
/**
|
|
4
|
+
* Builds the Puppeteer `'request'` handler that attaches the user-supplied
|
|
5
|
+
* extra headers to in-scope requests only. It is meant for a page that has
|
|
6
|
+
* `setRequestInterception(true)`.
|
|
7
|
+
*
|
|
8
|
+
* WHY not `page.setExtraHTTPHeaders`: that applies to every request the page
|
|
9
|
+
* issues — third-party sub-resources and external redirect targets included —
|
|
10
|
+
* which would hand a bearer token to every CDN and analytics host the page
|
|
11
|
+
* touches. Deciding per request URL keeps the credential inside the scope
|
|
12
|
+
* (the same boundary `scope-auth-leak.e2e.ts` guards for Basic auth).
|
|
13
|
+
*
|
|
14
|
+
* Header names are matched case-insensitively. `request.headers()` returns
|
|
15
|
+
* lower-case keys, so a naive object spread would send both `authorization`
|
|
16
|
+
* (the page's own) and `Authorization` (the override) and the server would
|
|
17
|
+
* see a comma-joined value.
|
|
18
|
+
*
|
|
19
|
+
* An out-of-scope request has the configured header names removed, not just
|
|
20
|
+
* left unset: a redirect hop can inherit the headers an earlier in-scope hop
|
|
21
|
+
* was continued with, and `request.headers()` then still carries them.
|
|
22
|
+
*
|
|
23
|
+
* Each request is explicitly continued: once interception is on, an
|
|
24
|
+
* unhandled request hangs. A request another handler already resolved is left
|
|
25
|
+
* alone. If `continue()` itself rejects (Chromium refusing a header), the
|
|
26
|
+
* request is aborted rather than left hanging, and `onError` is told — an
|
|
27
|
+
* unhandled rejection here would take the whole crawl down.
|
|
28
|
+
* @param params - Headers to attach, the scope predicate and an optional error sink.
|
|
29
|
+
* @returns The handler to register with `page.on('request', handler)`.
|
|
30
|
+
* @example
|
|
31
|
+
* await page.setRequestInterception(true);
|
|
32
|
+
* page.on(
|
|
33
|
+
* 'request',
|
|
34
|
+
* createScopedHeaderRequestHandler({
|
|
35
|
+
* requestHeaders: { Authorization: 'Bearer token' },
|
|
36
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
37
|
+
* }),
|
|
38
|
+
* );
|
|
39
|
+
*/
|
|
40
|
+
export declare function createScopedHeaderRequestHandler(params: CreateScopedHeaderRequestHandlerParams): (request: HTTPRequest) => void;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the Puppeteer `'request'` handler that attaches the user-supplied
|
|
3
|
+
* extra headers to in-scope requests only. It is meant for a page that has
|
|
4
|
+
* `setRequestInterception(true)`.
|
|
5
|
+
*
|
|
6
|
+
* WHY not `page.setExtraHTTPHeaders`: that applies to every request the page
|
|
7
|
+
* issues — third-party sub-resources and external redirect targets included —
|
|
8
|
+
* which would hand a bearer token to every CDN and analytics host the page
|
|
9
|
+
* touches. Deciding per request URL keeps the credential inside the scope
|
|
10
|
+
* (the same boundary `scope-auth-leak.e2e.ts` guards for Basic auth).
|
|
11
|
+
*
|
|
12
|
+
* Header names are matched case-insensitively. `request.headers()` returns
|
|
13
|
+
* lower-case keys, so a naive object spread would send both `authorization`
|
|
14
|
+
* (the page's own) and `Authorization` (the override) and the server would
|
|
15
|
+
* see a comma-joined value.
|
|
16
|
+
*
|
|
17
|
+
* An out-of-scope request has the configured header names removed, not just
|
|
18
|
+
* left unset: a redirect hop can inherit the headers an earlier in-scope hop
|
|
19
|
+
* was continued with, and `request.headers()` then still carries them.
|
|
20
|
+
*
|
|
21
|
+
* Each request is explicitly continued: once interception is on, an
|
|
22
|
+
* unhandled request hangs. A request another handler already resolved is left
|
|
23
|
+
* alone. If `continue()` itself rejects (Chromium refusing a header), the
|
|
24
|
+
* request is aborted rather than left hanging, and `onError` is told — an
|
|
25
|
+
* unhandled rejection here would take the whole crawl down.
|
|
26
|
+
* @param params - Headers to attach, the scope predicate and an optional error sink.
|
|
27
|
+
* @returns The handler to register with `page.on('request', handler)`.
|
|
28
|
+
* @example
|
|
29
|
+
* await page.setRequestInterception(true);
|
|
30
|
+
* page.on(
|
|
31
|
+
* 'request',
|
|
32
|
+
* createScopedHeaderRequestHandler({
|
|
33
|
+
* requestHeaders: { Authorization: 'Bearer token' },
|
|
34
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
35
|
+
* }),
|
|
36
|
+
* );
|
|
37
|
+
*/
|
|
38
|
+
export function createScopedHeaderRequestHandler(params) {
|
|
39
|
+
const lowerNames = new Set(Object.keys(params.requestHeaders).map((n) => n.toLowerCase()));
|
|
40
|
+
return (request) => {
|
|
41
|
+
if (request.isInterceptResolutionHandled()) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const headers = request.headers();
|
|
45
|
+
const stripped = Object.fromEntries(Object.entries(headers).filter(([key]) => !lowerNames.has(key.toLowerCase())));
|
|
46
|
+
const inherited = Object.keys(stripped).length !== Object.keys(headers).length;
|
|
47
|
+
let settled;
|
|
48
|
+
if (params.isInScope(request.url())) {
|
|
49
|
+
settled = request.continue({ headers: { ...stripped, ...params.requestHeaders } });
|
|
50
|
+
}
|
|
51
|
+
else if (inherited) {
|
|
52
|
+
settled = request.continue({ headers: stripped });
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
settled = request.continue();
|
|
56
|
+
}
|
|
57
|
+
settled.catch(async (error) => {
|
|
58
|
+
params.onError?.(error);
|
|
59
|
+
if (!request.isInterceptResolutionHandled()) {
|
|
60
|
+
await request.abort('failed').catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { CreateStripHeadersOnRedirectParams } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The slice of `follow-redirects`' per-hop request options this module reads
|
|
4
|
+
* and mutates. `follow-redirects` hands `beforeRedirect` its internal
|
|
5
|
+
* options object, already rewritten for the next hop.
|
|
6
|
+
*/
|
|
7
|
+
interface RedirectHopOptions {
|
|
8
|
+
href?: string;
|
|
9
|
+
protocol?: string | null;
|
|
10
|
+
hostname?: string | null;
|
|
11
|
+
port?: string | number | null;
|
|
12
|
+
path?: string | null;
|
|
13
|
+
headers?: Record<string, unknown> | readonly string[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Builds the `beforeRedirect` hook for `follow-redirects` that removes the
|
|
17
|
+
* user-supplied extra request headers when a redirect leaves the crawl scope.
|
|
18
|
+
*
|
|
19
|
+
* WHY: `follow-redirects` only drops `Authorization` / `Cookie` when the
|
|
20
|
+
* redirect crosses to another host (or downgrades https → http); it keeps any
|
|
21
|
+
* custom header (`X-Api-Key`, …) and it keeps `Authorization` for a different
|
|
22
|
+
* path on the same host. A scope is a `(hostname, port, path)` triple, so an
|
|
23
|
+
* in-scope URL can redirect to an out-of-scope path or port that the scope
|
|
24
|
+
* rule must still treat as external. Judging each hop with the same scope
|
|
25
|
+
* predicate the rest of the crawler uses keeps a single definition of
|
|
26
|
+
* "where credentials may go".
|
|
27
|
+
*
|
|
28
|
+
* Once stripped, a header is not restored even if a later hop re-enters the
|
|
29
|
+
* scope: the request has already been observed by an out-of-scope party.
|
|
30
|
+
* @param params - Header names to drop and the scope predicate.
|
|
31
|
+
* @returns A hook to assign to the request options' `beforeRedirect`.
|
|
32
|
+
* @example
|
|
33
|
+
* const request = {
|
|
34
|
+
* beforeRedirect: createStripHeadersOnRedirect({
|
|
35
|
+
* headerNames: ['Authorization'],
|
|
36
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
37
|
+
* }),
|
|
38
|
+
* };
|
|
39
|
+
*/
|
|
40
|
+
export declare function createStripHeadersOnRedirect(params: CreateStripHeadersOnRedirectParams): (options: RedirectHopOptions) => void;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the `beforeRedirect` hook for `follow-redirects` that removes the
|
|
3
|
+
* user-supplied extra request headers when a redirect leaves the crawl scope.
|
|
4
|
+
*
|
|
5
|
+
* WHY: `follow-redirects` only drops `Authorization` / `Cookie` when the
|
|
6
|
+
* redirect crosses to another host (or downgrades https → http); it keeps any
|
|
7
|
+
* custom header (`X-Api-Key`, …) and it keeps `Authorization` for a different
|
|
8
|
+
* path on the same host. A scope is a `(hostname, port, path)` triple, so an
|
|
9
|
+
* in-scope URL can redirect to an out-of-scope path or port that the scope
|
|
10
|
+
* rule must still treat as external. Judging each hop with the same scope
|
|
11
|
+
* predicate the rest of the crawler uses keeps a single definition of
|
|
12
|
+
* "where credentials may go".
|
|
13
|
+
*
|
|
14
|
+
* Once stripped, a header is not restored even if a later hop re-enters the
|
|
15
|
+
* scope: the request has already been observed by an out-of-scope party.
|
|
16
|
+
* @param params - Header names to drop and the scope predicate.
|
|
17
|
+
* @returns A hook to assign to the request options' `beforeRedirect`.
|
|
18
|
+
* @example
|
|
19
|
+
* const request = {
|
|
20
|
+
* beforeRedirect: createStripHeadersOnRedirect({
|
|
21
|
+
* headerNames: ['Authorization'],
|
|
22
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
23
|
+
* }),
|
|
24
|
+
* };
|
|
25
|
+
*/
|
|
26
|
+
export function createStripHeadersOnRedirect(params) {
|
|
27
|
+
const lowerNames = new Set(params.headerNames.map((name) => name.toLowerCase()));
|
|
28
|
+
return (options) => {
|
|
29
|
+
const headers = options.headers;
|
|
30
|
+
// Node types `headers` as possibly a raw `string[]`; follow-redirects
|
|
31
|
+
// always hands over the object form this crawler built.
|
|
32
|
+
if (!headers || Array.isArray(headers)) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const href = resolveHopHref(options);
|
|
36
|
+
if (href !== null && params.isInScope(href)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const record = headers;
|
|
40
|
+
for (const key of Object.keys(record)) {
|
|
41
|
+
if (lowerNames.has(key.toLowerCase())) {
|
|
42
|
+
delete record[key];
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Reconstructs the absolute URL of a redirect hop. An unresolvable hop yields
|
|
49
|
+
* `null`, which the caller treats as out of scope (fail closed).
|
|
50
|
+
* @param options - The per-hop options `follow-redirects` passes in.
|
|
51
|
+
* @returns The absolute URL, or `null` when it cannot be determined.
|
|
52
|
+
*/
|
|
53
|
+
function resolveHopHref(options) {
|
|
54
|
+
if (options.href) {
|
|
55
|
+
return options.href;
|
|
56
|
+
}
|
|
57
|
+
if (!options.protocol || !options.hostname) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
const port = options.port ? `:${options.port}` : '';
|
|
61
|
+
// An IPv6 literal arrives unbracketed (`::1`); without brackets the rebuilt
|
|
62
|
+
// URL is unparseable and an in-scope hop would be judged external.
|
|
63
|
+
const host = options.hostname.includes(':')
|
|
64
|
+
? `[${options.hostname}]`
|
|
65
|
+
: options.hostname;
|
|
66
|
+
return `${options.protocol}//${host}${port}${options.path ?? '/'}`;
|
|
67
|
+
}
|
|
@@ -20,6 +20,20 @@ export interface FetchDestinationParams {
|
|
|
20
20
|
};
|
|
21
21
|
/** User-Agent string to send with the request. */
|
|
22
22
|
readonly userAgent?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Extra request headers (`--header` / `--authorization`) to send. Applied
|
|
25
|
+
* only when the URL is in scope (`isExternal === false`) and dropped again
|
|
26
|
+
* if a redirect leaves the scope (see `isInScope`). A header named
|
|
27
|
+
* `Authorization` wins over the Basic credentials embedded in the URL,
|
|
28
|
+
* because Node ignores `auth` when an `Authorization` header is present.
|
|
29
|
+
*/
|
|
30
|
+
readonly requestHeaders?: Readonly<Record<string, string>>;
|
|
31
|
+
/**
|
|
32
|
+
* Whether a redirect target (absolute URL) is inside the crawl scope.
|
|
33
|
+
* Required for `requestHeaders` to survive any redirect safely: when it is
|
|
34
|
+
* omitted, `requestHeaders` are stripped on every redirect hop (fail closed).
|
|
35
|
+
*/
|
|
36
|
+
readonly isInScope?: (href: string) => boolean;
|
|
23
37
|
/**
|
|
24
38
|
* Race timeout for the network request in milliseconds. Defaults to
|
|
25
39
|
* {@link DEFAULT_HEAD_TIMEOUT_MS} (10s). `Crawler.#sendHeadRequest` passes
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { delay } from '@d-zero/shared/delay';
|
|
2
2
|
import { raceWithTimeout } from '@d-zero/shared/race-with-timeout';
|
|
3
3
|
import redirects from 'follow-redirects';
|
|
4
|
+
import { createStripHeadersOnRedirect } from './create-strip-headers-on-redirect.js';
|
|
4
5
|
import { decodeAuthCredential } from './decode-auth-credential.js';
|
|
5
6
|
import { destinationCache } from './destination-cache.js';
|
|
6
7
|
import NetTimeoutError from './net-timeout-error.js';
|
|
@@ -23,7 +24,7 @@ const DEFAULT_HEAD_TIMEOUT_MS = 10 * 1000;
|
|
|
23
24
|
* @throws {Error} If the HTTP request fails for any other reason.
|
|
24
25
|
*/
|
|
25
26
|
export async function fetchDestination(params) {
|
|
26
|
-
const { url, isExternal, method = 'HEAD', options, userAgent, timeout } = params;
|
|
27
|
+
const { url, isExternal, method = 'HEAD', options, userAgent, requestHeaders, isInScope, timeout, } = params;
|
|
27
28
|
const titleBytesLimit = options?.titleBytesLimit;
|
|
28
29
|
const cacheKey = titleBytesLimit == null ? url.withoutHash : `${url.withoutHash}:title`;
|
|
29
30
|
if (destinationCache.has(cacheKey)) {
|
|
@@ -38,7 +39,16 @@ export async function fetchDestination(params) {
|
|
|
38
39
|
// Race the fetch against the requested timeout via `raceWithTimeout`, which
|
|
39
40
|
// clears the losing timer internally so it never keeps the event loop
|
|
40
41
|
// alive after the race settles.
|
|
41
|
-
const { result: challengeResult, timeout: timedOut } = await raceWithTimeout(() => _fetchHead(
|
|
42
|
+
const { result: challengeResult, timeout: timedOut } = await raceWithTimeout(() => _fetchHead({
|
|
43
|
+
url,
|
|
44
|
+
isExternal,
|
|
45
|
+
method: effectiveMethod,
|
|
46
|
+
titleBytesLimit,
|
|
47
|
+
userAgent,
|
|
48
|
+
requestHeaders,
|
|
49
|
+
isInScope,
|
|
50
|
+
timeout,
|
|
51
|
+
}).catch((error) => error instanceof Error ? error : new Error(String(error))), raceTimeoutMs);
|
|
42
52
|
const result = timedOut ? new NetTimeoutError(url.href) : challengeResult;
|
|
43
53
|
// HEAD failure fallback: a WAF / middlebox that silently drops HEAD will
|
|
44
54
|
// surface as NetTimeoutError / parse-error / connection-reset here even
|
|
@@ -55,6 +65,8 @@ export async function fetchDestination(params) {
|
|
|
55
65
|
isExternal,
|
|
56
66
|
method: 'GET',
|
|
57
67
|
userAgent,
|
|
68
|
+
requestHeaders,
|
|
69
|
+
isInScope,
|
|
58
70
|
timeout,
|
|
59
71
|
});
|
|
60
72
|
// GET succeeded — that is the canonical answer for this URL, so
|
|
@@ -95,17 +107,21 @@ export async function fetchDestination(params) {
|
|
|
95
107
|
*
|
|
96
108
|
* Handles both HTTP and HTTPS protocols via `follow-redirects`, tracks redirect chains,
|
|
97
109
|
* and falls back to GET on certain status codes (405, 501, 503).
|
|
98
|
-
* @param
|
|
99
|
-
* @param
|
|
100
|
-
* @param
|
|
101
|
-
* @param
|
|
110
|
+
* @param params - Request parameters.
|
|
111
|
+
* @param params.url - The extended URL to request.
|
|
112
|
+
* @param params.isExternal - Whether the URL is external to the crawl scope.
|
|
113
|
+
* @param params.method - The HTTP method (`"HEAD"` or `"GET"`).
|
|
114
|
+
* @param params.titleBytesLimit - When set, reads up to this many bytes from the response body
|
|
102
115
|
* to extract a `<title>` tag, then destroys the connection.
|
|
103
|
-
* @param userAgent - Optional User-Agent string to send with the request.
|
|
104
|
-
* @param
|
|
116
|
+
* @param params.userAgent - Optional User-Agent string to send with the request.
|
|
117
|
+
* @param params.requestHeaders - Optional extra headers, sent only for in-scope URLs.
|
|
118
|
+
* @param params.isInScope - Scope predicate used to drop `requestHeaders` on out-of-scope redirects.
|
|
119
|
+
* @param params.timeout - Optional race timeout in ms, forwarded to GET fallback so the
|
|
105
120
|
* second pass keeps the same budget as the original HEAD attempt.
|
|
106
121
|
* @returns A promise resolving to {@link PageData} with response metadata.
|
|
107
122
|
*/
|
|
108
|
-
async function _fetchHead(
|
|
123
|
+
async function _fetchHead(params) {
|
|
124
|
+
const { url, isExternal, method, titleBytesLimit, userAgent, requestHeaders, isInScope, timeout, } = params;
|
|
109
125
|
return new Promise((resolve, reject) => {
|
|
110
126
|
const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
|
|
111
127
|
// `trackRedirects` makes follow-redirects populate `res.redirects` with the
|
|
@@ -148,6 +164,28 @@ async function _fetchHead(url, isExternal, method, titleBytesLimit, userAgent, t
|
|
|
148
164
|
// `http.request(url)` (see `decode-auth-credential.ts`).
|
|
149
165
|
request.auth = `${decodeAuthCredential(url.username)}:${decodeAuthCredential(url.password)}`;
|
|
150
166
|
}
|
|
167
|
+
// Extra headers are a scope-bound credential: never sent to an external
|
|
168
|
+
// URL, and dropped again if a redirect hop leaves the scope. Applied after
|
|
169
|
+
// `request.auth` is set so the explicit `Authorization` header wins.
|
|
170
|
+
const extraHeaderNames = requestHeaders ? Object.keys(requestHeaders) : [];
|
|
171
|
+
if (!isExternal && requestHeaders && extraHeaderNames.length > 0) {
|
|
172
|
+
// Case-insensitive replace: the base headers use fixed casings
|
|
173
|
+
// (`Accept`, `User-Agent`), so a plain `Object.assign` of `accept`
|
|
174
|
+
// would leave both keys and Node would send both.
|
|
175
|
+
// The object literal above is always the plain-object form, never `string[]`.
|
|
176
|
+
const baseHeaders = request.headers;
|
|
177
|
+
const overridden = new Set(extraHeaderNames.map((name) => name.toLowerCase()));
|
|
178
|
+
for (const key of Object.keys(baseHeaders)) {
|
|
179
|
+
if (overridden.has(key.toLowerCase())) {
|
|
180
|
+
delete baseHeaders[key];
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
Object.assign(baseHeaders, requestHeaders);
|
|
184
|
+
request.beforeRedirect = createStripHeadersOnRedirect({
|
|
185
|
+
headerNames: extraHeaderNames,
|
|
186
|
+
isInScope: isInScope ?? (() => false),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
151
189
|
let req;
|
|
152
190
|
let destroyed = false;
|
|
153
191
|
const response = (res) => {
|
|
@@ -226,6 +264,9 @@ async function _fetchHead(url, isExternal, method, titleBytesLimit, userAgent, t
|
|
|
226
264
|
url,
|
|
227
265
|
isExternal,
|
|
228
266
|
method: 'GET',
|
|
267
|
+
userAgent,
|
|
268
|
+
requestHeaders,
|
|
269
|
+
isInScope,
|
|
229
270
|
timeout,
|
|
230
271
|
});
|
|
231
272
|
}
|
|
@@ -247,6 +288,9 @@ async function _fetchHead(url, isExternal, method, titleBytesLimit, userAgent, t
|
|
|
247
288
|
url,
|
|
248
289
|
isExternal,
|
|
249
290
|
method: 'GET',
|
|
291
|
+
userAgent,
|
|
292
|
+
requestHeaders,
|
|
293
|
+
isInScope,
|
|
250
294
|
timeout,
|
|
251
295
|
});
|
|
252
296
|
}
|
|
@@ -271,6 +315,9 @@ async function _fetchHead(url, isExternal, method, titleBytesLimit, userAgent, t
|
|
|
271
315
|
url,
|
|
272
316
|
isExternal,
|
|
273
317
|
method: 'GET',
|
|
318
|
+
userAgent,
|
|
319
|
+
requestHeaders,
|
|
320
|
+
isInScope,
|
|
274
321
|
timeout,
|
|
275
322
|
});
|
|
276
323
|
}
|
|
@@ -31,6 +31,13 @@ interface RobotsResult {
|
|
|
31
31
|
/**
|
|
32
32
|
* Fetches and parses the robots.txt file for a given origin URL.
|
|
33
33
|
*
|
|
34
|
+
* Deliberately sends neither the user's extra request headers
|
|
35
|
+
* (`--header` / `--authorization`) nor Basic credentials: robots.txt is
|
|
36
|
+
* fetched per origin (external ones included), and a credential must stay
|
|
37
|
+
* inside the crawl scope. A protected site that answers 401 here is read as
|
|
38
|
+
* "no robots.txt" — everything allowed — which is the existing behaviour for
|
|
39
|
+
* a missing file.
|
|
40
|
+
*
|
|
34
41
|
* Sends an HTTP(S) GET request to `{origin}/robots.txt` and parses the
|
|
35
42
|
* response using `robots-parser`. Returns `null` if the server returns
|
|
36
43
|
* a non-200 status code or if the request fails.
|
|
@@ -5,6 +5,13 @@ const robotsParser = require('robots-parser');
|
|
|
5
5
|
/**
|
|
6
6
|
* Fetches and parses the robots.txt file for a given origin URL.
|
|
7
7
|
*
|
|
8
|
+
* Deliberately sends neither the user's extra request headers
|
|
9
|
+
* (`--header` / `--authorization`) nor Basic credentials: robots.txt is
|
|
10
|
+
* fetched per origin (external ones included), and a credential must stay
|
|
11
|
+
* inside the crawl scope. A protected site that answers 401 here is read as
|
|
12
|
+
* "no robots.txt" — everything allowed — which is the existing behaviour for
|
|
13
|
+
* a missing file.
|
|
14
|
+
*
|
|
8
15
|
* Sends an HTTP(S) GET request to `{origin}/robots.txt` and parses the
|
|
9
16
|
* response using `robots-parser`. Returns `null` if the server returns
|
|
10
17
|
* a non-200 status code or if the request fails.
|
|
@@ -17,6 +17,12 @@ export interface ScanJsResourceForLicenseCommentOptions {
|
|
|
17
17
|
* pass over the rest of the archive's resources (see
|
|
18
18
|
* `scanJsResourcesForTechnologySignals`, this function's only caller).
|
|
19
19
|
*
|
|
20
|
+
* Deliberately sends no user-supplied request headers (`--header` /
|
|
21
|
+
* `--authorization`): the resources scanned here are archive-wide and include
|
|
22
|
+
* third-party hosts, so a scope-bound credential must not reach them. A JS
|
|
23
|
+
* file that is only readable with the header answers 401, resolves `null`,
|
|
24
|
+
* and is recorded as scanned-without-a-match.
|
|
25
|
+
*
|
|
20
26
|
* Not cached and not routed through `destinationCache` (unlike
|
|
21
27
|
* `fetchDestination`): callers are expected to persist the outcome in
|
|
22
28
|
* `technology_js_scan_cache`, keyed by `resourceId`, so a resource is never
|
|
@@ -16,6 +16,12 @@ const JS_LICENSE_COMMENT_DEFINITIONS = TECHNOLOGY_SIGNAL_DEFINITIONS.filter((def
|
|
|
16
16
|
* pass over the rest of the archive's resources (see
|
|
17
17
|
* `scanJsResourcesForTechnologySignals`, this function's only caller).
|
|
18
18
|
*
|
|
19
|
+
* Deliberately sends no user-supplied request headers (`--header` /
|
|
20
|
+
* `--authorization`): the resources scanned here are archive-wide and include
|
|
21
|
+
* third-party hosts, so a scope-bound credential must not reach them. A JS
|
|
22
|
+
* file that is only readable with the header answers 401, resolves `null`,
|
|
23
|
+
* and is recorded as scanned-without-a-match.
|
|
24
|
+
*
|
|
19
25
|
* Not cached and not routed through `destinationCache` (unlike
|
|
20
26
|
* `fetchDestination`): callers are expected to persist the outcome in
|
|
21
27
|
* `technology_js_scan_cache`, keyed by `resourceId`, so a resource is never
|
package/lib/crawler/types.d.ts
CHANGED
|
@@ -141,6 +141,15 @@ export interface CrawlerOptions extends Required<Pick<ParseURLOptions, 'disableQ
|
|
|
141
141
|
verbose: boolean;
|
|
142
142
|
/** User-Agent string sent with HTTP requests. */
|
|
143
143
|
userAgent: string;
|
|
144
|
+
/**
|
|
145
|
+
* Extra request headers (`--header` / `--authorization` / `--header-file`)
|
|
146
|
+
* attached to in-scope requests only — HEAD/GET pre-flights and the
|
|
147
|
+
* browser's page and sub-resource requests. Never sent to external URLs or
|
|
148
|
+
* to a redirect hop that leaves the scope, never persisted (only the names
|
|
149
|
+
* are, as `Config.requestHeaderNames`) and never logged (see
|
|
150
|
+
* `redactRequestHeaders`). `undefined`/empty disables the feature.
|
|
151
|
+
*/
|
|
152
|
+
requestHeaders?: Readonly<Record<string, string>>;
|
|
144
153
|
/** Whether to ignore robots.txt restrictions. */
|
|
145
154
|
ignoreRobots: boolean;
|
|
146
155
|
/**
|
|
@@ -642,3 +651,38 @@ export interface OutageSuspect {
|
|
|
642
651
|
/** Distinct host count at trigger time (== `hostThreshold` or more). */
|
|
643
652
|
readonly triggerHostCount: number;
|
|
644
653
|
}
|
|
654
|
+
/**
|
|
655
|
+
* Parameters for `createScopedHeaderRequestHandler`.
|
|
656
|
+
*/
|
|
657
|
+
export interface CreateScopedHeaderRequestHandlerParams {
|
|
658
|
+
/** Extra request headers to attach to in-scope requests. */
|
|
659
|
+
readonly requestHeaders: Readonly<Record<string, string>>;
|
|
660
|
+
/** Whether a request URL is inside the crawl scope. */
|
|
661
|
+
readonly isInScope: (href: string) => boolean;
|
|
662
|
+
/**
|
|
663
|
+
* Told when Chromium refuses to continue a request (e.g. a header it
|
|
664
|
+
* considers invalid). The request is aborted afterwards. Never receives a
|
|
665
|
+
* header value — only the error Puppeteer raised.
|
|
666
|
+
*/
|
|
667
|
+
readonly onError?: (error: unknown) => void;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Parameters for `createStripHeadersOnRedirect`.
|
|
671
|
+
*/
|
|
672
|
+
export interface CreateStripHeadersOnRedirectParams {
|
|
673
|
+
/** Names of the extra request headers to drop (case-insensitive). */
|
|
674
|
+
readonly headerNames: readonly string[];
|
|
675
|
+
/** Whether a redirect target (absolute URL) is inside the crawl scope. */
|
|
676
|
+
readonly isInScope: (href: string) => boolean;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Parameters for `applyRequestHeaderInterception`.
|
|
680
|
+
*/
|
|
681
|
+
export interface ApplyRequestHeaderInterceptionParams {
|
|
682
|
+
/** Extra request headers; `undefined` or empty leaves the page untouched. */
|
|
683
|
+
readonly requestHeaders: Readonly<Record<string, string>> | undefined;
|
|
684
|
+
/** Whether a request URL is inside the crawl scope. */
|
|
685
|
+
readonly isInScope: (href: string) => boolean;
|
|
686
|
+
/** Forwarded to the request handler's `onError`. */
|
|
687
|
+
readonly onError?: (error: unknown) => void;
|
|
688
|
+
}
|
|
@@ -54,6 +54,12 @@ interface CrawlConfig extends Config {
|
|
|
54
54
|
verbose: boolean;
|
|
55
55
|
/** Custom User-Agent string for HTTP requests. */
|
|
56
56
|
userAgent: string;
|
|
57
|
+
/**
|
|
58
|
+
* See {@link CrawlerOptions.requestHeaders}. Runtime-only: the values are
|
|
59
|
+
* never written to the archive (`INFO_COLUMN_ALLOWLIST` has no such
|
|
60
|
+
* column); only the names are, as `requestHeaderNames`.
|
|
61
|
+
*/
|
|
62
|
+
requestHeaders: Readonly<Record<string, string>>;
|
|
57
63
|
/** Whether to ignore robots.txt restrictions. */
|
|
58
64
|
ignoreRobots: boolean;
|
|
59
65
|
/**
|
|
@@ -9,6 +9,7 @@ import Archive from './archive/archive.js';
|
|
|
9
9
|
import { copyFileWithProgress } from './archive/filesystem/copy-file-with-progress.js';
|
|
10
10
|
import { REQUIRED_FORMAT_VERSION } from './archive/meta/assert-compatible-version.js';
|
|
11
11
|
import { computeAutoRetryBackoffDelayMs } from './compute-auto-retry-backoff-delay.js';
|
|
12
|
+
import { buildScopeMap } from './crawler/build-scope-map.js';
|
|
12
13
|
import { clearDestinationCache } from './crawler/clear-destination-cache.js';
|
|
13
14
|
import { clearDnsBurnedHostCache } from './crawler/clear-dns-burned-host-cache.js';
|
|
14
15
|
import Crawler from './crawler/crawler.js';
|
|
@@ -33,6 +34,7 @@ import { RESUME_SETUP_PHASES } from './resume-setup-phases.js';
|
|
|
33
34
|
import { RETRY_FAILED_SETUP_PHASES } from './retry-failed-setup-phases.js';
|
|
34
35
|
import { SETUP_RECOVERY_PHASE_LABELS } from './setup-recovery-phase-labels.js';
|
|
35
36
|
import { cleanObject } from './utils/object/clean-object.js';
|
|
37
|
+
import { redactRequestHeaders } from './utils/object/redact-request-headers.js';
|
|
36
38
|
import { WriteQueue } from './write-queue.js';
|
|
37
39
|
const [RECOVERY_RESTORE_FROM_BACKUP, RECOVERY_LEAVE_STATE_FOR_RESUME] = SETUP_RECOVERY_PHASE_LABELS;
|
|
38
40
|
/**
|
|
@@ -222,6 +224,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
222
224
|
disableQueries: options?.disableQueries,
|
|
223
225
|
verbose: options?.verbose ?? false,
|
|
224
226
|
userAgent: options?.userAgent || defaultUserAgent,
|
|
227
|
+
requestHeaders: options?.requestHeaders,
|
|
225
228
|
ignoreRobots: options?.ignoreRobots ?? false,
|
|
226
229
|
mainContentSelector: options?.mainContentSelector ?? null,
|
|
227
230
|
// Let the crawler reuse sub-resource data captured during page
|
|
@@ -976,6 +979,8 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
976
979
|
userAgent: options?.userAgent || defaultUserAgent,
|
|
977
980
|
ignoreRobots: options?.ignoreRobots ?? false,
|
|
978
981
|
mainContentSelector: options?.mainContentSelector ?? null,
|
|
982
|
+
// Names only — the values are credentials and never reach the archive.
|
|
983
|
+
requestHeaderNames: Object.keys(options?.requestHeaders ?? {}),
|
|
979
984
|
...buildCreatedCwdPatch(cwd),
|
|
980
985
|
});
|
|
981
986
|
const orchestrator = new CrawlerOrchestrator(archive, {
|
|
@@ -1068,6 +1073,15 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
1068
1073
|
fromList: false,
|
|
1069
1074
|
recursive: true,
|
|
1070
1075
|
baseUrl: mergedRoots[0],
|
|
1076
|
+
// Union, not replace: a name stays recorded once any session used
|
|
1077
|
+
// it, so a later run that omits it still gets the re-supply warning.
|
|
1078
|
+
// Names only — the values never reach the archive.
|
|
1079
|
+
requestHeaderNames: [
|
|
1080
|
+
...new Set([
|
|
1081
|
+
...(archived.requestHeaderNames ?? []),
|
|
1082
|
+
...Object.keys(options?.requestHeaders ?? {}),
|
|
1083
|
+
]),
|
|
1084
|
+
],
|
|
1071
1085
|
// Stamped for `Archive.resume` (issue #350) — this session's
|
|
1072
1086
|
// cwd, not `options.cwd` (already spread above and dropped by
|
|
1073
1087
|
// `updateConfig`'s allowlist): a stub left behind by THIS
|
|
@@ -1080,14 +1094,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
1080
1094
|
await copyFileWithProgress(absFilePath, backupPath, setupProgress?.onCopyProgress);
|
|
1081
1095
|
try {
|
|
1082
1096
|
await archive.updateConfig(mergedConfig);
|
|
1083
|
-
const scopeMap =
|
|
1084
|
-
for (const raw of mergedRoots) {
|
|
1085
|
-
const parsed = parseUrl(raw, archived);
|
|
1086
|
-
if (!parsed)
|
|
1087
|
-
continue;
|
|
1088
|
-
const existing = scopeMap.get(parsed.hostname) ?? [];
|
|
1089
|
-
scopeMap.set(parsed.hostname, [...existing, parsed]);
|
|
1090
|
-
}
|
|
1097
|
+
const scopeMap = buildScopeMap(mergedRoots, archived);
|
|
1091
1098
|
setupProgress?.onPhase?.(PHASE_REPROMOTING);
|
|
1092
1099
|
await archive.repromoteExternalPages(scopeMap, archived, setupProgress?.onChunkProgress);
|
|
1093
1100
|
// Seed the sticky set from prior sessions' confirmed traps so
|
|
@@ -1861,14 +1868,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
1861
1868
|
*/
|
|
1862
1869
|
static async #classifyInventoryCandidateUrls(rawUrls, archived, archive) {
|
|
1863
1870
|
const parsedAll = sortUrl(rawUrls, archived);
|
|
1864
|
-
const scopeMap =
|
|
1865
|
-
for (const raw of archived.roots) {
|
|
1866
|
-
const parsed = parseUrl(raw, archived);
|
|
1867
|
-
if (!parsed)
|
|
1868
|
-
continue;
|
|
1869
|
-
const existing = scopeMap.get(parsed.hostname) ?? [];
|
|
1870
|
-
scopeMap.set(parsed.hostname, [...existing, parsed]);
|
|
1871
|
-
}
|
|
1871
|
+
const scopeMap = buildScopeMap(archived.roots, archived);
|
|
1872
1872
|
const inScope = [];
|
|
1873
1873
|
let outOfScope = 0;
|
|
1874
1874
|
for (const url of parsedAll) {
|
|
@@ -2270,7 +2270,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
2270
2270
|
log('Start resuming');
|
|
2271
2271
|
log('Data %s', stubPath);
|
|
2272
2272
|
log('URL %s', url.href);
|
|
2273
|
-
log('Config %O', config);
|
|
2273
|
+
log('Config %O', redactRequestHeaders(config));
|
|
2274
2274
|
await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
|
|
2275
2275
|
await orchestrator.#crawlUntilPendingClears([url]);
|
|
2276
2276
|
CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
|