@nitpicker/crawler 0.23.0 → 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.js +3 -2
- 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/init-schema.js +1 -0
- 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/transfer/merge-archive-configs.d.ts +3 -0
- package/lib/archive/transfer/merge-archive-configs.js +7 -0
- package/lib/archive/types.d.ts +10 -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/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 +14 -1
- package/lib/crawler.d.ts +1 -0
- package/lib/crawler.js +1 -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 +3 -3
package/lib/archive/archive.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import { redactRequestHeaders } from '../utils/object/redact-request-headers.js';
|
|
2
3
|
import { ArchiveAccessor } from './archive-accessor.js';
|
|
3
4
|
import { acquireArchiveLock } from './archive-lock.js';
|
|
4
5
|
import { computeArchiveCacheKey } from './cache/compute-archive-cache-key.js';
|
|
@@ -511,7 +512,7 @@ export default class Archive extends ArchiveAccessor {
|
|
|
511
512
|
* @param config - The configuration object to store.
|
|
512
513
|
*/
|
|
513
514
|
async setConfig(config) {
|
|
514
|
-
dbLog('Set config: %O', config);
|
|
515
|
+
dbLog('Set config: %O', redactRequestHeaders(config));
|
|
515
516
|
return this.#db.setConfig(config);
|
|
516
517
|
}
|
|
517
518
|
/**
|
|
@@ -629,7 +630,7 @@ export default class Archive extends ArchiveAccessor {
|
|
|
629
630
|
* @param patch - Partial {@link Config} fields to overwrite. `undefined` values are ignored.
|
|
630
631
|
*/
|
|
631
632
|
async updateConfig(patch) {
|
|
632
|
-
dbLog('Update config: %O', patch);
|
|
633
|
+
dbLog('Update config: %O', redactRequestHeaders(patch));
|
|
633
634
|
await this.#db.updateConfig(patch);
|
|
634
635
|
}
|
|
635
636
|
/**
|
|
@@ -2,7 +2,7 @@ import type { Config } from '../../types.js';
|
|
|
2
2
|
import type { Knex } from 'knex';
|
|
3
3
|
/**
|
|
4
4
|
* Retrieves the full crawl configuration from the `info` table.
|
|
5
|
-
* Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`).
|
|
5
|
+
* Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`, `requestHeaderNames`).
|
|
6
6
|
* @param knex - Knex query builder connected to the archive DB.
|
|
7
7
|
* @returns The parsed {@link Config} object.
|
|
8
8
|
* @throws {Error} If no configuration is found in the database.
|
|
@@ -2,7 +2,7 @@ import { dbLog } from '../../debug.js';
|
|
|
2
2
|
import { getJSON } from '../../get-json.js';
|
|
3
3
|
/**
|
|
4
4
|
* Retrieves the full crawl configuration from the `info` table.
|
|
5
|
-
* Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`).
|
|
5
|
+
* Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`, `requestHeaderNames`).
|
|
6
6
|
* @param knex - Knex query builder connected to the archive DB.
|
|
7
7
|
* @returns The parsed {@link Config} object.
|
|
8
8
|
* @throws {Error} If no configuration is found in the database.
|
|
@@ -18,6 +18,7 @@ export async function getConfig(knex) {
|
|
|
18
18
|
excludeKeywords: getJSON(config.excludeKeywords, []),
|
|
19
19
|
excludeUrls: getJSON(config.excludeUrls, []),
|
|
20
20
|
roots: getJSON(config.roots, []),
|
|
21
|
+
requestHeaderNames: getJSON(config.requestHeaderNames, []),
|
|
21
22
|
retry: config.retry ?? 3,
|
|
22
23
|
maxExcludedDepth: config.maxExcludedDepth ?? 0,
|
|
23
24
|
};
|
|
@@ -5,6 +5,7 @@ import { migrateContentItemsDedupeCapEventId } from '../../migrate-content-items
|
|
|
5
5
|
import { migrateContentItemsIsMetadataOnly } from '../../migrate-content-items-is-metadata-only.js';
|
|
6
6
|
import { migrateInfoCreatedCwd } from '../../migrate-info-created-cwd.js';
|
|
7
7
|
import { migrateInfoMainContentSelector } from '../../migrate-info-main-content-selector.js';
|
|
8
|
+
import { migrateInfoRequestHeaderNames } from '../../migrate-info-request-header-names.js';
|
|
8
9
|
import { migrateInfoRoots } from '../../migrate-info-roots.js';
|
|
9
10
|
import { migrateInventoryRunsToListReconcileRuns } from '../../migrate-inventory-runs-to-list-reconcile-runs.js';
|
|
10
11
|
import { migrateListReconcileRunsExcludeSkipped } from '../../migrate-list-reconcile-runs-exclude-skipped.js';
|
|
@@ -95,6 +96,7 @@ export async function init(knex, readOnly, onLog) {
|
|
|
95
96
|
await initSchema(knex);
|
|
96
97
|
await migrateInfoRoots(knex, onLog);
|
|
97
98
|
await migrateInfoMainContentSelector(knex, onLog);
|
|
99
|
+
await migrateInfoRequestHeaderNames(knex, onLog);
|
|
98
100
|
await migrateInfoCreatedCwd(knex, onLog);
|
|
99
101
|
await migrateMainContentsColumns(knex, onLog);
|
|
100
102
|
await migratePageMetaBodyHash(knex, onLog);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
/**
|
|
3
|
+
* Adds the `info.requestHeaderNames` column to archives created before it
|
|
4
|
+
* existed. `CREATE TABLE IF NOT EXISTS` (used for `info` itself) cannot
|
|
5
|
+
* retrofit a new column onto an already-existing table, so this lightweight,
|
|
6
|
+
* `hasColumn`-guarded `ALTER TABLE` runs on every `initSchema` call —
|
|
7
|
+
* idempotent, and self-healing for archives whose provisioning crashed
|
|
8
|
+
* partway through.
|
|
9
|
+
* @param instance - The Knex query builder instance connected to the database.
|
|
10
|
+
* @param onLog - Called instead of `console.error` when this migration
|
|
11
|
+
* actually applies (issue #294: a bare `console.error` here can fire
|
|
12
|
+
* while a `@d-zero/dealer` `Lanes`/`TaskList` display is mid-redraw during
|
|
13
|
+
* `Archive.open`, corrupting its cursor tracking). Falls back to
|
|
14
|
+
* `console.error` when omitted (direct/test callers).
|
|
15
|
+
*/
|
|
16
|
+
export declare function migrateInfoRequestHeaderNames(instance: Knex, onLog?: (message: string) => void): Promise<void>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds the `info.requestHeaderNames` column to archives created before it
|
|
3
|
+
* existed. `CREATE TABLE IF NOT EXISTS` (used for `info` itself) cannot
|
|
4
|
+
* retrofit a new column onto an already-existing table, so this lightweight,
|
|
5
|
+
* `hasColumn`-guarded `ALTER TABLE` runs on every `initSchema` call —
|
|
6
|
+
* idempotent, and self-healing for archives whose provisioning crashed
|
|
7
|
+
* partway through.
|
|
8
|
+
* @param instance - The Knex query builder instance connected to the database.
|
|
9
|
+
* @param onLog - Called instead of `console.error` when this migration
|
|
10
|
+
* actually applies (issue #294: a bare `console.error` here can fire
|
|
11
|
+
* while a `@d-zero/dealer` `Lanes`/`TaskList` display is mid-redraw during
|
|
12
|
+
* `Archive.open`, corrupting its cursor tracking). Falls back to
|
|
13
|
+
* `console.error` when omitted (direct/test callers).
|
|
14
|
+
*/
|
|
15
|
+
export async function migrateInfoRequestHeaderNames(instance, onLog) {
|
|
16
|
+
const hasInfo = await instance.schema.hasTable('info');
|
|
17
|
+
if (!hasInfo) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const hasColumn = await instance.schema.hasColumn('info', 'requestHeaderNames');
|
|
21
|
+
if (hasColumn) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
await instance.schema.table('info', (t) => {
|
|
25
|
+
t.json('requestHeaderNames');
|
|
26
|
+
});
|
|
27
|
+
const message = '[migrate] info.requestHeaderNames column added';
|
|
28
|
+
if (onLog) {
|
|
29
|
+
onLog(message);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
// eslint-disable-next-line no-console
|
|
33
|
+
console.error(message);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -20,6 +20,9 @@ import type { Config } from '../types.js';
|
|
|
20
20
|
* `baseUrl` is the merged `roots[0]`.
|
|
21
21
|
* - `excludes` / `excludeKeywords` / `excludeUrls` are unioned the same
|
|
22
22
|
* way, order-preserving.
|
|
23
|
+
* - `requestHeaderNames` is unioned too: it only records which header names
|
|
24
|
+
* ANY source needed (never values), so dropping a later source's names would
|
|
25
|
+
* silence the "re-supply these headers" warning for that source's pages.
|
|
23
26
|
* - Every other scalar field (`recursive`, `interval`, `image`,
|
|
24
27
|
* `fetchExternal`, `parallels`, `maxExcludedDepth`, `retry`,
|
|
25
28
|
* `userAgent`, `ignoreRobots`, `mainContentSelector`) is taken from the
|
|
@@ -23,6 +23,9 @@ const STRICT_MATCH_FIELDS = ['disableQueries', 'fromList'];
|
|
|
23
23
|
* `baseUrl` is the merged `roots[0]`.
|
|
24
24
|
* - `excludes` / `excludeKeywords` / `excludeUrls` are unioned the same
|
|
25
25
|
* way, order-preserving.
|
|
26
|
+
* - `requestHeaderNames` is unioned too: it only records which header names
|
|
27
|
+
* ANY source needed (never values), so dropping a later source's names would
|
|
28
|
+
* silence the "re-supply these headers" warning for that source's pages.
|
|
26
29
|
* - Every other scalar field (`recursive`, `interval`, `image`,
|
|
27
30
|
* `fetchExternal`, `parallels`, `maxExcludedDepth`, `retry`,
|
|
28
31
|
* `userAgent`, `ignoreRobots`, `mainContentSelector`) is taken from the
|
|
@@ -63,6 +66,9 @@ export function mergeArchiveConfigs(configs, name) {
|
|
|
63
66
|
const excludes = [...new Set(configs.flatMap((c) => c.excludes))];
|
|
64
67
|
const excludeKeywords = [...new Set(configs.flatMap((c) => c.excludeKeywords))];
|
|
65
68
|
const excludeUrls = [...new Set(configs.flatMap((c) => c.excludeUrls))];
|
|
69
|
+
const requestHeaderNames = [
|
|
70
|
+
...new Set(configs.flatMap((c) => c.requestHeaderNames ?? [])),
|
|
71
|
+
];
|
|
66
72
|
const first = configs[0];
|
|
67
73
|
return {
|
|
68
74
|
...first,
|
|
@@ -73,6 +79,7 @@ export function mergeArchiveConfigs(configs, name) {
|
|
|
73
79
|
excludes,
|
|
74
80
|
excludeKeywords,
|
|
75
81
|
excludeUrls,
|
|
82
|
+
requestHeaderNames,
|
|
76
83
|
createdCwd: null,
|
|
77
84
|
};
|
|
78
85
|
}
|
package/lib/archive/types.d.ts
CHANGED
|
@@ -80,6 +80,16 @@ export interface Config extends Required<Pick<ParseURLOptions, 'disableQueries'>
|
|
|
80
80
|
* detection, or `null`/omitted to use the automatic heuristic.
|
|
81
81
|
*/
|
|
82
82
|
mainContentSelector?: string | null;
|
|
83
|
+
/**
|
|
84
|
+
* Names (never values) of the extra request headers the crawl was started
|
|
85
|
+
* with (`--header` / `--authorization` / `--header-file`). Header values
|
|
86
|
+
* are credentials and are deliberately NOT persisted — `.nitpicker` files
|
|
87
|
+
* are shared between users. The names exist only so a later
|
|
88
|
+
* `--resume` / `--append` / `--retry-failed` / `--recrawl` / `--inventory`
|
|
89
|
+
* run can warn that the operator did not re-supply them. Empty/omitted
|
|
90
|
+
* means no extra headers were used.
|
|
91
|
+
*/
|
|
92
|
+
requestHeaderNames?: string[];
|
|
83
93
|
/**
|
|
84
94
|
* The `process.cwd()` recorded when this session's stub (tmpDir) was
|
|
85
95
|
* created by `CrawlerOrchestrator.crawling` / `.append` / `.inventory` /
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ApplyRequestHeaderInterceptionParams } from './types.js';
|
|
2
|
+
import type { Page } from 'puppeteer';
|
|
3
|
+
/**
|
|
4
|
+
* Turns on request interception for `page` and attaches the user-supplied
|
|
5
|
+
* extra headers to its in-scope requests — or does nothing at all when no
|
|
6
|
+
* headers were configured.
|
|
7
|
+
*
|
|
8
|
+
* The no-op for `undefined` / empty headers is the contract that keeps the
|
|
9
|
+
* default crawl path free of the per-request CDP round-trip interception adds
|
|
10
|
+
* (and of any change to caching behaviour), so it is pinned by a unit test.
|
|
11
|
+
* The caller also skips this for external pages: nothing of theirs is in
|
|
12
|
+
* scope, so interception would only slow them down.
|
|
13
|
+
* @param page - The Puppeteer page about to navigate.
|
|
14
|
+
* @param params - Headers, scope predicate and error sink.
|
|
15
|
+
* @returns Resolves once interception is configured (or immediately for a no-op).
|
|
16
|
+
* @example
|
|
17
|
+
* await applyRequestHeaderInterception(page, {
|
|
18
|
+
* requestHeaders: { Authorization: 'Bearer token' },
|
|
19
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
export declare function applyRequestHeaderInterception(page: Pick<Page, 'on' | 'setRequestInterception'>, params: ApplyRequestHeaderInterceptionParams): Promise<void>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { createScopedHeaderRequestHandler } from './create-scoped-header-request-handler.js';
|
|
2
|
+
/**
|
|
3
|
+
* Turns on request interception for `page` and attaches the user-supplied
|
|
4
|
+
* extra headers to its in-scope requests — or does nothing at all when no
|
|
5
|
+
* headers were configured.
|
|
6
|
+
*
|
|
7
|
+
* The no-op for `undefined` / empty headers is the contract that keeps the
|
|
8
|
+
* default crawl path free of the per-request CDP round-trip interception adds
|
|
9
|
+
* (and of any change to caching behaviour), so it is pinned by a unit test.
|
|
10
|
+
* The caller also skips this for external pages: nothing of theirs is in
|
|
11
|
+
* scope, so interception would only slow them down.
|
|
12
|
+
* @param page - The Puppeteer page about to navigate.
|
|
13
|
+
* @param params - Headers, scope predicate and error sink.
|
|
14
|
+
* @returns Resolves once interception is configured (or immediately for a no-op).
|
|
15
|
+
* @example
|
|
16
|
+
* await applyRequestHeaderInterception(page, {
|
|
17
|
+
* requestHeaders: { Authorization: 'Bearer token' },
|
|
18
|
+
* isInScope: (href) => href.startsWith('https://example.com/'),
|
|
19
|
+
* });
|
|
20
|
+
*/
|
|
21
|
+
export async function applyRequestHeaderInterception(page, params) {
|
|
22
|
+
const { requestHeaders, isInScope, onError } = params;
|
|
23
|
+
if (!requestHeaders || Object.keys(requestHeaders).length === 0) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
await page.setRequestInterception(true);
|
|
27
|
+
page.on('request', createScopedHeaderRequestHandler({ requestHeaders, isInScope, onError }));
|
|
28
|
+
}
|
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
|
/**
|
|
@@ -34,6 +34,7 @@ import { RESUME_SETUP_PHASES } from './resume-setup-phases.js';
|
|
|
34
34
|
import { RETRY_FAILED_SETUP_PHASES } from './retry-failed-setup-phases.js';
|
|
35
35
|
import { SETUP_RECOVERY_PHASE_LABELS } from './setup-recovery-phase-labels.js';
|
|
36
36
|
import { cleanObject } from './utils/object/clean-object.js';
|
|
37
|
+
import { redactRequestHeaders } from './utils/object/redact-request-headers.js';
|
|
37
38
|
import { WriteQueue } from './write-queue.js';
|
|
38
39
|
const [RECOVERY_RESTORE_FROM_BACKUP, RECOVERY_LEAVE_STATE_FOR_RESUME] = SETUP_RECOVERY_PHASE_LABELS;
|
|
39
40
|
/**
|
|
@@ -223,6 +224,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
223
224
|
disableQueries: options?.disableQueries,
|
|
224
225
|
verbose: options?.verbose ?? false,
|
|
225
226
|
userAgent: options?.userAgent || defaultUserAgent,
|
|
227
|
+
requestHeaders: options?.requestHeaders,
|
|
226
228
|
ignoreRobots: options?.ignoreRobots ?? false,
|
|
227
229
|
mainContentSelector: options?.mainContentSelector ?? null,
|
|
228
230
|
// Let the crawler reuse sub-resource data captured during page
|
|
@@ -977,6 +979,8 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
977
979
|
userAgent: options?.userAgent || defaultUserAgent,
|
|
978
980
|
ignoreRobots: options?.ignoreRobots ?? false,
|
|
979
981
|
mainContentSelector: options?.mainContentSelector ?? null,
|
|
982
|
+
// Names only — the values are credentials and never reach the archive.
|
|
983
|
+
requestHeaderNames: Object.keys(options?.requestHeaders ?? {}),
|
|
980
984
|
...buildCreatedCwdPatch(cwd),
|
|
981
985
|
});
|
|
982
986
|
const orchestrator = new CrawlerOrchestrator(archive, {
|
|
@@ -1069,6 +1073,15 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
1069
1073
|
fromList: false,
|
|
1070
1074
|
recursive: true,
|
|
1071
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
|
+
],
|
|
1072
1085
|
// Stamped for `Archive.resume` (issue #350) — this session's
|
|
1073
1086
|
// cwd, not `options.cwd` (already spread above and dropped by
|
|
1074
1087
|
// `updateConfig`'s allowlist): a stub left behind by THIS
|
|
@@ -2257,7 +2270,7 @@ export class CrawlerOrchestrator extends EventEmitter {
|
|
|
2257
2270
|
log('Start resuming');
|
|
2258
2271
|
log('Data %s', stubPath);
|
|
2259
2272
|
log('URL %s', url.href);
|
|
2260
|
-
log('Config %O', config);
|
|
2273
|
+
log('Config %O', redactRequestHeaders(config));
|
|
2261
2274
|
await CrawlerOrchestrator.#preloadDnsBurnedHostCache(archive);
|
|
2262
2275
|
await orchestrator.#crawlUntilPendingClears([url]);
|
|
2263
2276
|
CrawlerOrchestrator.#finalizeCrawlSession(orchestrator);
|
package/lib/crawler.d.ts
CHANGED
|
@@ -56,6 +56,7 @@ export type { NetworkProbe } from './crawler/probe-network.js';
|
|
|
56
56
|
export { probeNetwork } from './crawler/probe-network.js';
|
|
57
57
|
export { computeOutageClampTimestamp } from './archive/db-ops/outages/compute-outage-clamp-timestamp.js';
|
|
58
58
|
export { chooseProbeHost } from './crawler/choose-probe-host.js';
|
|
59
|
+
export { redactRequestHeaders } from './utils/object/redact-request-headers.js';
|
|
59
60
|
export { assertChromeIsInstalled } from './crawler/assert-chrome-installed.js';
|
|
60
61
|
export { assertPuppeteerSharedWithBeholder } from './crawler/assert-puppeteer-shared-with-beholder.js';
|
|
61
62
|
export { computeFileSha256 } from './utils/compute-file-sha256.js';
|
package/lib/crawler.js
CHANGED
|
@@ -53,6 +53,7 @@ export { default as NetworkGate } from './crawler/network-gate.js';
|
|
|
53
53
|
export { probeNetwork } from './crawler/probe-network.js';
|
|
54
54
|
export { computeOutageClampTimestamp } from './archive/db-ops/outages/compute-outage-clamp-timestamp.js';
|
|
55
55
|
export { chooseProbeHost } from './crawler/choose-probe-host.js';
|
|
56
|
+
export { redactRequestHeaders } from './utils/object/redact-request-headers.js';
|
|
56
57
|
export { assertChromeIsInstalled } from './crawler/assert-chrome-installed.js';
|
|
57
58
|
export { assertPuppeteerSharedWithBeholder } from './crawler/assert-puppeteer-shared-with-beholder.js';
|
|
58
59
|
export { computeFileSha256 } from './utils/compute-file-sha256.js';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns a copy of `config` whose `requestHeaders` values are replaced with
|
|
3
|
+
* `***`, leaving the header names visible. Use it before a config object is
|
|
4
|
+
* logged or printed.
|
|
5
|
+
*
|
|
6
|
+
* WHY: request header values are credentials. The runtime config that flows
|
|
7
|
+
* through the orchestrator carries them, and it is dumped by `debug` logs and
|
|
8
|
+
* the crawl-start header — neither may show a token.
|
|
9
|
+
* @param config - Any config object that may carry `requestHeaders`.
|
|
10
|
+
* @returns The same object when it has no `requestHeaders`, otherwise a shallow copy with masked values.
|
|
11
|
+
* @example
|
|
12
|
+
* redactRequestHeaders({ userAgent: 'x', requestHeaders: { Authorization: 'Bearer t' } });
|
|
13
|
+
* // => { userAgent: 'x', requestHeaders: { Authorization: '***' } }
|
|
14
|
+
*/
|
|
15
|
+
export declare function redactRequestHeaders<T extends object>(config: T): T;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Placeholder shown instead of a request header value. */
|
|
2
|
+
const REDACTED = '***';
|
|
3
|
+
/**
|
|
4
|
+
* Returns a copy of `config` whose `requestHeaders` values are replaced with
|
|
5
|
+
* `***`, leaving the header names visible. Use it before a config object is
|
|
6
|
+
* logged or printed.
|
|
7
|
+
*
|
|
8
|
+
* WHY: request header values are credentials. The runtime config that flows
|
|
9
|
+
* through the orchestrator carries them, and it is dumped by `debug` logs and
|
|
10
|
+
* the crawl-start header — neither may show a token.
|
|
11
|
+
* @param config - Any config object that may carry `requestHeaders`.
|
|
12
|
+
* @returns The same object when it has no `requestHeaders`, otherwise a shallow copy with masked values.
|
|
13
|
+
* @example
|
|
14
|
+
* redactRequestHeaders({ userAgent: 'x', requestHeaders: { Authorization: 'Bearer t' } });
|
|
15
|
+
* // => { userAgent: 'x', requestHeaders: { Authorization: '***' } }
|
|
16
|
+
*/
|
|
17
|
+
export function redactRequestHeaders(config) {
|
|
18
|
+
const { requestHeaders } = config;
|
|
19
|
+
if (!requestHeaders) {
|
|
20
|
+
return config;
|
|
21
|
+
}
|
|
22
|
+
const masked = {};
|
|
23
|
+
for (const name of Object.keys(requestHeaders)) {
|
|
24
|
+
masked[name] = REDACTED;
|
|
25
|
+
}
|
|
26
|
+
return { ...config, requestHeaders: masked };
|
|
27
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nitpicker/crawler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.0",
|
|
4
4
|
"description": "Web crawler engine with headless browser rendering and archive storage",
|
|
5
5
|
"author": "D-ZERO",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"ansi-colors": "4.1.3",
|
|
39
39
|
"debug": "4.4.3",
|
|
40
40
|
"follow-redirects": "1.16.0",
|
|
41
|
-
"fs-extra": "11.4.
|
|
41
|
+
"fs-extra": "11.4.1",
|
|
42
42
|
"knex": "3.3.0",
|
|
43
43
|
"libsql": "0.5.29",
|
|
44
44
|
"puppeteer": "25.5.0",
|
|
@@ -52,5 +52,5 @@
|
|
|
52
52
|
"@types/tar": "7.0.87",
|
|
53
53
|
"@types/unzipper": "0.10.11"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "840a594573c4abe0aaff1257469b7f2108fcdb19"
|
|
56
56
|
}
|