@dominevo/series-scraper-core 0.0.88 → 0.0.89

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/dist/index.d.ts CHANGED
@@ -14,3 +14,5 @@ export { readDockerLayout } from './docker-layout/read-docker-layout';
14
14
  export type { DockerLayout } from './docker-layout/read-docker-layout';
15
15
  export { DEFAULT_SETTINGS } from './repositories/settings.repository';
16
16
  export { scrubSecrets } from './ports/log-scrub';
17
+ export { runWithDirectAllowance, type DirectAllowance } from './services/egress/direct-allowance';
18
+ export { errorWithCause } from './services/vpn.service';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.scrubSecrets = exports.DEFAULT_SETTINGS = exports.readDockerLayout = exports.DOCKER_SECRET_LAYOUT = exports.runForEntry = exports.egressContext = exports.outsideEntryFetch = exports.buildWebhookPayload = exports.WebhookRepository = exports.WaitingForVpnError = exports.EgressGate = exports.createScraperApp = exports.ScraperModule = exports.createScraperModule = void 0;
17
+ exports.errorWithCause = exports.runWithDirectAllowance = exports.scrubSecrets = exports.DEFAULT_SETTINGS = exports.readDockerLayout = exports.DOCKER_SECRET_LAYOUT = exports.runForEntry = exports.egressContext = exports.outsideEntryFetch = exports.buildWebhookPayload = exports.WebhookRepository = exports.WaitingForVpnError = exports.EgressGate = exports.createScraperApp = exports.ScraperModule = exports.createScraperModule = void 0;
18
18
  var scraper_module_1 = require("./scraper.module");
19
19
  Object.defineProperty(exports, "createScraperModule", { enumerable: true, get: function () { return scraper_module_1.createScraperModule; } });
20
20
  Object.defineProperty(exports, "ScraperModule", { enumerable: true, get: function () { return scraper_module_1.ScraperModule; } });
@@ -41,3 +41,7 @@ var settings_repository_1 = require("./repositories/settings.repository");
41
41
  Object.defineProperty(exports, "DEFAULT_SETTINGS", { enumerable: true, get: function () { return settings_repository_1.DEFAULT_SETTINGS; } });
42
42
  var log_scrub_1 = require("./ports/log-scrub");
43
43
  Object.defineProperty(exports, "scrubSecrets", { enumerable: true, get: function () { return log_scrub_1.scrubSecrets; } });
44
+ var direct_allowance_1 = require("./services/egress/direct-allowance");
45
+ Object.defineProperty(exports, "runWithDirectAllowance", { enumerable: true, get: function () { return direct_allowance_1.runWithDirectAllowance; } });
46
+ var vpn_service_1 = require("./services/vpn.service");
47
+ Object.defineProperty(exports, "errorWithCause", { enumerable: true, get: function () { return vpn_service_1.errorWithCause; } });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A short, named permission to reach a fixed set of hosts DIRECTLY while no exit can serve them.
3
+ * It exists for downloads the exit itself depends on (the tunnel binary, the media tools): while the
4
+ * VPN gate is closed they would be refused, and the gate could never open. The host names its
5
+ * pinned download hosts, wraps only that download in `runWithDirectAllowance`, and the routing
6
+ * dispatcher honours it only when the router would otherwise refuse, so an exit that is up still
7
+ * carries the traffic. Everything else stays refused; every use is logged by the dispatcher.
8
+ */
9
+ export interface DirectAllowance {
10
+ /** What the download is, for the log line. */
11
+ readonly reason: string;
12
+ /** Exact host names (lower case); a redirect to another host is not covered. */
13
+ readonly hosts: readonly string[];
14
+ }
15
+ export declare function runWithDirectAllowance<T>(allowance: DirectAllowance, fn: () => Promise<T>): Promise<T>;
16
+ /** The allowance for `host` in the calling async context, if any. */
17
+ export declare function directAllowanceFor(host: string): DirectAllowance | undefined;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runWithDirectAllowance = runWithDirectAllowance;
4
+ exports.directAllowanceFor = directAllowanceFor;
5
+ const async_hooks_1 = require("async_hooks");
6
+ const storage = new async_hooks_1.AsyncLocalStorage();
7
+ function runWithDirectAllowance(allowance, fn) {
8
+ return storage.run({ reason: allowance.reason, hosts: allowance.hosts.map((h) => h.toLowerCase()) }, fn);
9
+ }
10
+ /** The allowance for `host` in the calling async context, if any. */
11
+ function directAllowanceFor(host) {
12
+ const current = storage.getStore();
13
+ return current?.hosts.includes(host.toLowerCase()) ? current : undefined;
14
+ }
@@ -4,6 +4,7 @@ exports.RoutingDispatcher = exports.EgressNotReadyError = void 0;
4
4
  const undici_1 = require("undici");
