@dominevo/series-scraper-core 0.0.86 → 0.0.88

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 (38) 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/docker-layout/read-docker-layout.d.ts +15 -0
  6. package/dist/docker-layout/read-docker-layout.js +56 -0
  7. package/dist/docker-layout/secret-layout.d.ts +22 -0
  8. package/dist/docker-layout/secret-layout.js +120 -0
  9. package/dist/index.d.ts +8 -0
  10. package/dist/index.js +12 -1
  11. package/dist/ports/host-info.d.ts +6 -0
  12. package/dist/ports/log-files.d.ts +17 -7
  13. package/dist/ports/log-files.js +12 -0
  14. package/dist/ports/log-scrub.d.ts +2 -0
  15. package/dist/ports/log-scrub.js +58 -0
  16. package/dist/ports/logger.d.ts +0 -5
  17. package/dist/ports/logger.js +12 -2
  18. package/dist/repositories/settings.repository.d.ts +2 -0
  19. package/dist/repositories/settings.repository.js +4 -3
  20. package/dist/scraper.module.js +6 -0
  21. package/dist/services/core.service.d.ts +4 -1
  22. package/dist/services/core.service.js +21 -2
  23. package/dist/services/download.service.d.ts +3 -0
  24. package/dist/services/download.service.js +33 -0
  25. package/dist/services/egress/egress-gate.d.ts +66 -0
  26. package/dist/services/egress/egress-gate.js +119 -0
  27. package/dist/services/egress/egress-router.d.ts +2 -0
  28. package/dist/services/egress/egress-router.js +5 -0
  29. package/dist/services/egress/firewall-policy.d.ts +3 -2
  30. package/dist/services/egress/firewall-policy.js +4 -3
  31. package/dist/services/egress/outbound-routes.d.ts +2 -0
  32. package/dist/services/egress/outbound-routes.js +33 -0
  33. package/dist/services/egress/vpn-gate.guard.d.ts +8 -0
  34. package/dist/services/egress/vpn-gate.guard.js +35 -0
  35. package/dist/services/plugin-network-guard.js +4 -2
  36. package/dist/services/vpn.service.d.ts +30 -2
  37. package/dist/services/vpn.service.js +195 -14
  38. package/package.json +1 -1
