@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
@@ -27,6 +27,7 @@ const exit_runtime_1 = require("./egress/exit-runtime");
27
27
  const egress_context_1 = require("./egress/egress-context");
28
28
  const host_rules_1 = require("./egress/host-rules");
29
29
  const leak_guard_1 = require("./egress/leak-guard");
30
+ const egress_gate_1 = require("./egress/egress-gate");
30
31
  const firewall_policy_1 = require("./egress/firewall-policy");
31
32
  const routing_dispatcher_1 = require("./egress/routing-dispatcher");
32
33
  const wireproxy_supervisor_1 = require("./egress/wireproxy-supervisor");
@@ -34,6 +35,13 @@ const CONTAINER_NETWORK = 'Container network';
34
35
  const TEST_ENDPOINT = 'https://api.ipify.org?format=json';
35
36
  const TEST_TIMEOUT_MS = 15_000;
36
37
  const LEAK_GUARD_INTERVAL_MS = 10 * 60 * 1000;
38
+ /** Hosts of a VPN provider's own API: the only ones `fetchProviderJson` reaches without a ready exit. */
39
+ const PROVIDER_API_HOSTS = ['api.nordvpn.com'];
40
+ const PROVIDER_FETCH_TIMEOUT_MS = 20_000;
41
+ const PROVIDER_FETCH_MAX_BYTES = 20 * 1024 * 1024;
42
+ /** With an exit required, a leak is found within a minute, and a closed gate asks again every 15 s. */
43
+ const LEAK_GUARD_REQUIRED_INTERVAL_MS = 60 * 1000;
44
+ const GATE_RETRY_MS = 15 * 1000;
37
45
  const BLOCK_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
38
46
  /** Chrome would otherwise reveal the real address through WebRTC UDP, whatever the proxy. */
39
47
  const WEBRTC_LEAK_ARGS = [
@@ -49,7 +57,7 @@ function hostOfUrl(url) {
49
57
  }
50
58
  }