5
5
  const block_classification_1 = require("./block-classification");
6
6
  const rejecting_dispatcher_1 = require("./rejecting-dispatcher");
7
+ const direct_allowance_1 = require("./direct-allowance");
7
8
  const egress_router_1 = require("./egress-router");
8
9
  Object.defineProperty(exports, "EgressNotReadyError", { enumerable: true, get: function () { return egress_router_1.EgressNotReadyError; } });
9
10
  /** A challenge page is tiny; past this the body is judged on its first bytes. */
@@ -186,6 +187,12 @@ class RoutingDispatcher extends undici_1.Dispatcher {
186
187
  selection = this.router.select(host);
187
188
  }
188
189
  catch (err) {
190
+ const allowance = (0, direct_allowance_1.directAllowanceFor)(host);
191
+ if (allowance) {
192
+ // A pinned download the exits depend on, while no exit can serve it: direct, named, logged.
193
+ this.logger.log(`Direct download allowed while no exit is ready: ${host} (${allowance.reason})`);
194
+ return this.direct.dispatch(opts, handler);
195
+ }
189
196
  return (0, rejecting_dispatcher_1.failDispatch)(handler, err instanceof Error ? err : new Error(String(err)));
190
197
  }
191
198
  if (selection.kind === 'direct')
@@ -2,6 +2,13 @@ import type { Paths } from '../ports/paths';
2
2
  import { ScraperAdapter, VpnPreset, BookAdapter, PluginSettingField, PluginSettingValues } from '../types';
3
3
  import { PluginSettingsRepository } from '../repositories/plugin-settings.repository';
4
4
  import { HeadlessBrowserService } from './headless-browser.service';
5
+ /** The resolver a plugin falls back to for anything that is not shared. */
6
+ export interface PluginFallbackRequire {
7
+ (id: string): unknown;
8
+ resolve(id: string, options?: {
9
+ paths?: string[];
10
+ }): string;
11
+ }
5
12
  export type PluginKind = 'scraper' | 'vpn-preset' | 'book-adapter';
