@dominevo/series-scraper-core 0.0.87 → 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 (32) 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 +3 -0
  6. package/dist/index.js +6 -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/egress-gate.d.ts +66 -0
  20. package/dist/services/egress/egress-gate.js +119 -0
  21. package/dist/services/egress/egress-router.d.ts +2 -0
  22. package/dist/services/egress/egress-router.js +5 -0
  23. package/dist/services/egress/firewall-policy.d.ts +3 -2
  24. package/dist/services/egress/firewall-policy.js +4 -3
  25. package/dist/services/egress/outbound-routes.d.ts +2 -0
  26. package/dist/services/egress/outbound-routes.js +33 -0
  27. package/dist/services/egress/vpn-gate.guard.d.ts +8 -0
  28. package/dist/services/egress/vpn-gate.guard.js +35 -0
  29. package/dist/services/plugin-network-guard.js +4 -2
  30. package/dist/services/vpn.service.d.ts +30 -2
  31. package/dist/services/vpn.service.js +195 -14
  32. package/package.json +1 -1
@@ -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 {};