@dominevo/series-scraper-core 0.0.87 → 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.
Files changed (37) hide show
  1. package/dist/controllers/logs.controller.d.ts +7 -6
  2. package/dist/controllers/logs.controller.js +26 -9
  3. package/dist/controllers/vpn.controller.d.ts +2 -0
  4. package/dist/controllers/vpn.controller.js +14 -4
  5. package/dist/index.d.ts +5 -0
  6. package/dist/index.js +10 -1
  7. package/dist/ports/host-info.d.ts +6 -0
  8. package/dist/ports/log-files.d.ts +17 -7
  9. package/dist/ports/log-files.js +12 -0
  10. package/dist/ports/log-scrub.d.ts +2 -0
  11. package/dist/ports/log-scrub.js +58 -0
  12. package/dist/ports/logger.d.ts +0 -5
  13. package/dist/ports/logger.js +12 -2
  14. package/dist/scraper.module.js +6 -0
  15. package/dist/services/core.service.d.ts +4 -1
  16. package/dist/services/core.service.js +21 -2
  17. package/dist/services/download.service.d.ts +3 -0
  18. package/dist/services/download.service.js +33 -0
  19. package/dist/services/egress/direct-allowance.d.ts +17 -0
  20. package/dist/services/egress/direct-allowance.js +14 -0
  21. package/dist/services/egress/egress-gate.d.ts +66 -0
  22. package/dist/services/egress/egress-gate.js +119 -0
  23. package/dist/services/egress/egress-router.d.ts +2 -0
  24. package/dist/services/egress/egress-router.js +5 -0
  25. package/dist/services/egress/firewall-policy.d.ts +3 -2
  26. package/dist/services/egress/firewall-policy.js +4 -3
  27. package/dist/services/egress/outbound-routes.d.ts +2 -0
  28. package/dist/services/egress/outbound-routes.js +33 -0
  29. package/dist/services/egress/routing-dispatcher.js +7 -0
  30. package/dist/services/egress/vpn-gate.guard.d.ts +8 -0
  31. package/dist/services/egress/vpn-gate.guard.js +35 -0
  32. package/dist/services/plugin-loader.service.d.ts +12 -1
  33. package/dist/services/plugin-loader.service.js +44 -3
  34. package/dist/services/plugin-network-guard.js +4 -2
  35. package/dist/services/vpn.service.d.ts +32 -2
  36. package/dist/services/vpn.service.js +216 -17
  37. package/package.json +1 -1
@@ -1,14 +1,15 @@
1
1
  import { Response } from 'express';
2
- import type { LogFiles } from '../ports/log-files';
2
+ import { type LogFiles } from '../ports/log-files';
3
+ export declare function clampPage(raw: string | undefined): number;
3
4
  export declare class LogsController {
4
5
  private readonly logFiles?;
5
6
  constructor(logFiles?: LogFiles | undefined);
6
- get(page?: string, level?: string, file?: string): import("../ports/log-files").LogPage;
7
- listFiles(): import("../ports/log-files").LogFileInfo[];
8
- raw(file: string | undefined, res: Response): void;
9
- clear(): {
7
+ get(page?: string, level?: string, file?: string): Promise<import("../ports/log-files").LogPage>;
8
+ listFiles(): import("../ports/log-files").MaybePromise<import("../ports/log-files").LogFileInfo[]>;
9
+ raw(file: string | undefined, res: Response): Promise<void>;
10
+ clear(): Promise<{
10
11
  ok: boolean;
11
- };
12
+ }>;
12
13
  /** The host's log files, or a plain 404 when it keeps none. */
13
14
  private files;
14
15
  }
@@ -13,28 +13,45 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.LogsController = void 0;
16
+ exports.clampPage = clampPage;
16
17
  const common_1 = require("@nestjs/common");
17
18
  const tokens_1 = require("../ports/tokens");