6
13
  export interface PluginMeta {
7
14
  name: string;
@@ -33,7 +40,7 @@ export interface PluginLoadResult {
33
40
  * anything else (including no kind field) is treated as a scraper adapter.
34
41
  * - `.json` — GenericSiteConfig (scraper adapter only).
35
42
  *
36
- * The require cache is cleared on each loadAll(), enabling live reload after upload.
43
+ * A plugin file is re-read on each loadAll(), enabling live reload after upload.
37
44
  */
38
45
  export declare class PluginLoaderService {
39
46
  private readonly headless;
@@ -49,6 +56,10 @@ export declare class PluginLoaderService {
49
56
  /** Records a module's `settings` fields and applies stored values through its `configure`. */
50
57
  private attachSettings;
51
58
  private loadJson;
59
+ /** What a plugin's `require` falls back to. A seam so a spec does not depend on the environment's node_modules. */
60
+ protected fallbackRequire(filePath: string): PluginFallbackRequire;
61
+ /** Run a plugin file as a CommonJS module whose `require` serves the shared modules first. Never cached: a reload re-reads it. */
62
+ private evaluate;
52
63
  private loadJs;
53
64
  private isValidAdapter;
54
65
  private isValidBookAdapter;
@@ -18,12 +18,38 @@ const common_1 = require("@nestjs/common");
18
18
  const logger_1 = require("../ports/logger");
19
19
  const tokens_1 = require("../ports/tokens");
20
20
  const fs_1 = require("fs");
21
+ const module_1 = require("module");
21
22
  const path_1 = require("path");
22
23
  const plugin_settings_repository_1 = require("../repositories/plugin-settings.repository");
23
24
  const plugin_settings_1 = require("./plugin-settings");
24
25
  const generic_adapter_1 = require("../adapters/generic.adapter");
25
26
  const headless_browser_service_1 = require("./headless-browser.service");
26
27
  const plugin_network_guard_1 = require("./plugin-network-guard");
28
+ /**
29
+ * What a plugin may `require` from the host, by name. A plugin file lives in the data directory, and
30
+ * Node resolves its `require` from there: in Docker that found the app's `node_modules`, in a host
31
+ * that bundles its dependencies it finds nothing. These are served from the host itself, so the
32
+ * plugin gets the same module wherever the host runs. Everything else resolves normally (Node's own
33
+ * modules) and has already passed the network guard.
34
+ *
35
+ * Only modules that cannot open a connection belong here, and a module that CAN gets a facade without
36
+ * that export: `cheerio.fromURL` builds its own undici client, which bypasses the global dispatcher
37
+ * and so the VPN, so a plugin sees cheerio without it. The other cheerio exports work on memory only.
38
+ */
39
+ const CHEERIO_NETWORK_EXPORTS = new Set(['fromURL']);
40
+ function cheerioFacade() {
41
+ const real = require('cheerio');
42
+ const facade = {};
43
+ for (const key of Object.keys(real)) {
44
+ if (!CHEERIO_NETWORK_EXPORTS.has(key))
45
+ facade[key] = real[key];
46
+ }
47
+ return Object.freeze(facade);
48
+ }
49
+ const SHARED_MODULES = {
50
+ cheerio: cheerioFacade,
51
+ uuid: () => require('uuid'),
52
+ };
27
53
  /**
28
54
  * Loads plugins at runtime from `data/plugins/`. Plugins can be either
29
55
  * scraper adapters (default) or VPN provider presets.
@@ -34,7 +60,7 @@ const plugin_network_guard_1 = require("./plugin-network-guard");
34
60
  * anything else (including no kind field) is treated as a scraper adapter.
35
61
  * - `.json` — GenericSiteConfig (scraper adapter only).
36
62
  *
37
- * The require cache is cleared on each loadAll(), enabling live reload after upload.
63
+ * A plugin file is re-read on each loadAll(), enabling live reload after upload.
38
64
  */
39
65
  let PluginLoaderService = PluginLoaderService_1 = class PluginLoaderService {
40
66
  constructor(headless, paths, pluginSettings) {
@@ -150,9 +176,24 @@ let PluginLoaderService = PluginLoaderService_1 = class PluginLoaderService {
150
176
  : undefined;
151
177
  return new generic_adapter_1.GenericAdapter(config, fetchPageHtml);
152
178
  }
179
+ /** What a plugin's `require` falls back to. A seam so a spec does not depend on the environment's node_modules. */
180
+ fallbackRequire(filePath) {
181
+ return (0, module_1.createRequire)(filePath);
182
+ }
183
+ /** Run a plugin file as a CommonJS module whose `require` serves the shared modules first. Never cached: a reload re-reads it. */
184
+ evaluate(filePath) {
185
+ const fallback = this.fallbackRequire(filePath);
186
+ const pluginRequire = Object.assign((id) => {
187
+ const shared = Object.prototype.hasOwnProperty.call(SHARED_MODULES, id) ? SHARED_MODULES[id] : undefined;
188
+ return shared ? shared() : fallback(id);
189
+ }, { resolve: (id, options) => fallback.resolve(id, options) });
190
+ const module = { exports: {} };
191
+ const run = new Function('exports', 'require', 'module', '__filename', '__dirname', (0, fs_1.readFileSync)(filePath, 'utf-8'));
192
+ run(module.exports, pluginRequire, module, filePath, (0, path_1.dirname)(filePath));
193
+ return module.exports;
194
+ }
153
195
  loadJs(filePath) {
154
- delete require.cache[require.resolve(filePath)];
155
- const mod = require(filePath);
196
+ const mod = this.evaluate(filePath);
156
197
  if (typeof mod === 'function') {
157
198
  try {
158
199
  return new mod();
@@ -38,6 +38,8 @@ export interface PuppeteerProxy {
38
38
  /** The exit that serves this page, to record on the links it produces. */
39
39
  egressId: string;
40
40
  }
41
+ /** An error with its `cause` chain ("fetch failed" alone says nothing); the logger scrubs it. */
42
+ export declare function errorWithCause(err: unknown): string;
41
43
  /** Where a leak-guard lookup should leave from. */
42
44
  type LookupRoute = {
43
45
  kind: 'direct';
@@ -14,6 +14,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
14
14
  var VpnService_1;
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.VpnService = void 0;
17
+ exports.errorWithCause = errorWithCause;
17
18
  const common_1 = require("@nestjs/common");
18
19
  const tokens_1 = require("../ports/tokens");
19
20
  const logger_1 = require("../ports/logger");
@@ -33,6 +34,23 @@ const routing_dispatcher_1 = require("./egress/routing-dispatcher");
33
34
  const wireproxy_supervisor_1 = require("./egress/wireproxy-supervisor");
34
35
  const CONTAINER_NETWORK = 'Container network';
35
36
  const TEST_ENDPOINT = 'https://api.ipify.org?format=json';
37
+ /** An error with its `cause` chain ("fetch failed" alone says nothing); the logger scrubs it. */
38
+ function errorWithCause(err) {
39
+ const parts = [];
40
+ let current = err;
41
+ for (let depth = 0; depth < 4 && current !== undefined && current !== null; depth++) {
42
+ if (current instanceof Error) {
43
+ const code = 'code' in current && typeof current.code === 'string' ? ` [${current.code}]` : '';
44
+ parts.push(`${current.message}${code}`);
45
+ current = 'cause' in current ? current.cause : undefined;
46
+ }
47
+ else {
48
+ parts.push(String(current));
49
+ break;
50
+ }
51
+ }
52
+ return parts.join(' <- cause: ');
53
+ }
36
54
  const TEST_TIMEOUT_MS = 15_000;
37
55
  const LEAK_GUARD_INTERVAL_MS = 10 * 60 * 1000;
38
56
  /** Hosts of a VPN provider's own API: the only ones `fetchProviderJson` reaches without a ready exit. */
@@ -495,7 +513,7 @@ let VpnService = VpnService_1 = class VpnService {
495
513
  return await this.buildLiveHandle(egress, localPort, fingerprint);
496
514
  }
497
515
  catch (err) {
498
- const message = err instanceof Error ? err.message : String(err);
516
+ const message = errorWithCause(err);
499
517
  this.logger.error(`Exit "${egress.name}" setup failed: ${message}`);
500
518
  return this.notReadyHandle(egress, `setup failed: ${message}`);
501
519
  }
@@ -557,7 +575,7 @@ let VpnService = VpnService_1 = class VpnService {
557
575
  return;
558
576
  }
559
577
  // The tunnel may listen on a new port: the exit is rebuilt against it, never just flipped.
560
- void this.serialize(() => this.rebuildExit(egressId)).catch((err) => this.logger.error(`Exit ${egressId}: could not follow its tunnel: ${err instanceof Error ? err.message : String(err)}`));
578
+ void this.serialize(() => this.rebuildExit(egressId)).catch((err) => this.logger.error(`Exit ${egressId}: could not follow its tunnel: ${errorWithCause(err)}`));
561
579
  }
562
580
  async rebuildExit(egressId) {
563
581
  const egress = this.providersRepo.getById(egressId);
@@ -793,7 +811,7 @@ let VpnService = VpnService_1 = class VpnService {
793
811
  return { ok: true, egressIp: body.ip, latencyMs };
794
812
  }
795
813
  catch (err) {
796
- return { ok: false, error: err instanceof Error ? err.message : String(err), latencyMs: Date.now() - started };
814
+ return { ok: false, error: errorWithCause(err), latencyMs: Date.now() - started };
797
815
  }
798
816
  }
799
817
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.88",
3
+ "version": "0.0.89",
4
4
  "description": "Host-agnostic scraper core: services, repositories, controllers and the ports a host supplies",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",