51
59
  let VpnService = VpnService_1 = class VpnService {
52
- constructor(providersRepo, settingsRepo, host, binaries) {
60
+ constructor(providersRepo, settingsRepo, host, binaries, gate) {
53
61
  this.providersRepo = providersRepo;
54
62
  this.settingsRepo = settingsRepo;
55
63
  this.host = host;
@@ -64,33 +72,43 @@ let VpnService = VpnService_1 = class VpnService {
64
72
  this.directAgent = new undici_1.Agent();
65
73
  this.tunnels = new Map();
66
74
  this.leakFlagged = new Map();
75
+ /** The last leak-check answer per exit. Absent means unknown: nothing has compared its IP yet. */
76
+ this.verdicts = new Map();
67
77
  this.leakGuardActive = false;
68
78
  this.leakGuardRunning = false;
69
- this.settings = (0, firewall_policy_1.applyFirewallPolicy)(this.settingsRepo.get(), this.host.egressFirewall);
79
+ this.gate = gate ?? new egress_gate_1.EgressGate(host);
80
+ this.settings = (0, firewall_policy_1.applyFirewallPolicy)(this.settingsRepo.get(), this.host.egressFirewall, this.gate.required);
70
81
  this.router = new egress_router_1.EgressRouter({
71
82
  getSettings: () => this.settings,
72
- getExit: (id) => this.exits.get(id),
83
+ getExit: (id) => this.effective(this.exits.get(id)),
84
+ waiting: (host) => this.waitingFor(host),
73
85
  blocks: this.blocks,
74
86
  logger: this.logger,
75
87
  });
76
88
  this.routing = new routing_dispatcher_1.RoutingDispatcher(this.router, this.directAgent, this.logger);
77
89
  }
78
90
  async onApplicationBootstrap() {
91
+ // Every plugin calls the global fetch: routing happens here, not per call site. It is installed
92
+ // BEFORE any tunnel is spawned, so a request issued while the exits come up is judged by the
93
+ // router (refused when it has no ready exit), never sent on the direct network.
94
+ this.previousGlobal = (0, undici_1.getGlobalDispatcher)();
95
+ (0, undici_1.setGlobalDispatcher)(this.routing);
96
+ this.logger.log('Network egress routing installed as the global dispatcher');
79
97
  const swept = await (0, wireproxy_supervisor_1.sweepStaleWireproxyDirs)();
80
98
  if (swept > 0)
81
99
  this.logger.warn(`Removed ${swept} stale wireproxy config director${swept === 1 ? 'y' : 'ies'} left by a previous run`);
82
100
  await this.reload();
83
101
  this.logFirewallPosture();
84
- // Every plugin calls the global fetch: routing happens here, not per call site.
85
- this.previousGlobal = (0, undici_1.getGlobalDispatcher)();
86
- (0, undici_1.setGlobalDispatcher)(this.routing);
87
- this.logger.log('Network egress routing installed as the global dispatcher');
88
102
  this.startLeakGuard();
89
103
  this.blockSweepTimer = setInterval(() => this.blocks.sweep(), BLOCK_SWEEP_INTERVAL_MS);
90
104
  this.blockSweepTimer.unref();
91
105
  }
92
106
  /** With the egress firewall on, say so once, and shout when nothing can leave at all. */
93
107
  logFirewallPosture() {
108
+ if (this.gate.required && !this.host.egressFirewall) {
109
+ this.logger.log('Strict mode forced on: this host requires a VPN exit before any outbound work (an application-level guarantee, there is no firewall)');
110
+ return;
111
+ }
94
112
  if (!this.host.egressFirewall)
95
113
  return;
96
114
  this.logger.log('Strict mode forced on by EGRESS_FIREWALL');
@@ -103,6 +121,9 @@ let VpnService = VpnService_1 = class VpnService {
103
121
  if (this.leakTimer)
104
122
  clearInterval(this.leakTimer);
105
123
  this.leakTimer = undefined;
124
+ if (this.gateRetryTimer)
125
+ clearInterval(this.gateRetryTimer);
126
+ this.gateRetryTimer = undefined;
106
127
  if (this.blockSweepTimer)
107
128
  clearInterval(this.blockSweepTimer);
108
129
  this.blockSweepTimer = undefined;
@@ -166,7 +187,10 @@ let VpnService = VpnService_1 = class VpnService {
166
187
  getDispatcherForExit(egressId) {
167
188
  // An entry override beats a pinned link exit: precedence is override > pin > rules.
168
189
  const id = egress_context_1.egressContext.current()?.egressId ?? egressId;
169
- const handle = this.exits.get(id);
190
+ const waiting = this.waitingFor('pinned download');
191
+ if (waiting)
192
+ throw waiting;
193
+ const handle = this.effective(this.exits.get(id));
170
194
  if (handle?.ready)
171
195
  return handle.dispatcher;
172
196
  throw this.pinnedError(id, 'pinned download');
@@ -279,6 +303,7 @@ let VpnService = VpnService_1 = class VpnService {
279
303
  return;
280
304
  this.exits = new Map(this.exits).set(id, { ...handle, ready: false, error: reason });
281
305
  this.logger.error(`Exit "${handle.egress.name}" marked not ready: ${reason}`);
306
+ this.updateGate();
282
307
  }
283
308
  /** Leak guard recovery. Only a handle that was built live can simply be flipped back. */
284
309
  markReady(id) {
@@ -289,6 +314,7 @@ let VpnService = VpnService_1 = class VpnService {
289
314
  return;
290
315
  this.exits = new Map(this.exits).set(id, { ...handle, ready: true, error: undefined });
291
316
  this.logger.log(`Exit "${handle.egress.name}" is ready again`);
317
+ this.updateGate();
292
318
  }
293
319
  /** Rebuild every exit after settings or exit changes. One reload at a time. */
294
320
  reload() {
@@ -338,12 +364,20 @@ let VpnService = VpnService_1 = class VpnService {
338
364
  }
339
365
  const previous = [...this.exits.values()];
340
366
  const kept = new Set([...next.values()].map((h) => h.dispatcher));
341
- this.settings = (0, firewall_policy_1.applyFirewallPolicy)(settings, this.host.egressFirewall);
367
+ this.settings = (0, firewall_policy_1.applyFirewallPolicy)(settings, this.host.egressFirewall, this.gate.required);
368
+ for (const id of [...this.verdicts.keys()]) {
369
+ const before = this.exits.get(id);
370
+ const after = next.get(id);
371
+ if (!before || !after || before.fingerprint === undefined || before.fingerprint !== after.fingerprint || before.dispatcher !== after.dispatcher) {
372
+ this.verdicts.delete(id);
373
+ }
374
+ }
342
375
  this.exits = next;
343
376
  for (const id of [...this.leakFlagged.keys()])
344
377
  if (!next.has(id))
345
378
  this.leakFlagged.delete(id);
346
379
  await this.pruneTunnels(new Set(all.map((e) => e.id)));
380
+ this.updateGate();
347
381
  if (this.leakGuardActive)
348
382
  void this.runLeakGuard();
349
383
  // Replaced exits drain in the background: in-flight downloads finish, the mutex is not held for them.
@@ -404,10 +438,12 @@ let VpnService = VpnService_1 = class VpnService {
404
438
  if (settings.defaultEgressId)
405
439
  ids.add(settings.defaultEgressId);
406
440
  settings.rules.forEach((r) => r.egressIds.forEach((id) => ids.add(id)));
441
+ if (settings.captchaFallbackEgressId)
442
+ ids.add(settings.captchaFallbackEgressId);
407
443
  return [...ids];
408
444
  }
409
445
  pinnedError(egressId, host) {
410
- const handle = this.exits.get(egressId);
446
+ const handle = this.effective(this.exits.get(egressId));
411
447
  return new egress_router_1.EgressNotReadyError(egressId, handle?.egress.name ?? egressId, host, handle ? handle.error ?? 'not ready' : 'exit no longer exists');
412
448
  }
413
449
  /** The exit that serves `url`: the pinned one, else the one routing picks. Undefined = direct (no chain). */
@@ -415,10 +451,14 @@ let VpnService = VpnService_1 = class VpnService {
415
451
  // An entry override beats a pinned link exit (override > pin > rules).
416
452
  const egressId = egress_context_1.egressContext.current()?.egressId ?? pinnedId;
417
453
  if (egressId) {
418
- const pinned = this.exits.get(egressId);
454
+ const target = hostOfUrl(url) ?? url;
455
+ const waiting = this.waitingFor(target);
456
+ if (waiting)
457
+ throw waiting;
458
+ const pinned = this.effective(this.exits.get(egressId));
419
459
  if (pinned?.ready)
420
460
  return pinned;
421
- throw this.pinnedError(egressId, hostOfUrl(url) ?? url);
461
+ throw this.pinnedError(egressId, target);
422
462
  }
423
463
  const host = hostOfUrl(url);
424
464
  if (!host || (0, host_rules_1.isLocalHost)(host))
@@ -533,6 +573,7 @@ let VpnService = VpnService_1 = class VpnService {
533
573
  this.retire([current]);
534
574
  if (live.ready)
535
575
  this.logger.log(`Exit "${egress.name}" is ready again`);
576
+ this.updateGate();
536
577
  }
537
578
  async pruneTunnels(keep) {
538
579
  const gone = [...this.tunnels.entries()].filter(([id]) => !keep.has(id));
@@ -544,8 +585,71 @@ let VpnService = VpnService_1 = class VpnService {
544
585
  startLeakGuard() {
545
586
  this.leakGuardActive = true;
546
587
  void this.runLeakGuard();
547
- this.leakTimer = setInterval(() => void this.runLeakGuard(), LEAK_GUARD_INTERVAL_MS);
588
+ this.leakTimer = setInterval(() => void this.runLeakGuard(), this.gate.required ? LEAK_GUARD_REQUIRED_INTERVAL_MS : LEAK_GUARD_INTERVAL_MS);
548
589
  this.leakTimer.unref();
590
+ if (this.gate.required) {
591
+ // A closed gate does not wait for the next scheduled check: a verdict that came back unknown is asked again.
592
+ this.gateRetryTimer = setInterval(() => {
593
+ if (!this.gate.isOpen())
594
+ void this.runLeakGuard();
595
+ }, GATE_RETRY_MS);
596
+ this.gateRetryTimer.unref();
597
+ }
598
+ }
599
+ /**
600
+ * Fetch a JSON document from a VPN provider's own API (the lookup that resolves a server for an exit).
601
+ * On a host that requires an exit this is the one outbound call allowed while the gate is closed: an
602
+ * operator with no exit yet could never create the one that opens it. It goes on the direct network,
603
+ * only to a provider API host, https only, bounded in time and size, and every call is logged.
604
+ */
605
+ async fetchProviderJson(url) {
606
+ if (!this.gate.required) {
607
+ const res = await fetch(url, { signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS) });
608
+ if (!res.ok)
609
+ throw new Error(`${new URL(url).hostname} answered HTTP ${res.status}`);
610
+ return res.json();
611
+ }
612
+ const target = new URL(url);
613
+ if (target.protocol !== 'https:' || !PROVIDER_API_HOSTS.includes(target.hostname)) {
614
+ throw new Error(`${target.hostname} is not a VPN provider API host`);
615
+ }
616
+ this.logger.log(`Direct provider lookup: ${target.hostname}${target.pathname} (the only outbound call allowed without a ready exit)`);
617
+ // A redirect would turn this into a direct fetch of any host, so it is an error. DNS is not pinned
618
+ // to a known address: accepted, the call is TLS to a fixed host name.
619
+ const res = await (0, undici_1.fetch)(url, {
620
+ dispatcher: this.providerDispatcher(),
621
+ redirect: 'error',
622
+ signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),
623
+ });
624
+ if (!res.ok)
625
+ throw new Error(`${target.hostname} answered HTTP ${res.status}`);
626
+ const cap = this.providerMaxBytes();
627
+ const declared = Number(res.headers.get('content-length'));
628
+ if (Number.isFinite(declared) && declared > cap) {
629
+ await res.body?.cancel();
630
+ throw new Error(`${target.hostname} announced more than ${cap} bytes`);
631
+ }
632
+ const chunks = [];
633
+ let received = 0;
634
+ if (res.body) {
635
+ for await (const chunk of res.body) {
636
+ received += chunk.byteLength;
637
+ if (received > cap) {
638
+ // Leaving the loop by throwing cancels the stream.
639
+ throw new Error(`${target.hostname} answered more than ${cap} bytes`);
640
+ }
641
+ chunks.push(chunk);
642
+ }
643
+ }
644
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
645
+ }
646
+ /** How many bytes a provider lookup may read. Overridable for specs. */
647
+ providerMaxBytes() {
648
+ return PROVIDER_FETCH_MAX_BYTES;
649
+ }
650
+ /** The direct network, as the leak probe uses it. Overridable for specs. */
651
+ providerDispatcher() {
652
+ return this.directAgent;
549
653
  }
550
654
  /** The IP the world sees for a route. Overridable; undefined when the lookup failed. */
551
655
  async lookupEgressIp(route) {
@@ -581,6 +685,10 @@ let VpnService = VpnService_1 = class VpnService {
581
685
  const id = handle.egress.id;
582
686
  const exitIp = await this.lookupEgressIp({ kind: 'exit', egressId: id });
583
687
  const verdict = (0, leak_guard_1.evaluateLeak)({ exitIp, directIp });
688
+ // A failed lookup says nothing: it never revokes a verdict a check already gave, and it
689
+ // never grants one. A host that requires an exit therefore stays closed until one answers.
690
+ if (verdict !== 'unknown')
691
+ this.verdicts.set(id, verdict);
584
692
  if (verdict === 'leak' && !this.leakFlagged.has(id)) {
585
693
  const reason = 'leak guard: this exit reports the same egress IP as the direct network';
586
694
  this.leakFlagged.set(id, reason);
@@ -597,8 +705,80 @@ let VpnService = VpnService_1 = class VpnService {
597
705
  }
598
706
  finally {
599
707
  this.leakGuardRunning = false;
708
+ this.updateGate();
600
709
  }
601
710
  }
711
+ // ── The VPN gate ───────────────────────────────────────────────────────────
712
+ verdictOf(id) {
713
+ return this.verdicts.get(id) ?? 'unknown';
714
+ }
715
+ /**
716
+ * An exit as a request may use it. On a host that requires an exit, a VPN exit serves only
717
+ * after the leak check has compared its IP with the direct one and found them different.
718
+ */
719
+ effective(handle) {
720
+ if (!handle || !this.gate.required || handle.egress.type === 'direct' || !handle.ready)
721
+ return handle;
722
+ if (this.verdictOf(handle.egress.id) === 'ok')
723
+ return handle;
724
+ return { ...handle, ready: false, error: 'waiting for the leak check to confirm the exit IP differs from the direct one' };
725
+ }
726
+ /** The refusal for a non-local host while the gate is closed. */
727
+ waitingFor(host) {
728
+ if (this.gate.isOpen())
729
+ return undefined;
730
+ const id = this.settings.defaultEgressId ?? '';
731
+ return new egress_gate_1.WaitingForVpnError(id, this.exits.get(id)?.egress.name ?? 'default exit', host, this.gate.status());
732
+ }
733
+ /** The default exit's tunnel is up, its connection test passed and the leak check says `ok`. */
734
+ gateEvaluation() {
735
+ const id = this.settings.defaultEgressId;
736
+ if (!id)
737
+ return { open: false, reason: 'no default exit is configured' };
738
+ const handle = this.exits.get(id);
739
+ if (!handle)
740
+ return { open: false, reason: 'the default exit no longer exists' };
741
+ if (handle.egress.type === 'direct')
742
+ return { open: false, reason: `the default exit "${handle.egress.name}" is a direct connection, not a VPN` };
743
+ if (!handle.ready)
744
+ return { open: false, reason: `the default exit "${handle.egress.name}" is not ready: ${handle.error ?? 'unknown reason'}` };
745
+ const verdict = this.verdictOf(id);
746
+ if (verdict === 'leak')
747
+ return { open: false, reason: `the default exit "${handle.egress.name}" leaks: it reports the direct IP` };
748
+ if (verdict === 'unknown')
749
+ return { open: false, reason: `the leak check has not yet confirmed the default exit "${handle.egress.name}"` };
750
+ return { open: true };
751
+ }
752
+ gateExits() {
753
+ const roles = new Map();
754
+ const add = (id, role) => {
755
+ if (!id)
756
+ return;
757
+ const list = roles.get(id) ?? [];
758
+ if (!list.includes(role))
759
+ list.push(role);
760
+ roles.set(id, list);
761
+ };
762
+ add(this.settings.defaultEgressId, 'default');
763
+ this.settings.rules.forEach((r) => r.egressIds.forEach((id) => add(id, 'rule')));
764
+ add(this.settings.captchaFallbackEgressId, 'captcha');
765
+ return [...roles.entries()].map(([id, list]) => {
766
+ const handle = this.exits.get(id);
767
+ return {
768
+ id,
769
+ name: handle?.egress.name ?? id,
770
+ roles: list,
771
+ ready: !!handle?.ready,
772
+ verdict: this.verdictOf(id),
773
+ ...(handle && !handle.ready && handle.error ? { error: handle.error } : {}),
774
+ };
775
+ });
776
+ }
777
+ updateGate() {
778
+ if (!this.gate.required)
779
+ return;
780
+ this.gate.evaluate(this.gateEvaluation(), this.gateExits());
781
+ }
602
782
  async runTest(dispatcher) {
603
783
  const started = Date.now();
604
784
  try {
@@ -622,6 +802,7 @@ exports.VpnService = VpnService = VpnService_1 = __decorate([
622
802
  (0, common_1.Injectable)(),
623
803
  __param(2, (0, common_1.Inject)(tokens_1.HOST_INFO)),
624
804
  __param(3, (0, common_1.Inject)(tokens_1.BINARIES)),
805
+ __param(4, (0, common_1.Optional)()),
625
806
  __metadata("design:paramtypes", [vpn_providers_repository_1.VpnProvidersRepository,
626
- vpn_settings_repository_1.VpnSettingsRepository, Object, Object])
807
+ vpn_settings_repository_1.VpnSettingsRepository, Object, Object, egress_gate_1.EgressGate])
627
808
  ], VpnService);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.86",
3
+ "version": "0.0.88",
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",