19
+ const log_files_1 = require("../ports/log-files");
20
+ /** The newest page is 0; a negative, fractional, NaN or absurd value is brought into range. */
21
+ const MAX_LOG_PAGE = 10_000;
22
+ function clampPage(raw) {
23
+ const n = Math.floor(Number(raw));
24
+ if (!Number.isFinite(n) || n < 0)
25
+ return 0;
26
+ return Math.min(n, MAX_LOG_PAGE);
27
+ }
18
28
  let LogsController = class LogsController {
19
29
  constructor(logFiles) {
20
30
  this.logFiles = logFiles;
21
31
  }
22
- get(page, level, file) {
23
- return this.files().getPage(Number(page) || 0, level || undefined, file || undefined);
32
+ async get(page, level, file) {
33
+ return this.files().getPage(clampPage(page), level || undefined, file || undefined);
24
34
  }
25
35
  listFiles() {
26
36
  return this.files().listFiles();
27
37
  }
28
- raw(file, res) {
29
- const result = this.files().getRaw(file);
38
+ async raw(file, res) {
39
+ const result = await this.files().getRaw(file);
30
40
  if (!result)
31
41
  throw new common_1.HttpException('Log file not found or compressed', common_1.HttpStatus.NOT_FOUND);
32
42
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
33
43
  res.setHeader('Content-Disposition', `attachment; filename="${result.fileName}"`);
34
44
  res.send(result.content);
35
45
  }
36
- clear() {
37
- this.files().clear();
46
+ async clear() {
47
+ try {
48
+ await this.files().clear();
49
+ }
50
+ catch (error) {
51
+ if (error instanceof log_files_1.LogFilesRefused)
52
+ throw new common_1.HttpException(error.message, common_1.HttpStatus.CONFLICT);
53
+ throw error;
54
+ }
38
55
  return { ok: true };
39
56
  }
40
57
  /** The host's log files, or a plain 404 when it keeps none. */
@@ -52,7 +69,7 @@ __decorate([
52
69
  __param(2, (0, common_1.Query)('file')),
53
70
  __metadata("design:type", Function),
54
71
  __metadata("design:paramtypes", [String, String, String]),
55
- __metadata("design:returntype", void 0)
72
+ __metadata("design:returntype", Promise)
56
73
  ], LogsController.prototype, "get", null);
57
74
  __decorate([
58
75
  (0, common_1.Get)('files'),
@@ -66,13 +83,13 @@ __decorate([
66
83
  __param(1, (0, common_1.Res)()),
67
84
  __metadata("design:type", Function),
68
85
  __metadata("design:paramtypes", [Object, Object]),
69
- __metadata("design:returntype", void 0)
86
+ __metadata("design:returntype", Promise)
70
87
  ], LogsController.prototype, "raw", null);
71
88
  __decorate([
72
89
  (0, common_1.Delete)(),
73
90
  __metadata("design:type", Function),
74
91
  __metadata("design:paramtypes", []),
75
- __metadata("design:returntype", void 0)
92
+ __metadata("design:returntype", Promise)
76
93
  ], LogsController.prototype, "clear", null);
77
94
  exports.LogsController = LogsController = __decorate([
78
95
  (0, common_1.Controller)('api/logs'),
@@ -36,6 +36,8 @@ export declare class VpnController {
36
36
  rules: import("../types").HostRule[];
37
37
  }>;
38
38
  getStatus(): import("../services/vpn.service").VpnStatus;
39
+ /** Whether work may go out: open, or closed with the reason. Always answers, whatever the gate says. */
40
+ getGate(): import("..").GateStatus;
39
41
  getBlocks(): import("../services/egress/block-registry").ActiveBlock[];
40
42
  /** Forget active (host, exit) blocks: one pair, a host, an exit, or all. */
41
43
  clearBlocks(host?: string, egressId?: string): {
@@ -34,12 +34,12 @@ function validated(fn) {
34
34
  }
35
35
  }
36
36
  /** Resolve a NordVPN country/server named in a body, when it needs it. */
37
- async function resolveNord(body) {
37
+ async function resolveNord(vpn, body) {
38
38
  const target = (0, egress_input_1.nordTargetOf)(body);
39
39
  if (!target)
40
40
  return undefined;
41
41
  try {
42
- return await (0, nord_lookup_1.resolveNordTarget)(target);
42
+ return await (0, nord_lookup_1.resolveNordTarget)(target, (url) => vpn.fetchProviderJson(url));
43
43
  }
44
44
  catch (err) {
45
45
  throw new common_1.HttpException(`NordVPN lookup failed: ${err instanceof Error ? err.message : String(err)}`, common_1.HttpStatus.BAD_REQUEST);
@@ -61,7 +61,7 @@ let VpnController = class VpnController {
61
61
  return this.providersRepo.getAll().map(egress_migration_1.toEgressView);
62
62
  }
63
63
  async createProvider(body) {
64
- const resolved = await resolveNord(body);
64
+ const resolved = await resolveNord(this.vpn, body);
65
65
  const created = this.providersRepo.create(validated(() => (0, egress_input_1.parseNewEgress)(body, resolved)));
66
66
  await this.vpn.reload();
67
67
  return (0, egress_migration_1.toEgressView)(created);
@@ -70,7 +70,7 @@ let VpnController = class VpnController {
70
70
  const existing = this.providersRepo.getById(id);
71
71
  if (!existing)
72
72
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
73
- const resolved = await resolveNord(body);
73
+ const resolved = await resolveNord(this.vpn, body);
74
74
  const saved = this.providersRepo.update(id, validated(() => (0, egress_input_1.applyEgressPatch)(existing, body, resolved)));
75
75
  if (!saved)
76
76
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
@@ -111,6 +111,10 @@ let VpnController = class VpnController {
111
111
  getStatus() {
112
112
  return this.vpn.getStatus();
113
113
  }
114
+ /** Whether work may go out: open, or closed with the reason. Always answers, whatever the gate says. */
115
+ getGate() {
116
+ return this.vpn.gate.status();
117
+ }
114
118
  getBlocks() {
115
119
  return this.vpn.getBlocks();
116
120
  }
@@ -181,6 +185,12 @@ __decorate([
181
185
  __metadata("design:paramtypes", []),
182
186
  __metadata("design:returntype", void 0)
183
187
  ], VpnController.prototype, "getStatus", null);
188
+ __decorate([
189
+ (0, common_1.Get)('gate'),
190
+ __metadata("design:type", Function),
191
+ __metadata("design:paramtypes", []),
192
+ __metadata("design:returntype", void 0)
193
+ ], VpnController.prototype, "getGate", null);
184
194
  __decorate([
185
195
  (0, common_1.Get)('blocks'),
186
196
  __metadata("design:type", Function),
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { createScraperModule, ScraperModule } from './scraper.module';
2
2
  export { createScraperApp } from './scraper-app';
3
3
  export * from './ports';
4
+ export { EgressGate, WaitingForVpnError } from './services/egress/egress-gate';
5
+ export type { GateStatus, GateExitStatus } from './services/egress/egress-gate';
4
6
  export { WebhookRepository } from './repositories/webhook.repository';
5
7
  export type { WebhookConfig } from './repositories/webhook.repository';
6
8
  export { buildWebhookPayload } from './services/webhook-payload';
@@ -11,3 +13,6 @@ export type { SecretCollection } from './docker-layout/secret-layout';
11
13
  export { readDockerLayout } from './docker-layout/read-docker-layout';
12
14
  export type { DockerLayout } from './docker-layout/read-docker-layout';
13
15
  export { DEFAULT_SETTINGS } from './repositories/settings.repository';
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,13 +14,16 @@ 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.DEFAULT_SETTINGS = exports.readDockerLayout = exports.DOCKER_SECRET_LAYOUT = exports.runForEntry = exports.egressContext = exports.outsideEntryFetch = exports.buildWebhookPayload = exports.WebhookRepository = 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; } });
21
21
  var scraper_app_1 = require("./scraper-app");
22
22
  Object.defineProperty(exports, "createScraperApp", { enumerable: true, get: function () { return scraper_app_1.createScraperApp; } });
23
23
  __exportStar(require("./ports"), exports);
24
+ var egress_gate_1 = require("./services/egress/egress-gate");
25
+ Object.defineProperty(exports, "EgressGate", { enumerable: true, get: function () { return egress_gate_1.EgressGate; } });
26
+ Object.defineProperty(exports, "WaitingForVpnError", { enumerable: true, get: function () { return egress_gate_1.WaitingForVpnError; } });
24
27
  var webhook_repository_1 = require("./repositories/webhook.repository");
25
28
  Object.defineProperty(exports, "WebhookRepository", { enumerable: true, get: function () { return webhook_repository_1.WebhookRepository; } });
26
29
  var webhook_payload_1 = require("./services/webhook-payload");
@@ -36,3 +39,9 @@ var read_docker_layout_1 = require("./docker-layout/read-docker-layout");
36
39
  Object.defineProperty(exports, "readDockerLayout", { enumerable: true, get: function () { return read_docker_layout_1.readDockerLayout; } });
37
40
  var settings_repository_1 = require("./repositories/settings.repository");
38
41
  Object.defineProperty(exports, "DEFAULT_SETTINGS", { enumerable: true, get: function () { return settings_repository_1.DEFAULT_SETTINGS; } });
42
+ var log_scrub_1 = require("./ports/log-scrub");
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; } });
@@ -4,4 +4,10 @@ export interface HostInfo {
4
4
  version: string;
5
5
  /** The host runs behind its own egress firewall, so a request with no exit must be refused. */
6
6
  egressFirewall: boolean;
7
+ /**
8
+ * The host has no firewall but demands a VPN exit anyway: strict mode is forced on and nothing
9
+ * goes out until the default exit is up, tested and verified by the leak check. An
10
+ * application-level guarantee, not a network one. Absent means off.
11
+ */
12
+ requireExit?: boolean;
7
13
  }
@@ -14,17 +14,27 @@ export interface LogPage {
14
14
  total: number;
15
15
  page: number;
16
16
  }
17
+ /** A host that keeps its log elsewhere answers asynchronously; a file-backed one stays synchronous. */
18
+ export type MaybePromise<T> = T | Promise<T>;
17
19
  /**
18
- * Optional: a host that keeps its log in files lets the logs page list, page through,
19
- * download and clear them. Without it the logs routes answer 404 with a plain reason.
20
+ * Thrown by a `LogFiles` host for an operation its log store does not offer (a shared log
21
+ * that one application cannot wipe). The logs route answers 409 with the message, not 500.
22
+ */
23
+ export declare class LogFilesRefused extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * Optional: a host that keeps its log lets the logs page list, page through, download and
28
+ * clear it. Without it the logs routes answer 404 with a plain reason.
20
29
  */
21
30
  export interface LogFiles {
22
- listFiles(): LogFileInfo[];
23
- getPage(page: number, level?: string, fileName?: string): LogPage;
31
+ listFiles(): MaybePromise<LogFileInfo[]>;
32
+ getPage(page: number, level?: string, fileName?: string): MaybePromise<LogPage>;
24
33
  /** `null` when there is no such file or it cannot be read as text. */
25
- getRaw(fileName?: string): {
34
+ getRaw(fileName?: string): MaybePromise<{
26
35
  fileName: string;
27
36
  content: string;
28
- } | null;
29
- clear(): void;
37
+ } | null>;
38
+ /** May throw `LogFilesRefused` when the store cannot be cleared. */
39
+ clear(): MaybePromise<void>;
30
40
  }
@@ -1,2 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LogFilesRefused = void 0;
4
+ /**
5
+ * Thrown by a `LogFiles` host for an operation its log store does not offer (a shared log
6
+ * that one application cannot wipe). The logs route answers 409 with the message, not 500.
7
+ */
8
+ class LogFilesRefused extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = 'LogFilesRefused';
12
+ }
13
+ }
14
+ exports.LogFilesRefused = LogFilesRefused;
@@ -0,0 +1,2 @@
1
+ export declare const REDACTED = "[redacted]";
2
+ export declare function scrubSecrets(message: string): string;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDACTED = void 0;
4
+ exports.scrubSecrets = scrubSecrets;
5
+ /**
6
+ * Log lines name URLs, and a URL can carry a credential: a hoster's signed `token=` and `expires=`, a
7
+ * Plex `X-Plex-Token`, an `apikey` parameter, a `user:password@` prefix. This is the one place that
8
+ * removes them, applied by `ScopedLogger` to every line of every host.
9
+ */
10
+ const SECRET_PARAMS = [
11
+ 'token',
12
+ 'access_token',
13
+ 'refresh_token',
14
+ 'x-plex-token',
15
+ 'apikey',
16
+ 'api_key',
17
+ 'api-key',
18
+ 'x-api-key',
19
+ 'key',
20
+ 'secret',
21
+ 'password',
22
+ 'passwd',
23
+ 'pwd',
24
+ 'auth',
25
+ 'authorization',
26
+ 'sig',
27
+ 'signature',
28
+ 'expires',
29
+ 'hash',
30
+ 'session',
31
+ 'sessionid',
32
+ 'sid',
33
+ ];
34
+ const PARAM_VALUE = new RegExp(`([?&;\\s"'](?:${SECRET_PARAMS.join('|')}))=([^&#\\s"'<>]+)`, 'gi');
35
+ const USER_INFO = /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi;
36
+ const BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
37
+ const HEADER_VALUE = /\b(x-plex-token|x-api-key|authorization)(["']?\s*[:=]\s*["']?)[^\s"',;]+/gi;
38
+ /** A Cookie / Set-Cookie header: every pair, to the end of the line (`cf_clearance` and session ids included). */
39
+ const COOKIE_HEADER = /\b(set-cookie|cookie)(["']?\s*[:=]\s*)[^\r\n]*/gi;
40
+ /** A JSON member whose key names a credential: `"token":"x"`, `"apiKey":"x"`, `"privateKey":"x"`. */
41
+ const JSON_SECRET = /("[\w.-]*(?:token|password|passwd|secret|api_?key|private_?key|authorization|cookie|credential)[\w.-]*"\s*:\s*)"(?:[^"\\]|\\.)*"/gi;
42
+ /** Credentials that live in a URL path: Discord and Slack webhooks, a Telegram bot token. */
43
+ const DISCORD_WEBHOOK = /(\/api\/(?:v\d+\/)?webhooks\/)[^\s/?#"']+(?:\/[^\s/?#"']+)?/gi;
44
+ const SLACK_WEBHOOK = /(hooks\.slack\.com\/(?:services|workflows|triggers)\/)[^\s?#"']+/gi;
45
+ const TELEGRAM_BOT = /(\/bot)\d+:[A-Za-z0-9_-]+(?=\/|\s|$|["'?])/gi;
46
+ exports.REDACTED = '[redacted]';
47
+ function scrubSecrets(message) {
48
+ return message
49
+ .replace(USER_INFO, `$1${exports.REDACTED}@`)
50
+ .replace(DISCORD_WEBHOOK, `$1${exports.REDACTED}`)
51
+ .replace(SLACK_WEBHOOK, `$1${exports.REDACTED}`)
52
+ .replace(TELEGRAM_BOT, `$1${exports.REDACTED}`)
53
+ .replace(COOKIE_HEADER, `$1$2${exports.REDACTED}`)
54
+ .replace(JSON_SECRET, `$1"${exports.REDACTED}"`)
55
+ .replace(PARAM_VALUE, `$1=${exports.REDACTED}`)
56
+ .replace(BEARER, `$1 ${exports.REDACTED}`)
57
+ .replace(HEADER_VALUE, `$1$2${exports.REDACTED}`);
58
+ }
@@ -1,8 +1,3 @@
1
- /**
2
- * What the core logs through. The host supplies one `LoggerPort`; every class that
3
- * logs holds a `ScopedLogger` that stamps its own context on each line and hands it
4
- * to that port. Nothing in the core reaches for a logging library or a global.
5
- */
6
1
  export interface LoggerPort {
7
2
  log(message: string, context?: string): void;
8
3
  warn(message: string, context?: string): void;
@@ -2,6 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ScopedLogger = void 0;
4
4
  exports.bindLogger = bindLogger;
5
+ /**
6
+ * What the core logs through. The host supplies one `LoggerPort`; every class that
7
+ * logs holds a `ScopedLogger` that stamps its own context on each line and hands it
8
+ * to that port. Nothing in the core reaches for a logging library or a global.
9
+ */
10
+ const log_scrub_1 = require("./log-scrub");
5
11
  let bound;
6
12
  /**
7
13
  * Point every `ScopedLogger` at the host's logger (`createScraperModule` does it).
@@ -12,13 +18,17 @@ let bound;
12
18
  function bindLogger(port) {
13
19
  bound = port;
14
20
  }
15
- function text(message) {
21
+ function raw(message) {
16
22
  if (typeof message === 'string')
17
23
  return message;
18
24
  if (message instanceof Error)
19
25
  return message.stack ?? message.message;
20
26
  return String(message);
21
27
  }
28
+ /** Every line the core logs passes here: credentials in a URL or header never reach the host's logger. */
29
+ function text(message) {
30
+ return (0, log_scrub_1.scrubSecrets)(raw(message));
31
+ }
22
32
  class ScopedLogger {
23
33
  constructor(context) {
24
34
  this.context = context;
@@ -36,7 +46,7 @@ class ScopedLogger {
36
46
  bound?.verbose(text(message), this.context);
37
47
  }
38
48
  error(message, trace) {
39
- bound?.error(text(message), typeof trace === 'string' ? trace : undefined, this.context);
49
+ bound?.error(text(message), typeof trace === 'string' ? (0, log_scrub_1.scrubSecrets)(trace) : undefined, this.context);
40
50
  }
41
51
  }
42
52
  exports.ScopedLogger = ScopedLogger;
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ScraperModule = void 0;
10
10
  exports.createScraperModule = createScraperModule;
11
11
  const common_1 = require("@nestjs/common");
12
+ const core_1 = require("@nestjs/core");
12
13
  const tokens_1 = require("./ports/tokens");
13
14
  const logger_1 = require("./ports/logger");
14
15
  // Repositories
@@ -42,6 +43,8 @@ const plugin_settings_service_1 = require("./services/plugin-settings.service");
42
43
  const details_service_1 = require("./services/details.service");
43
44
  const vpn_preset_registry_service_1 = require("./services/vpn-preset-registry.service");
44
45
  const vpn_service_1 = require("./services/vpn.service");
46
+ const egress_gate_1 = require("./services/egress/egress-gate");
47
+ const vpn_gate_guard_1 = require("./services/egress/vpn-gate.guard");
45
48
  const book_adapter_registry_service_1 = require("./services/book-adapter-registry.service");
46
49
  // Controllers
47
50
  const core_controller_1 = require("./controllers/core.controller");
@@ -114,6 +117,7 @@ const PROVIDERS = [
114
117
  plugin_settings_service_1.PluginSettingsService,
115
118
  details_service_1.DetailsService,
116
119
  vpn_preset_registry_service_1.VpnPresetRegistryService,
120
+ egress_gate_1.EgressGate,
117
121
  vpn_service_1.VpnService,
118
122
  captcha_service_1.CaptchaService,
119
123
  book_adapter_registry_service_1.BookAdapterRegistryService,
@@ -137,6 +141,8 @@ function createScraperModule(ports) {
137
141
  { provide: tokens_1.PATHS, useValue: ports.paths },
138
142
  { provide: tokens_1.BINARIES, useValue: ports.binaries },
139
143
  { provide: tokens_1.HOST_INFO, useValue: ports.hostInfo },
144
+ // Closed while the host requires a VPN exit that is not yet verified: outbound routes answer 503.
145
+ { provide: core_1.APP_GUARD, useClass: vpn_gate_guard_1.VpnGateGuard },
140
146
  { provide: tokens_1.SETTINGS_SEED, useValue: ports.settingsSeed ?? {} },
141
147
  ...(ports.notifier ? [{ provide: tokens_1.NOTIFIER, useValue: ports.notifier }] : []),
142
148
  // Without LogFiles the logs routes answer 404: the controller injects it as optional.
@@ -1,4 +1,5 @@
1
1
  import { OnModuleInit, OnModuleDestroy } from '@nestjs/common';
2
+ import { EgressGate } from './egress/egress-gate';
2
3
  import { SettingsService } from './settings.service';
3
4
  import { SonarrService } from './sonarr.service';
4
5
  import { RadarrService } from './radarr.service';
@@ -14,12 +15,14 @@ export declare class CoreService implements OnModuleInit, OnModuleDestroy {
14
15
  private readonly tags;
15
16
  private readonly download;
16
17
  private readonly notifications;
18
+ private readonly gate?;
17
19
  private readonly logger;
18
20
  private timer;
19
21
  private running;
20
22
  private lastScan;
21
23
  private scanning;
22
- constructor(settings: SettingsService, sonarr: SonarrService, radarr: RadarrService, table: TableService, tags: TagsService, download: DownloadService, notifications: NotificationService);
24
+ private skippedForGate;
25
+ constructor(settings: SettingsService, sonarr: SonarrService, radarr: RadarrService, table: TableService, tags: TagsService, download: DownloadService, notifications: NotificationService, gate?: EgressGate | undefined);
23
26
  onModuleInit(): void;
24
27
  onModuleDestroy(): void;
25
28
  getStatus(): {
@@ -8,10 +8,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
11
14
  var CoreService_1;
12
15
  Object.defineProperty(exports, "__esModule", { value: true });
13
16
  exports.CoreService = void 0;
14
17
  const common_1 = require("@nestjs/common");
18
+ const egress_gate_1 = require("./egress/egress-gate");
15
19
  const logger_1 = require("../ports/logger");
16
20
  const settings_service_1 = require("./settings.service");
17
21
  const sonarr_service_1 = require("./sonarr.service");
@@ -21,7 +25,7 @@ const tags_service_1 = require("./tags.service");
21
25
  const download_service_1 = require("./download.service");
22
26
  const notification_service_1 = require("./notification.service");
23
27
  let CoreService = CoreService_1 = class CoreService {
24
- constructor(settings, sonarr, radarr, table, tags, download, notifications) {
28
+ constructor(settings, sonarr, radarr, table, tags, download, notifications, gate) {
25
29
  this.settings = settings;
26
30
  this.sonarr = sonarr;
27
31
  this.radarr = radarr;
@@ -29,11 +33,13 @@ let CoreService = CoreService_1 = class CoreService {
29
33
  this.tags = tags;
30
34
  this.download = download;
31
35
  this.notifications = notifications;
36
+ this.gate = gate;
32
37
  this.logger = new logger_1.ScopedLogger(CoreService_1.name);
33
38
  this.timer = null;
34
39
  this.running = false;
35
40
  this.lastScan = null;
36
41
  this.scanning = false;
42
+ this.skippedForGate = false;
37
43
  }
38
44
  onModuleInit() {
39
45
  this.start();
@@ -73,12 +79,23 @@ let CoreService = CoreService_1 = class CoreService {
73
79
  if (this.scanning) {
74
80
  return { triggered: false, message: 'Scan already in progress' };
75
81
  }
82
+ if (this.gate && !this.gate.isOpen())
83
+ return { triggered: false, message: 'Waiting for the VPN' };
76
84
  this.job().catch((err) => this.logger.error(`Wakeup scan failed: ${err}`));
77
85
  return { triggered: true, message: 'Scan triggered' };
78
86
  }
79
87
  async job() {
80
88
  if (this.scanning)
81
89
  return;
90
+ if (this.gate && !this.gate.isOpen()) {
91
+ // Nothing goes out, not even the question to Sonarr: say so once per closed period.
92
+ if (!this.skippedForGate) {
93
+ this.skippedForGate = true;
94
+ this.logger.warn(`Scan skipped: waiting for the VPN (${this.gate.status().reason ?? 'gate closed'})`);
95
+ }
96
+ return;
97
+ }
98
+ this.skippedForGate = false;
82
99
  this.scanning = true;
83
100
  const startTime = Date.now();
84
101
  try {
@@ -194,11 +211,13 @@ let CoreService = CoreService_1 = class CoreService {
194
211
  exports.CoreService = CoreService;
195
212
  exports.CoreService = CoreService = CoreService_1 = __decorate([
196
213
  (0, common_1.Injectable)(),
214
+ __param(7, (0, common_1.Optional)()),
197
215
  __metadata("design:paramtypes", [settings_service_1.SettingsService,
198
216
  sonarr_service_1.SonarrService,
199
217
  radarr_service_1.RadarrService,
200
218
  table_service_1.TableService,
201
219
  tags_service_1.TagsService,
202
220
  download_service_1.DownloadService,
203
- notification_service_1.NotificationService])
221
+ notification_service_1.NotificationService,
222
+ egress_gate_1.EgressGate])
204
223
  ], CoreService);
@@ -86,6 +86,9 @@ export declare class DownloadService implements OnApplicationBootstrap, OnModule
86
86
  */
87
87
  private vpnFetch;
88
88
  onModuleInit(): void;
89
+ private readonly pausedByGate;
90
+ private pauseForGate;
91
+ private resumeAfterGate;
89
92
  onApplicationBootstrap(): Promise<void>;
90
93
  /** Prefix used for all per-episode debug lines so they're easy to grep. */
91
94
  private epTag;
@@ -279,6 +279,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
279
279
  this.deliveredInRun = new Set();
280
280
  this.recentDeliveries = new Map();
281
281
  this.episodeSchedulerLimit = 0;
282
+ this.pausedByGate = new Set();
282
283
  }
283
284
  /** Re-read concurrentDownloads from settings and apply it to the scheduler immediately. */
284
285
  syncConcurrency() {
@@ -300,6 +301,31 @@ let DownloadService = DownloadService_1 = class DownloadService {
300
301
  this.tracker.setAutoPauseHandler((id) => {
301
302
  this.pauseEntry(id).catch((err) => this.logger.warn(`Auto-pause failed for ${id}: ${err}`));
302
303
  });
304
+ // The VPN gate: a download in flight is aborted the moment it closes and picks up again when it reopens.
305
+ this.vpn.gate.onClose(() => this.pauseForGate());
306
+ this.vpn.gate.onOpen(() => this.resumeAfterGate());
307
+ }
308
+ pauseForGate() {
309
+ const active = this.tracker.getActive().filter((p) => p.status === 'downloading' || p.status === 'queued');
310
+ for (const progress of active) {
311
+ const id = progress.entryId;
312
+ this.pausedByGate.add(id);
313
+ this.logger.warn(`VPN gate closed: aborting the download of "${progress.entryTitle}" (${id}); it resumes when the VPN is verified again`);
314
+ this.pauseEntry(id).catch((err) => this.logger.warn(`Pausing ${id} for the VPN gate failed: ${err}`));
315
+ }
316
+ }
317
+ resumeAfterGate() {
318
+ const ids = [...this.pausedByGate];
319
+ this.pausedByGate.clear();
320
+ for (const id of ids) {
321
+ if (!this.partialRepo.getById(id)) {
322
+ // Nothing was written yet, so there is nothing to resume from: say so, never leave it silent.
323
+ this.logger.warn(`VPN gate open: ${id} had no partial file to resume; start it again`);
324
+ continue;
325
+ }
326
+ this.logger.log(`VPN gate open: resuming ${id}`);
327
+ this.resumeEntry(id).catch((err) => this.logger.warn(`Resuming ${id} after the VPN gate failed: ${err}`));
328
+ }
303
329
  }
304
330
  async onApplicationBootstrap() {
305
331
  try {
@@ -435,6 +461,12 @@ let DownloadService = DownloadService_1 = class DownloadService {
435
461
  */
436
462
  /** All of an entry's work runs in its egress context, so its exit override reaches every request. */
437
463
  downloadEntry(entry, seasonNumber, opts) {
464
+ try {
465
+ this.vpn.gate.assertOpen(`download of ${entry.id}`);
466
+ }
467
+ catch (err) {
468
+ return Promise.reject(err);
469
+ }
438
470
  return this.trackRun(entry.id, (0, egress_context_1.runForEntry)(entry, () => this.downloadEntryInner(entry, seasonNumber, opts)));
439
471
  }
440
472
  trackRun(entryId, run) {
@@ -1374,6 +1406,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1374
1406
  * Runs in background — returns immediately with a trackId.
1375
1407
  */
1376
1408
  downloadDirect(link, fileName) {
1409
+ this.vpn.gate.assertOpen('direct download');
1377
1410
  const trackId = `direct-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1378
1411
  const safeName = this.sanitizeFileName(fileName);
1379
1412
  // Start tracking immediately
@@ -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
+ }