@@ -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,66 @@
1
+ import type { HostInfo } from '../../ports/host-info';
2
+ import { EgressNotReadyError } from './egress-router';
3
+ import type { LeakVerdict } from './leak-guard';
4
+ /** Which setting names an exit: the default, a host rule, or the captcha fallback. */
5
+ export type GateExitRole = 'default' | 'rule' | 'captcha';
6
+ export interface GateExitStatus {
7
+ id: string;
8
+ name: string;
9
+ roles: GateExitRole[];
10
+ /** The tunnel is up and the connection test passed. */
11
+ ready: boolean;
12
+ /** Exit IP against the direct IP: `unknown` until a check has answered. */
13
+ verdict: LeakVerdict;
14
+ error?: string;
15
+ }
16
+ export interface GateStatus {
17
+ /** The host demands a VPN exit before any outbound work. Without it the gate is always open. */
18
+ required: boolean;
19
+ open: boolean;
20
+ /** Why it is closed; absent when open. */
21
+ reason?: string;
22
+ /** When the gate last changed state (ISO). */
23
+ since: string;
24
+ exits: GateExitStatus[];
25
+ }
26
+ export type GateEvaluation = {
27
+ open: true;
28
+ } | {
29
+ open: false;
30
+ reason: string;
31
+ };
32
+ /** An outbound request or job was refused because the VPN gate is closed. Never rerouted. */
33
+ export declare class WaitingForVpnError extends EgressNotReadyError {
34
+ readonly status: GateStatus;
35
+ constructor(egressId: string, egressName: string, host: string, status: GateStatus);
36
+ }
37
+ type Listener = () => void;
38
+ /**
39
+ * "Nothing starts without the VPN". When the host requires an exit, this is closed from boot
40
+ * until the default exit is up, tested and verified by the leak check, and closes again the
41
+ * moment any of that stops being true. The VPN service evaluates it; everything that would go
42
+ * out asks it.
43
+ */
44
+ export declare class EgressGate {
45
+ private readonly logger;
46
+ private open;
47
+ private reason;
48
+ private since;
49
+ private exits;
50
+ private decided;
51
+ private readonly onCloseListeners;
52
+ private readonly onOpenListeners;
53
+ readonly required: boolean;
54
+ constructor(host?: HostInfo);
55
+ /** True when work may go out: the host does not require an exit, or the gate has opened. */
56
+ isOpen(): boolean;
57
+ status(): GateStatus;
58
+ /** Throws the typed refusal while closed. `what` names the work in the message. */
59
+ assertOpen(what: string): void;
60
+ onClose(listener: Listener): () => void;
61
+ onOpen(listener: Listener): () => void;
62
+ /** The VPN service reports what it sees. Every transition is logged with its reason. */
63
+ evaluate(result: GateEvaluation, exits: GateExitStatus[]): void;
64
+ private fire;
65
+ }
66
+ export {};
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var EgressGate_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.EgressGate = exports.WaitingForVpnError = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const tokens_1 = require("../../ports/tokens");
19
+ const logger_1 = require("../../ports/logger");
20
+ const egress_router_1 = require("./egress-router");
21
+ /** An outbound request or job was refused because the VPN gate is closed. Never rerouted. */
22
+ class WaitingForVpnError extends egress_router_1.EgressNotReadyError {
23
+ constructor(egressId, egressName, host, status) {
24
+ super(egressId, egressName, host, status.reason ?? 'waiting for the VPN');
25
+ this.status = status;
26
+ this.name = 'WaitingForVpnError';
27
+ }
28
+ }
29
+ exports.WaitingForVpnError = WaitingForVpnError;
30
+ /**
31
+ * "Nothing starts without the VPN". When the host requires an exit, this is closed from boot
32
+ * until the default exit is up, tested and verified by the leak check, and closes again the
33
+ * moment any of that stops being true. The VPN service evaluates it; everything that would go
34
+ * out asks it.
35
+ */
36
+ let EgressGate = EgressGate_1 = class EgressGate {
37
+ constructor(host) {
38
+ this.logger = new logger_1.ScopedLogger(EgressGate_1.name);
39
+ this.open = false;
40
+ this.reason = 'waiting for the VPN checks to run';
41
+ this.since = new Date().toISOString();
42
+ this.exits = [];
43
+ this.decided = false;
44
+ this.onCloseListeners = new Set();
45
+ this.onOpenListeners = new Set();
46
+ this.required = host?.requireExit === true;
47
+ }
48
+ /** True when work may go out: the host does not require an exit, or the gate has opened. */
49
+ isOpen() {
50
+ return !this.required || this.open;
51
+ }
52
+ status() {
53
+ return {
54
+ required: this.required,
55
+ open: this.isOpen(),
56
+ ...(this.isOpen() ? {} : { reason: this.reason }),
57
+ since: this.since,
58
+ exits: this.exits,
59
+ };
60
+ }
61
+ /** Throws the typed refusal while closed. `what` names the work in the message. */
62
+ assertOpen(what) {
63
+ if (this.isOpen())
64
+ return;
65
+ throw new WaitingForVpnError('', 'VPN gate', what, this.status());
66
+ }
67
+ onClose(listener) {
68
+ this.onCloseListeners.add(listener);
69
+ return () => this.onCloseListeners.delete(listener);
70
+ }
71
+ onOpen(listener) {
72
+ this.onOpenListeners.add(listener);
73
+ return () => this.onOpenListeners.delete(listener);
74
+ }
75
+ /** The VPN service reports what it sees. Every transition is logged with its reason. */
76
+ evaluate(result, exits) {
77
+ if (!this.required)
78
+ return;
79
+ this.exits = exits;
80
+ const wasOpen = this.open;
81
+ const reason = result.open ? '' : result.reason;
82
+ const changed = !this.decided || wasOpen !== result.open || (!result.open && reason !== this.reason);
83
+ this.open = result.open;
84
+ if (!result.open)
85
+ this.reason = reason;
86
+ if (!changed)
87
+ return;
88
+ if (wasOpen !== result.open || !this.decided)
89
+ this.since = new Date().toISOString();
90
+ this.decided = true;
91
+ if (result.open) {
92
+ this.logger.log('VPN gate open: the default exit is up, tested and verified by the leak check');
93
+ }
94
+ else {
95
+ this.logger.warn(`VPN gate closed: ${reason}`);
96
+ }
97
+ if (wasOpen && !result.open)
98
+ this.fire(this.onCloseListeners);
99
+ if (!wasOpen && result.open)
100
+ this.fire(this.onOpenListeners);
101
+ }
102
+ fire(listeners) {
103
+ for (const listener of listeners) {
104
+ try {
105
+ listener();
106
+ }
107
+ catch (err) {
108
+ this.logger.error(`VPN gate listener failed: ${err instanceof Error ? err.message : String(err)}`);
109
+ }
110
+ }
111
+ }
112
+ };
113
+ exports.EgressGate = EgressGate;
114
+ exports.EgressGate = EgressGate = EgressGate_1 = __decorate([
115
+ (0, common_1.Injectable)(),
116
+ __param(0, (0, common_1.Optional)()),
117
+ __param(0, (0, common_1.Inject)(tokens_1.HOST_INFO)),
118
+ __metadata("design:paramtypes", [Object])
119
+ ], EgressGate);
@@ -13,6 +13,8 @@ export interface RouterDeps {
13
13
  blocks: BlockRegistry;
14
14
  logger: RouterLogger;
15
15
  isLocal?: (host: string) => boolean;
16
+ /** A refusal for every non-local host while the VPN gate is closed; undefined when open. */
17
+ waiting?: (host: string) => EgressNotReadyError | undefined;
16
18
  }
17
19
  /** Why an exit was chosen. `container` means no exit: the container's own network. */
18
20
  export type ExitSource = 'override' | 'rule' | 'default' | 'container';
@@ -48,6 +48,11 @@ class EgressRouter {
48
48
  const isLocal = this.deps.isLocal ?? host_rules_1.isLocalHost;
49
49
  if (isLocal(host))
50
50
  return { kind: 'direct' };
51
+ const waiting = this.deps.waiting?.(host);
52
+ if (waiting) {
53
+ this.deps.logger.debug(`Refusing ${host}: waiting for the VPN`);
54
+ throw waiting;
55
+ }
51
56
  // A watched entry's override comes first and stands alone: no rules, no fallback, no direct.
52
57
  const override = egress_context_1.egressContext.current()?.egressId;
53
58
  if (override)
@@ -2,6 +2,7 @@ import type { VpnSettings } from '../../types';
2
2
  /**
3
3
  * With the firewall on, strict mode is not a preference: a request with no
4
4
  * exit must be refused, never sent from the host's own address. Returns
5
- * a copy; the stored setting is untouched.
5
+ * a copy; the stored setting is untouched. A host that requires an exit forces it the same way,
6
+ * without claiming a firewall.
6
7
  */
7
- export declare function applyFirewallPolicy(settings: VpnSettings, firewallEnabled: boolean): VpnSettings;
8
+ export declare function applyFirewallPolicy(settings: VpnSettings, firewallEnabled: boolean, requireExit?: boolean): VpnSettings;
@@ -4,10 +4,11 @@ exports.applyFirewallPolicy = applyFirewallPolicy;
4
4
  /**
5
5
  * With the firewall on, strict mode is not a preference: a request with no
6
6
  * exit must be refused, never sent from the host's own address. Returns
7
- * a copy; the stored setting is untouched.
7
+ * a copy; the stored setting is untouched. A host that requires an exit forces it the same way,
8
+ * without claiming a firewall.
8
9
  */
9
- function applyFirewallPolicy(settings, firewallEnabled) {
10
- if (!firewallEnabled || settings.strictMode)
10
+ function applyFirewallPolicy(settings, firewallEnabled, requireExit = false) {
11
+ if (!(firewallEnabled || requireExit) || settings.strictMode)
11
12
  return settings;
12
13
  return { ...settings, strictMode: true };
13
14
  }
@@ -0,0 +1,2 @@
1
+ /** `path` is the request path without the query string. */
2
+ export declare function startsOutboundWork(method: string, path: string): boolean;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startsOutboundWork = startsOutboundWork;
4
+ const route = (method, path) => ({ method, path });
5
+ const OUTBOUND_ROUTES = [
6
+ route('GET', /^\/api\/books\/(metadata\/.*|search|links)$/),
7
+ route('POST', /^\/api\/captchas\/[^/]+\/(solve|refresh|fallback)$/),
8
+ route('GET', /^\/api\/catalog\/lookup$/),
9
+ route('POST', /^\/api\/catalog\/ensure$/),
10
+ route('GET', /^\/api\/updates$/),
11
+ route('PUT', /^\/api\/wakeup$/),
12
+ route('POST', /^\/api\/core\/(start|restart)$/),
13
+ route('POST', /^\/api\/downloads\/(direct|resolve)$/),
14
+ route('POST', /^\/api\/downloads\/[^/]+\/resume$/),
15
+ route('POST', /^\/api\/notifications\/webhooks\/[^/]+\/test$/),
16
+ route('GET', /^\/api\/plex\/sections$/),
17
+ route('POST', /^\/api\/plex\/test$/),
18
+ route('GET', /^\/api\/(detect|search|seasons|episodes|links)$/),
19
+ route('GET', /^\/api\/(sonarr|radarr)\/.*$/),
20
+ route('POST', /^\/api\/(sonarr|radarr)\/.*$/),
21
+ route('POST', /^\/api\/sites\/analyze(\/search)?$/),
22
+ route('POST', /^\/api\/table\/[^/]+\/(download|restart)$/),
23
+ route('POST', /^\/api\/table\/[^/]+\/download\/[^/]+$/),
24
+ route('POST', /^\/api\/table\/[^/]+\/episode\/(download|external-download)$/),
25
+ route('GET', /^\/api\/table\/[^/]+\/(details|episode\/links)$/),
26
+ route('POST', /^\/api\/tags\/sync$/),
27
+ ];
28
+ /** `path` is the request path without the query string. */
29
+ function startsOutboundWork(method, path) {
30
+ const m = method.toUpperCase();
31
+ const clean = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
32
+ return OUTBOUND_ROUTES.some((r) => r.method === m && r.path.test(clean));
33
+ }
@@ -0,0 +1,8 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { EgressGate } from './egress-gate';
3
+ /** While the VPN gate is closed, a route that would go out answers 503 `waiting-for-vpn`. */
4
+ export declare class VpnGateGuard implements CanActivate {
5
+ private readonly gate;
6
+ constructor(gate: EgressGate);
7
+ canActivate(context: ExecutionContext): boolean;
8
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.VpnGateGuard = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const egress_gate_1 = require("./egress-gate");
15
+ const outbound_routes_1 = require("./outbound-routes");
16
+ /** While the VPN gate is closed, a route that would go out answers 503 `waiting-for-vpn`. */
17
+ let VpnGateGuard = class VpnGateGuard {
18
+ constructor(gate) {
19
+ this.gate = gate;
20
+ }
21
+ canActivate(context) {
22
+ if (this.gate.isOpen())
23
+ return true;
24
+ const req = context.switchToHttp().getRequest();
25
+ const path = req.path ?? req.url.split('?')[0];
26
+ if (!(0, outbound_routes_1.startsOutboundWork)(req.method, path))
27
+ return true;
28
+ throw new common_1.HttpException({ error: 'waiting-for-vpn', status: this.gate.status() }, common_1.HttpStatus.SERVICE_UNAVAILABLE);
29
+ }
30
+ };
31
+ exports.VpnGateGuard = VpnGateGuard;
32
+ exports.VpnGateGuard = VpnGateGuard = __decorate([
33
+ (0, common_1.Injectable)(),
34
+ __metadata("design:paramtypes", [egress_gate_1.EgressGate])
35
+ ], VpnGateGuard);
@@ -7,8 +7,10 @@ exports.findForbiddenModule = findForbiddenModule;
7
7
  * leave from the container's own address, so it is refused at load.
8
8
  *
9
9
  * This reads the plugin's source for module references. It cannot see a
10
- * module name assembled at runtime; the egress firewall (EGRESS_FIREWALL=1)
11
- * is the backstop for that.
10
+ * module name assembled at runtime, nor `process.binding`. Where the host runs
11
+ * an egress firewall (the Docker deployment with EGRESS_FIREWALL=1) that is the
12
+ * backstop. Where it does not (the embedded host has no firewall, its VPN gate is
13
+ * an application-level guarantee), such a plugin would leave directly.
12
14
  */
13
15
  const FORBIDDEN_MODULES = [
14
16
  'http', 'https', 'http2', 'net', 'tls', 'dgram', 'child_process',
@@ -7,6 +7,7 @@ import { VpnProvidersRepository } from '../repositories/vpn-providers.repository
7
7
  import { VpnSettingsRepository } from '../repositories/vpn-settings.repository';
8
8
  import { ActiveBlock, BlockSelector } from './egress/block-registry';
9
9
  import { ActiveEgress } from './download-tracker.service';
10
+ import { EgressGate } from './egress/egress-gate';
10
11
  import { SupervisorState, WireproxySupervisor } from './egress/wireproxy-supervisor';
11
12
  export interface VpnTestResult {
12
13
  ok: boolean;
@@ -65,9 +66,13 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
65
66
  private tunnels;
66
67
  private readonly leakFlagged;
67
68
  private leakTimer;
69
+ private gateRetryTimer;
70
+ /** The last leak-check answer per exit. Absent means unknown: nothing has compared its IP yet. */
71
+ private readonly verdicts;
72
+ readonly gate: EgressGate;
68
73
  private leakGuardActive;
69
74
  private leakGuardRunning;
70
- constructor(providersRepo: VpnProvidersRepository, settingsRepo: VpnSettingsRepository, host: HostInfo, binaries: Binaries);
75
+ constructor(providersRepo: VpnProvidersRepository, settingsRepo: VpnSettingsRepository, host: HostInfo, binaries: Binaries, gate?: EgressGate);
71
76
  onApplicationBootstrap(): Promise<void>;
72
77
  /** With the egress firewall on, say so once, and shout when nothing can leave at all. */
73
78
  private logFirewallPosture;
@@ -137,6 +142,17 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
137
142
  private rebuildExit;
138
143
  private pruneTunnels;
139
144
  private startLeakGuard;
145
+ /**
146
+ * Fetch a JSON document from a VPN provider's own API (the lookup that resolves a server for an exit).
147
+ * On a host that requires an exit this is the one outbound call allowed while the gate is closed: an
148
+ * operator with no exit yet could never create the one that opens it. It goes on the direct network,
149
+ * only to a provider API host, https only, bounded in time and size, and every call is logged.
150
+ */
151
+ fetchProviderJson(url: string): Promise<unknown>;
152
+ /** How many bytes a provider lookup may read. Overridable for specs. */
153
+ protected providerMaxBytes(): number;
154
+ /** The direct network, as the leak probe uses it. Overridable for specs. */
155
+ protected providerDispatcher(): Dispatcher;
140
156
  /** The IP the world sees for a route. Overridable; undefined when the lookup failed. */
141
157
  protected lookupEgressIp(route: LookupRoute): Promise<string | undefined>;
142
158
  /**
@@ -145,6 +161,18 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
145
161
  * mode then refuses its traffic) until a later check differs.
146
162
  */
147
163
  protected runLeakGuard(): Promise<void>;
148
- private runTest;
164
+ private verdictOf;
165
+ /**
166
+ * An exit as a request may use it. On a host that requires an exit, a VPN exit serves only
167
+ * after the leak check has compared its IP with the direct one and found them different.
168
+ */
169
+ private effective;
170
+ /** The refusal for a non-local host while the gate is closed. */
171
+ private waitingFor;
172
+ /** The default exit's tunnel is up, its connection test passed and the leak check says `ok`. */
173
+ private gateEvaluation;
174
+ private gateExits;
175
+ private updateGate;
176
+ protected runTest(dispatcher: Dispatcher): Promise<VpnTestResult>;
149
177
  }
150
178
  export {};