@dominevo/series-scraper-core 0.0.89 → 0.0.91

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.
@@ -23,6 +23,7 @@ const sonarr_service_1 = require("../services/sonarr.service");
23
23
  const radarr_service_1 = require("../services/radarr.service");
24
24
  const details_service_1 = require("../services/details.service");
25
25
  const vpn_providers_repository_1 = require("../repositories/vpn-providers.repository");
26
+ const vpn_service_1 = require("../services/vpn.service");
26
27
  const egress_input_1 = require("../services/egress/egress-input");
27
28
  let TableController = TableController_1 = class TableController {
28
29
  constructor(tableService, downloadService, sonarr, radarr, details, vpnProviders) {
@@ -59,7 +60,7 @@ let TableController = TableController_1 = class TableController {
59
60
  update(id, body) {
60
61
  let patch = body;
61
62
  try {
62
- const egress = (0, egress_input_1.parseEntryEgressPatch)(body, new Set(this.vpnProviders.getAll().map((e) => e.id)));
63
+ const egress = (0, egress_input_1.parseEntryEgressPatch)(body, new Set(this.vpnProviders.getAll().map((e) => e.id)), new Set(this.vpnProviders.getAll().filter(vpn_service_1.isHomeByDesign).map((e) => e.id)));
63
64
  // `egressId` is replaced by the validated value (or removed, which clears the override).
64
65
  if (egress.change)
65
66
  patch = { ...body, egressId: egress.egressId };
@@ -35,6 +35,11 @@ export declare class VpnController {
35
35
  strictMode: boolean;
36
36
  rules: import("../types").HostRule[];
37
37
  }>;
38
+ /**
39
+ * The home-connection choice belongs to the captcha role: when that role moves off an exit, the exit loses
40
+ * the flag in the same request, so it never keeps an exemption it no longer has a reason for.
41
+ */
42
+ private clearHomeFlagLeaving;
38
43
  getStatus(): import("../services/vpn.service").VpnStatus;
39
44
  /** Whether work may go out: open, or closed with the reason. Always answers, whatever the gate says. */
40
45
  getGate(): import("..").GateStatus;
@@ -19,6 +19,7 @@ const vpn_settings_repository_1 = require("../repositories/vpn-settings.reposito
19
19
  const vpn_preset_registry_service_1 = require("../services/vpn-preset-registry.service");
20
20
  const table_service_1 = require("../services/table.service");
21
21
  const vpn_service_1 = require("../services/vpn.service");
22
+ const vpn_service_2 = require("../services/vpn.service");
22
23
  const egress_input_1 = require("../services/egress/egress-input");
23
24
  const nord_lookup_1 = require("../services/egress/nord-lookup");
24
25
  const egress_migration_1 = require("../services/egress/egress-migration");
@@ -62,7 +63,11 @@ let VpnController = class VpnController {
62
63
  }
63
64
  async createProvider(body) {
64
65
  const resolved = await resolveNord(this.vpn, body);
65
- const created = this.providersRepo.create(validated(() => (0, egress_input_1.parseNewEgress)(body, resolved)));
66
+ const parsed = validated(() => (0, egress_input_1.parseNewEgress)(body, resolved));
67
+ if ('homeIpByDesign' in parsed && parsed.homeIpByDesign) {
68
+ throw new common_1.HttpException('Create the exit first, make it the captcha fallback exit, then mark it as using the home connection', common_1.HttpStatus.BAD_REQUEST);
69
+ }
70
+ const created = this.providersRepo.create(parsed);
66
71
  await this.vpn.reload();
67
72
  return (0, egress_migration_1.toEgressView)(created);
68
73
  }
@@ -71,7 +76,17 @@ let VpnController = class VpnController {
71
76
  if (!existing)
72
77
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
73
78
  const resolved = await resolveNord(this.vpn, body);
74
- const saved = this.providersRepo.update(id, validated(() => (0, egress_input_1.applyEgressPatch)(existing, body, resolved)));
79
+ const patched = validated(() => (0, egress_input_1.applyEgressPatch)(existing, body, resolved));
80
+ if ('homeIpByDesign' in patched && patched.homeIpByDesign) {
81
+ const settings = this.settingsRepo.get();
82
+ validated(() => (0, egress_input_1.assertHomeIpAllowed)(id, patched.name, {
83
+ defaultEgressId: settings.defaultEgressId,
84
+ ruleExitIds: settings.rules.flatMap((r) => r.egressIds),
85
+ entryEgressIds: this.table.getAll().flatMap((e) => (e.egressId ? [e.egressId] : [])),
86
+ captchaFallbackEgressId: settings.captchaFallbackEgressId,
87
+ }));
88
+ }
89
+ const saved = this.providersRepo.update(id, patched);
75
90
  if (!saved)
76
91
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
77
92
  await this.vpn.reload();
@@ -103,11 +118,26 @@ let VpnController = class VpnController {
103
118
  }
104
119
  async updateSettings(body) {
105
120
  const known = new Set(this.providersRepo.getAll().map((e) => e.id));
106
- const next = validated(() => (0, egress_input_1.parseSettingsPatch)(body, this.settingsRepo.get(), known));
121
+ const homeOnly = new Set(this.providersRepo.getAll().filter(vpn_service_2.isHomeByDesign).map((e) => e.id));
122
+ const next = validated(() => (0, egress_input_1.parseSettingsPatch)(body, this.settingsRepo.get(), known, homeOnly));
123
+ this.clearHomeFlagLeaving(this.settingsRepo.get().captchaFallbackEgressId, next.captchaFallbackEgressId);
107
124
  this.settingsRepo.update(next);
108
125
  await this.vpn.reload();
109
126
  return { ...next, captchaFallbackEgressId: next.captchaFallbackEgressId ?? null, status: this.vpn.getStatus() };
110
127
  }
128
+ /**
129
+ * The home-connection choice belongs to the captcha role: when that role moves off an exit, the exit loses
130
+ * the flag in the same request, so it never keeps an exemption it no longer has a reason for.
131
+ */
132
+ clearHomeFlagLeaving(previousId, nextId) {
133
+ if (!previousId || previousId === nextId)
134
+ return;
135
+ const old = this.providersRepo.getById(previousId);
136
+ if (!old || !(0, vpn_service_2.isHomeByDesign)(old) || old.type === 'direct' || old.type === 'wireguard')
137
+ return;
138
+ const { homeIpByDesign: _cleared, ...kept } = old;
139
+ this.providersRepo.update(previousId, kept);
140
+ }
111
141
  getStatus() {
112
142
  return this.vpn.getStatus();
113
143
  }
@@ -2,4 +2,11 @@
2
2
  export interface Paths {
3
3
  /** Chrome profiles, plugins and captcha dumps live under it. */
4
4
  dataDir: string;
5
+ /**
6
+ * What a RELATIVE `downloadPath` in the settings is resolved against (nothing resolves `bookDownloadPath`). Absent: `dataDir`,
7
+ * so a host whose working directory is not its own (an embedded one) never writes under it. The Docker
8
+ * image sets it to its working directory, where `./downloads` is a mounted volume. The sonarr and radarr
9
+ * roots still resolve against the working directory, on purpose: they are absolute in practice.
10
+ */
11
+ relativeBaseDir?: string;
5
12
  }
@@ -236,7 +236,7 @@ let CaptchaService = CaptchaService_1 = class CaptchaService {
236
236
  async exchange(challenge, url, init) {
237
237
  const host = (0, captcha_fallback_1.hostOf)(url);
238
238
  try {
239
- const dispatcher = challenge.egressId ? this.vpn.getDispatcherForExit(challenge.egressId) : undefined;
239
+ const dispatcher = challenge.egressId ? this.vpn.getDispatcherForExit(challenge.egressId, 'hoster-resolution') : undefined;
240
240
  const res = await fetch(url, dispatcher ? { ...init, dispatcher } : init);
241
241
  if (!res.ok) {
242
242
  this.logger.warn(`Captcha ${challenge.id}: ${host} answered HTTP ${res.status}`);
@@ -0,0 +1,3 @@
1
+ import type { Paths } from '../ports/paths';
2
+ /** A configured download directory as an absolute path: relative ones resolve against the host's base, never `process.cwd()`. */
3
+ export declare function resolveDownloadDir(configured: string, paths: Paths): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.resolveDownloadDir = resolveDownloadDir;
37
+ const path = __importStar(require("path"));
38
+ /** A configured download directory as an absolute path: relative ones resolve against the host's base, never `process.cwd()`. */
39
+ function resolveDownloadDir(configured, paths) {
40
+ return path.resolve(paths.relativeBaseDir ?? paths.dataDir, configured);
41
+ }
@@ -73,6 +73,7 @@ const sort_links_1 = require("./sort-links");
73
73
  const cloudflare_detect_1 = require("./cloudflare-detect");
74
74
  const media_url_1 = require("./media-url");
75
75
  const media_headers_1 = require("./media-headers");
76
+ const download_paths_1 = require("./download-paths");
76
77
  const ffmpeg_hls_args_1 = require("./ffmpeg-hls-args");
77
78
  const hls_progress_1 = require("./hls-progress");
78
79
  const describe_error_1 = require("../utils/describe-error");
@@ -718,7 +719,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
718
719
  const seasonFolder = `Season ${String(seasonNumber).padStart(2, '0')}`;
719
720
  return path.join(path.resolve(settings.sonarrRootPath), cachedFinalDirBase, seasonFolder);
720
721
  };
721
- const tempDir = path.resolve(settings.downloadPath);
722
+ const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
722
723
  const scheduler = this.getEpisodeScheduler();
723
724
  const forced = opts?.forced ?? false;
724
725
  // A scan leaves a recently not-available episode alone; an operator action re-checks it.
@@ -1311,7 +1312,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1311
1312
  const movieFolder = path.basename(movie.path);
1312
1313
  finalDir = path.join(path.resolve(settings.radarrRootPath), movieFolder);
1313
1314
  }
1314
- const tempDir = path.resolve(settings.downloadPath);
1315
+ const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
1315
1316
  notify({
1316
1317
  type: 'episode_start',
1317
1318
  title: 'Movie Downloading',
@@ -1420,7 +1421,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1420
1421
  }
1421
1422
  async _runDirectDownload(trackId, link, fileName) {
1422
1423
  const settings = this.settings.get();
1423
- const targetDir = path.resolve(settings.downloadPath);
1424
+ const targetDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
1424
1425
  const startedAt = new Date().toISOString();
1425
1426
  // Create history entry immediately with 'downloading' status
1426
1427
  const historyEntry = this.history.add({
@@ -1894,7 +1895,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
1894
1895
  const title = (current?.entryId ? this.tableRepo.getById(current.entryId)?.title : undefined) ?? 'unknown entry';
1895
1896
  const exitName = this.vpn.getExitName(egressId) ?? egressId;
1896
1897
  this.logger.log(`Fallback exit "${exitName}" used for the hoster page of "${title}" (host ${(0, captcha_fallback_1.hostOf)(link.url)})`);
1897
- const resolved = await egress_context_1.egressContext.run({ ...(current?.entryId ? { entryId: current.entryId } : {}), egressId }, () => this.resolveLinkRouted(link));
1898
+ const resolved = await egress_context_1.egressContext.run({ ...(current?.entryId ? { entryId: current.entryId } : {}), egressId, purpose: 'hoster-resolution' }, () => this.resolveLinkRouted(link));
1898
1899
  return resolved.egressId === egressId ? { ...resolved, egressId: undefined } : resolved;
1899
1900
  }
1900
1901
  async resolveMaxstreamPage(url, followedContinue = false, viaFallback = false) {
@@ -2091,7 +2092,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
2091
2092
  */
2092
2093
  async listLocalFiles() {
2093
2094
  const settings = this.settings.get();
2094
- const dir = path.resolve(settings.downloadPath);
2095
+ const dir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
2095
2096
  try {
2096
2097
  const entries = await fs.readdir(dir, { withFileTypes: true });
2097
2098
  const files = [];
@@ -2122,7 +2123,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
2122
2123
  */
2123
2124
  async deleteLocalFile(fileName) {
2124
2125
  const settings = this.settings.get();
2125
- const dir = path.resolve(settings.downloadPath);
2126
+ const dir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
2126
2127
  const filePath = path.join(dir, fileName);
2127
2128
  // Prevent directory traversal
2128
2129
  if (!filePath.startsWith(dir))
@@ -2681,11 +2682,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
2681
2682
  headers: (0, media_headers_1.toFfmpegHeaderBlock)((0, media_headers_1.buildMediaHeaders)({ referer: effectiveReferer, userAgent })),
2682
2683
  proxyUrl: this.vpn.getFfmpegProxyUrl(url, egressId),
2683
2684
  }),
2684
- ...audioMaps,
2685
- '-c', 'copy',
2686
- '-bsf:a', 'aac_adtstoasc',
2687
- '-y',
2688
- outputPath,
2685
+ ...(0, ffmpeg_hls_args_1.buildHlsOutputArgs)(audioMaps, outputPath),
2689
2686
  ];
2690
2687
  const proc = (0, child_process_1.spawn)(ffmpegPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
2691
2688
  let stderr = '';
@@ -2827,7 +2824,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
2827
2824
  return [];
2828
2825
  }
2829
2826
  this.logger.log(`HLS audio: pinning track LANGUAGE="${matchedLang}" (preferred="${preferred}", available=${langs.join(',')})`);
2830
- return ['-map', '0:v', '-map', `0:m:language:${matchedLang}`];
2827
+ return (0, ffmpeg_hls_args_1.buildAudioLanguageMaps)(matchedLang, (0, ffmpeg_hls_args_1.highestBandwidthVariant)(body));
2831
2828
  }
2832
2829
  catch (err) {
2833
2830
  this.logger.debug?.(`HLS audio pre-parse failed: ${err?.message || err}`);
@@ -3075,7 +3072,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3075
3072
  finalDir = path.join(path.resolve(settings.sonarrRootPath), seriesFolder, seasonFolder);
3076
3073
  }
3077
3074
  }
3078
- const tempDir = path.resolve(settings.downloadPath);
3075
+ const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
3079
3076
  const linkErrors = [];
3080
3077
  const linkFailures = [];
3081
3078
  const tag = this.epTag(entry.title, epLabel);
@@ -3138,7 +3135,7 @@ let DownloadService = DownloadService_1 = class DownloadService {
3138
3135
  if (settings.moveEp && settings.radarrRootPath) {
3139
3136
  finalDir = path.join(path.resolve(settings.radarrRootPath), path.basename(movie.path));
3140
3137
  }
3141
- const tempDir = path.resolve(settings.downloadPath);
3138
+ const tempDir = (0, download_paths_1.resolveDownloadDir)(settings.downloadPath, this.paths);
3142
3139
  const linkErrors = [];
3143
3140
  const linkFailures = [];
3144
3141
  for (const rawLink of candidates) {
@@ -1,6 +1,10 @@
1
+ /** Why a request is made. Named by the caller, never inferred from a host. */
2
+ export type ExitPurpose = 'hoster-resolution';
1
3
  /** What the work running right now belongs to: a watched entry, and the exit it insists on. */
2
4
  export interface EgressContextValue {
3
5
  entryId?: string;
6
+ /** What the work is for, stated by its call site. `hoster-resolution` (hoster pages, link decoders, headless player, captcha) is the only purpose a home-IP exit serves; media downloads never carry it. */
7
+ purpose?: ExitPurpose;
4
8
  /** Present = a chain of exactly this exit. Absent = rules and default as usual. */
5
9
  egressId?: string;
6
10
  }
@@ -21,6 +21,19 @@ export type EntryEgressPatch = {
21
21
  egressId: string | undefined;
22
22
  };
23
23
  /** The `egressId` of a watched-entry PATCH: absent leaves it, null or empty clears it, otherwise it must be a known exit. */
24
- export declare function parseEntryEgressPatch(body: unknown, known: ReadonlySet<string>): EntryEgressPatch;
24
+ export declare function parseEntryEgressPatch(body: unknown, known: ReadonlySet<string>, homeOnly?: ReadonlySet<string>): EntryEgressPatch;
25
25
  /** Validate a settings patch against the known exit ids and return the new settings. */
26
- export declare function parseSettingsPatch(body: unknown, current: VpnSettings, knownEgressIds: ReadonlySet<string>): VpnSettings;
26
+ export declare function parseSettingsPatch(body: unknown, current: VpnSettings, knownEgressIds: ReadonlySet<string>, homeOnly?: ReadonlySet<string>): VpnSettings;
27
+ /** What a home-connection exit would be used for besides hoster link resolution and captcha, to name it in a refusal. */
28
+ export interface HomeIpUsage {
29
+ defaultEgressId?: string;
30
+ ruleExitIds: readonly string[];
31
+ /** Watched entries that pin their traffic to an exit. */
32
+ entryEgressIds: readonly string[];
33
+ captchaFallbackEgressId?: string;
34
+ }
35
+ /**
36
+ * The flag is allowed only on an exit whose single role is captcha solving: it is the captcha fallback
37
+ * exit, and it is not the default, in a rule, or pinned by a watched item. Throws with the reason.
38
+ */
39
+ export declare function assertHomeIpAllowed(egressId: string, name: string, usage: HomeIpUsage): void;
@@ -6,6 +6,7 @@ exports.parseNewEgress = parseNewEgress;
6
6
  exports.applyEgressPatch = applyEgressPatch;
7
7
  exports.parseEntryEgressPatch = parseEntryEgressPatch;
8
8
  exports.parseSettingsPatch = parseSettingsPatch;
9
+ exports.assertHomeIpAllowed = assertHomeIpAllowed;
9
10
  const wireproxy_config_1 = require("./wireproxy-config");
10
11
  const NORD_DNS = '103.86.96.100';
11
12
  const DEFAULT_DNS = '1.1.1.1';
@@ -81,6 +82,9 @@ function buildEgress(fields, resolved) {
81
82
  const presetId = optionalText(fields.presetId);
82
83
  const type = fields.type;
83
84
  const base = presetId ? { name, presetId } : { name };
85
+ if (fields.homeIpByDesign === true && type !== 'socks5' && type !== 'http') {
86
+ throw new EgressInputError('Only a SOCKS5 or HTTP exit can use the home connection on purpose');
87
+ }
84
88
  if (type === 'direct')
85
89
  return { ...base, type };
86
90
  if (type === 'wireguard')
@@ -89,6 +93,8 @@ function buildEgress(fields, resolved) {
89
93
  throw new EgressInputError('type must be one of direct, socks5, http, wireguard');
90
94
  const username = optionalText(fields.username);
91
95
  const password = typeof fields.password === 'string' && fields.password ? fields.password : undefined;
96
+ if (fields.homeIpByDesign !== undefined && typeof fields.homeIpByDesign !== 'boolean')
97
+ throw new EgressInputError('homeIpByDesign must be a boolean');
92
98
  return {
93
99
  ...base,
94
100
  type,
@@ -96,6 +102,7 @@ function buildEgress(fields, resolved) {
96
102
  port: port(fields.port),
97
103
  ...(username ? { username } : {}),
98
104
  ...(password ? { password } : {}),
105
+ ...(fields.homeIpByDesign === true ? { homeIpByDesign: true } : {}),
99
106
  };
100
107
  }
101
108
  function parseNewEgress(body, resolved) {
@@ -113,7 +120,7 @@ function applyEgressPatch(existing, patch, resolved) {
113
120
  if (!isRecord(patch))
114
121
  throw new EgressInputError('A JSON object is required');
115
122
  const merged = { ...existing };
116
- for (const key of ['name', 'presetId', 'type', 'host', 'port', 'username', 'address', 'publicKey', 'endpoint', 'dns', 'mtu', 'nord']) {
123
+ for (const key of ['name', 'presetId', 'type', 'host', 'port', 'username', 'address', 'publicKey', 'endpoint', 'dns', 'mtu', 'nord', 'homeIpByDesign']) {
117
124
  if (key in patch)
118
125
  merged[key] = patch[key];
119
126
  }
@@ -149,7 +156,7 @@ function parseRules(value, known) {
149
156
  });
150
157
  }
151
158
  /** The `egressId` of a watched-entry PATCH: absent leaves it, null or empty clears it, otherwise it must be a known exit. */
152
- function parseEntryEgressPatch(body, known) {
159
+ function parseEntryEgressPatch(body, known, homeOnly = new Set()) {
153
160
  if (!isRecord(body) || !('egressId' in body))
154
161
  return { change: false };
155
162
  const id = body.egressId;
@@ -159,10 +166,12 @@ function parseEntryEgressPatch(body, known) {
159
166
  throw new EgressInputError('egressId must be an exit id or null');
160
167
  if (!known.has(id))
161
168
  throw new EgressInputError('egressId names an unknown exit');
169
+ if (homeOnly.has(id))
170
+ throw new EgressInputError('That exit uses the home connection on purpose and serves hoster link resolution and captcha only');
162
171
  return { change: true, egressId: id };
163
172
  }
164
173
  /** Validate a settings patch against the known exit ids and return the new settings. */
165
- function parseSettingsPatch(body, current, knownEgressIds) {
174
+ function parseSettingsPatch(body, current, knownEgressIds, homeOnly = new Set()) {
166
175
  if (!isRecord(body))
167
176
  throw new EgressInputError('A JSON object is required');
168
177
  let strictMode = current.strictMode;
@@ -176,6 +185,8 @@ function parseSettingsPatch(body, current, knownEgressIds) {
176
185
  const id = body.defaultEgressId;
177
186
  if (id === null || id === '')
178
187
  defaultEgressId = undefined;
188
+ else if (typeof id === 'string' && homeOnly.has(id))
189
+ throw new EgressInputError('That exit uses the home connection on purpose and serves hoster link resolution and captcha only: it cannot be the default');
179
190
  else if (typeof id === 'string' && knownEgressIds.has(id))
180
191
  defaultEgressId = id;
181
192
  else
@@ -192,5 +203,23 @@ function parseSettingsPatch(body, current, knownEgressIds) {
192
203
  throw new EgressInputError('captchaFallbackEgressId names an unknown exit');
193
204
  }
194
205
  const rules = 'rules' in body ? parseRules(body.rules, knownEgressIds) : current.rules;
206
+ if ('rules' in body && rules.some((r) => r.egressIds.some((id) => homeOnly.has(id)))) {
207
+ throw new EgressInputError('A rule names an exit that uses the home connection on purpose and serves hoster link resolution and captcha only');
208
+ }
195
209
  return { version: 2, defaultEgressId, strictMode, rules, captchaFallbackEgressId };
196
210
  }
211
+ /**
212
+ * The flag is allowed only on an exit whose single role is captcha solving: it is the captcha fallback
213
+ * exit, and it is not the default, in a rule, or pinned by a watched item. Throws with the reason.
214
+ */
215
+ function assertHomeIpAllowed(egressId, name, usage) {
216
+ if (usage.captchaFallbackEgressId !== egressId) {
217
+ throw new EgressInputError(`"${name}" must be the captcha fallback exit before it can use the home connection on purpose`);
218
+ }
219
+ if (usage.defaultEgressId === egressId)
220
+ throw new EgressInputError(`"${name}" is the default exit: it cannot use the home connection on purpose`);
221
+ if (usage.ruleExitIds.includes(egressId))
222
+ throw new EgressInputError(`"${name}" is used by a host rule: it cannot use the home connection on purpose`);
223
+ if (usage.entryEgressIds.includes(egressId))
224
+ throw new EgressInputError(`"${name}" is pinned by a watched item: it cannot use the home connection on purpose`);
225
+ }
@@ -1,4 +1,8 @@
1
- export type LeakVerdict = 'leak' | 'ok' | 'unknown';
1
+ /**
2
+ * `home`: the exit reports the direct IP and is flagged `homeIpByDesign`. That is the expected state of
3
+ * the captcha exit the operator chose to run on the home connection, informational, never a fault.
4
+ */
5
+ export type LeakVerdict = 'leak' | 'ok' | 'unknown' | 'home';
2
6
  /**
3
7
  * Compare an exit's egress IP with the direct one. Equal means the traffic
4
8
  * is not leaving through the exit. A failed lookup is `unknown`, never a
@@ -17,3 +17,29 @@ export interface HlsInputArgsOptions {
17
17
  readonly proxyUrl?: string;
18
18
  }
19
19
  export declare function buildHlsInputArgs({ url, headers, proxyUrl }: HlsInputArgsOptions): string[];
20
+ /**
21
+ * ffmpeg output arguments for an HLS download into mp4, as a stream copy.
22
+ *
23
+ * Without `audioMaps` nothing is mapped: ffmpeg's own selection keeps the best video and one audio
24
+ * stream, which is what a download wants. `-sn` and `-dn` keep subtitle and data streams out whatever
25
+ * the selection would do, because mp4 cannot hold a webvtt subtitle or timed ID3 and the muxer dies
26
+ * with "Could not write header (incorrect codec parameters ?)".
27
+ *
28
+ * `audioMaps` (see `buildAudioLanguageMaps`) pins one video variant and one audio rendition.
29
+ */
30
+ export declare function buildHlsOutputArgs(audioMaps: readonly string[], outputPath: string): string[];
31
+ /**
32
+ * Exactly one video variant plus the audio rendition tagged with `language`.
33
+ *
34
+ * The audio selector is an AUDIO one (`0:a:m:...`): a subtitle tagged with the same language must not
35
+ * match. ffmpeg's HLS demuxer makes one program per variant, numbered in playlist order, so
36
+ * `0:p:<variantIndex>:v` is that variant's video and nothing else. Without a variant index the first
37
+ * video stream is taken.
38
+ */
39
+ export declare function buildAudioLanguageMaps(language: string, variantIndex?: number): string[];
40
+ /**
41
+ * Position, among the `#EXT-X-STREAM-INF` entries of a master playlist, of the one with the highest
42
+ * BANDWIDTH (the best quality). A variant that declares a RESOLUTION is preferred over one that does
43
+ * not, so an audio-only variant is never the video pick. Undefined when the playlist lists none.
44
+ */
45
+ export declare function highestBandwidthVariant(masterBody: string): number | undefined;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildHlsInputArgs = buildHlsInputArgs;
4
+ exports.buildHlsOutputArgs = buildHlsOutputArgs;
5
+ exports.buildAudioLanguageMaps = buildAudioLanguageMaps;
6
+ exports.highestBandwidthVariant = highestBandwidthVariant;
4
7
  const RW_TIMEOUT_US = '15000000';
5
8
  const RECONNECT_DELAY_MAX_S = '5';
6
9
  function buildHlsInputArgs({ url, headers, proxyUrl }) {
@@ -15,3 +18,59 @@ function buildHlsInputArgs({ url, headers, proxyUrl }) {
15
18
  '-i', url,
16
19
  ];
17
20
  }
21
+ /**
22
+ * ffmpeg output arguments for an HLS download into mp4, as a stream copy.
23
+ *
24
+ * Without `audioMaps` nothing is mapped: ffmpeg's own selection keeps the best video and one audio
25
+ * stream, which is what a download wants. `-sn` and `-dn` keep subtitle and data streams out whatever
26
+ * the selection would do, because mp4 cannot hold a webvtt subtitle or timed ID3 and the muxer dies
27
+ * with "Could not write header (incorrect codec parameters ?)".
28
+ *
29
+ * `audioMaps` (see `buildAudioLanguageMaps`) pins one video variant and one audio rendition.
30
+ */
31
+ function buildHlsOutputArgs(audioMaps, outputPath) {
32
+ return [
33
+ ...audioMaps,
34
+ '-dn',
35
+ '-sn',
36
+ '-c', 'copy',
37
+ '-bsf:a', 'aac_adtstoasc',
38
+ '-y',
39
+ outputPath,
40
+ ];
41
+ }
42
+ /**
43
+ * Exactly one video variant plus the audio rendition tagged with `language`.
44
+ *
45
+ * The audio selector is an AUDIO one (`0:a:m:...`): a subtitle tagged with the same language must not
46
+ * match. ffmpeg's HLS demuxer makes one program per variant, numbered in playlist order, so
47
+ * `0:p:<variantIndex>:v` is that variant's video and nothing else. Without a variant index the first
48
+ * video stream is taken.
49
+ */
50
+ function buildAudioLanguageMaps(language, variantIndex) {
51
+ return [
52
+ '-map', variantIndex === undefined ? '0:v:0' : `0:p:${variantIndex}:v`,
53
+ '-map', `0:a:m:language:${language}`,
54
+ ];
55
+ }
56
+ /**
57
+ * Position, among the `#EXT-X-STREAM-INF` entries of a master playlist, of the one with the highest
58
+ * BANDWIDTH (the best quality). A variant that declares a RESOLUTION is preferred over one that does
59
+ * not, so an audio-only variant is never the video pick. Undefined when the playlist lists none.
60
+ */
61
+ function highestBandwidthVariant(masterBody) {
62
+ const variants = masterBody
63
+ .split(/\r?\n/)
64
+ .filter((line) => line.startsWith('#EXT-X-STREAM-INF:'))
65
+ .map((line, index) => ({
66
+ index,
67
+ bandwidth: Number(line.match(/(?:^|[:,])BANDWIDTH=(\d+)/i)?.[1] ?? 0),
68
+ hasResolution: /[:,]RESOLUTION=/i.test(line),
69
+ }));
70
+ const candidates = variants.some((v) => v.hasResolution) ? variants.filter((v) => v.hasResolution) : variants;
71
+ let best;
72
+ for (const v of candidates)
73
+ if (!best || v.bandwidth > best.bandwidth)
74
+ best = v;
75
+ return best?.index;
76
+ }
@@ -2,11 +2,13 @@ import { OnApplicationBootstrap, OnModuleDestroy } from '@nestjs/common';
2
2
  import type { Binaries, WireproxyBinary } from '../ports/binaries';
3
3
  import type { HostInfo } from '../ports/host-info';
4
4
  import { Dispatcher } from 'undici';
5
- import { EgressType, VpnSettings, WireguardEgress } from '../types';
5
+ import { Egress, EgressType, VpnSettings, WireguardEgress } from '../types';
6
6
  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 { LeakVerdict } from './egress/leak-guard';
11
+ import type { ExitPurpose } from './egress/egress-context';
10
12
  import { EgressGate } from './egress/egress-gate';
11
13
  import { SupervisorState, WireproxySupervisor } from './egress/wireproxy-supervisor';
12
14
  export interface VpnTestResult {
@@ -21,6 +23,8 @@ export interface ExitStatus {
21
23
  type: EgressType;
22
24
  ready: boolean;
23
25
  error?: string;
26
+ /** Last leak-guard verdict; `home` = home IP on purpose (hoster link resolution and captcha only). */
27
+ verdict?: LeakVerdict;
24
28
  }
25
29
  export interface VpnStatus {
26
30
  strictMode: boolean;
@@ -67,6 +71,7 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
67
71
  private settings;
68
72
  private tunnels;
69
73
  private readonly leakFlagged;
74
+ private readonly homeWarned;
70
75
  private leakTimer;
71
76
  private gateRetryTimer;
72
77
  /** The last leak-check answer per exit. Absent means unknown: nothing has compared its IP yet. */
@@ -92,7 +97,7 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
92
97
  * that produced its link. A pinned exit that is gone or not ready fails the
93
98
  * download: it never falls back to the routed or direct network.
94
99
  */
95
- getDispatcherForExit(egressId: string): Dispatcher;
100
+ getDispatcherForExit(egressId: string, purpose?: ExitPurpose): Dispatcher;
96
101
  /** HTTP proxy URL on 127.0.0.1 for ffmpeg `-http_proxy`; undefined only for an explicit direct exit or no chain. */
97
102
  getFfmpegProxyUrl(url: string, egressId?: string): string | undefined;
98
103
  /**
@@ -177,4 +182,6 @@ export declare class VpnService implements OnApplicationBootstrap, OnModuleDestr
177
182
  private updateGate;
178
183
  protected runTest(dispatcher: Dispatcher): Promise<VpnTestResult>;
179
184
  }
185
+ /** The operator ran this exit on the home connection on purpose (hoster link resolution and captcha only). */
186
+ export declare function isHomeByDesign(egress: Egress): boolean;
180
187
  export {};
@@ -15,6 +15,7 @@ var VpnService_1;
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.VpnService = void 0;
17
17
  exports.errorWithCause = errorWithCause;
18
+ exports.isHomeByDesign = isHomeByDesign;
18
19
  const common_1 = require("@nestjs/common");
19
20
  const tokens_1 = require("../ports/tokens");
20
21
  const logger_1 = require("../ports/logger");
@@ -90,6 +91,7 @@ let VpnService = VpnService_1 = class VpnService {
90
91
  this.directAgent = new undici_1.Agent();
91
92
  this.tunnels = new Map();
92
93
  this.leakFlagged = new Map();
94
+ this.homeWarned = new Set();
93
95
  /** The last leak-check answer per exit. Absent means unknown: nothing has compared its IP yet. */
94
96
  this.verdicts = new Map();
95
97
  this.leakGuardActive = false;
@@ -180,6 +182,7 @@ let VpnService = VpnService_1 = class VpnService {
180
182
  type: h.egress.type,
181
183
  ready: h.ready,
182
184
  error: h.error,
185
+ verdict: this.verdictOf(h.egress.id),
183
186
  }));
184
187
  return {
185
188
  strictMode: this.settings.strictMode,
@@ -202,16 +205,16 @@ let VpnService = VpnService_1 = class VpnService {
202
205
  * that produced its link. A pinned exit that is gone or not ready fails the
203
206
  * download: it never falls back to the routed or direct network.
204
207
  */
205
- getDispatcherForExit(egressId) {
208
+ getDispatcherForExit(egressId, purpose) {
206
209
  // An entry override beats a pinned link exit: precedence is override > pin > rules.
207
210
  const id = egress_context_1.egressContext.current()?.egressId ?? egressId;
208
211
  const waiting = this.waitingFor('pinned download');
209
212
  if (waiting)
210
213
  throw waiting;
211
- const handle = this.effective(this.exits.get(id));
214
+ const handle = this.effective(this.exits.get(id), purpose);
212
215
  if (handle?.ready)
213
216
  return handle.dispatcher;
214
- throw this.pinnedError(id, 'pinned download');
217
+ throw this.pinnedError(id, 'pinned download', purpose);
215
218
  }
216
219
  /** HTTP proxy URL on 127.0.0.1 for ffmpeg `-http_proxy`; undefined only for an explicit direct exit or no chain. */
217
220
  getFfmpegProxyUrl(url, egressId) {
@@ -391,6 +394,12 @@ let VpnService = VpnService_1 = class VpnService {
391
394
  }
392
395
  }
393
396
  this.exits = next;
397
+ for (const handle of next.values()) {
398
+ if (!isHomeByDesign(handle.egress) || this.homeWarned.has(handle.egress.id))
399
+ continue;
400
+ this.homeWarned.add(handle.egress.id);
401
+ this.logger.warn(`Exit "${handle.egress.name}" uses the home connection on purpose: it serves hoster link resolution and captcha only (media downloads always go through the VPN) and is exempt from the leak check`);
402
+ }
394
403
  for (const id of [...this.leakFlagged.keys()])
395
404
  if (!next.has(id))
396
405
  this.leakFlagged.delete(id);
@@ -407,6 +416,11 @@ let VpnService = VpnService_1 = class VpnService {
407
416
  const id = handle.egress.id;
408
417
  if (!handle.ready)
409
418
  return handle;
419
+ if (isHomeByDesign(handle.egress)) {
420
+ // The home connection is this exit's purpose: the leak guard never takes it out of service.
421
+ this.leakFlagged.delete(id);
422
+ return handle;
423
+ }
410
424
  const flagged = this.leakFlagged.get(id);
411
425
  if (flagged)
412
426
  return { ...handle, ready: false, error: flagged };
@@ -460,8 +474,8 @@ let VpnService = VpnService_1 = class VpnService {
460
474
  ids.add(settings.captchaFallbackEgressId);
461
475
  return [...ids];
462
476
  }
463
- pinnedError(egressId, host) {
464
- const handle = this.effective(this.exits.get(egressId));
477
+ pinnedError(egressId, host, purpose) {
478
+ const handle = this.effective(this.exits.get(egressId), purpose);
465
479
  return new egress_router_1.EgressNotReadyError(egressId, handle?.egress.name ?? egressId, host, handle ? handle.error ?? 'not ready' : 'exit no longer exists');
466
480
  }
467
481
  /** The exit that serves `url`: the pinned one, else the one routing picks. Undefined = direct (no chain). */
@@ -702,12 +716,17 @@ let VpnService = VpnService_1 = class VpnService {
702
716
  for (const handle of targets) {
703
717
  const id = handle.egress.id;
704
718
  const exitIp = await this.lookupEgressIp({ kind: 'exit', egressId: id });
705
- const verdict = (0, leak_guard_1.evaluateLeak)({ exitIp, directIp });
719
+ const raw = (0, leak_guard_1.evaluateLeak)({ exitIp, directIp });
720
+ // A home-connection exit reporting the direct IP is what the operator asked for.
721
+ const verdict = raw === 'leak' && isHomeByDesign(handle.egress) ? 'home' : raw;
706
722
  // A failed lookup says nothing: it never revokes a verdict a check already gave, and it
707
723
  // never grants one. A host that requires an exit therefore stays closed until one answers.
708
724
  if (verdict !== 'unknown')
709
725
  this.verdicts.set(id, verdict);
710
- if (verdict === 'leak' && !this.leakFlagged.has(id)) {
726
+ if (verdict === 'home') {
727
+ this.leakFlagged.delete(id);
728
+ }
729
+ else if (verdict === 'leak' && !this.leakFlagged.has(id)) {
711
730
  const reason = 'leak guard: this exit reports the same egress IP as the direct network';
712
731
  this.leakFlagged.set(id, reason);
713
732
  this.markNotReady(id, reason);
@@ -734,7 +753,13 @@ let VpnService = VpnService_1 = class VpnService {
734
753
  * An exit as a request may use it. On a host that requires an exit, a VPN exit serves only
735
754
  * after the leak check has compared its IP with the direct one and found them different.
736
755
  */
737
- effective(handle) {
756
+ effective(handle, purpose) {
757
+ if (handle && isHomeByDesign(handle.egress)) {
758
+ // The home connection serves hoster link resolution and captcha and nothing else, on every host, gate or not.
759
+ if ((purpose ?? egress_context_1.egressContext.current()?.purpose) === 'hoster-resolution')
760
+ return handle;
761
+ return { ...handle, ready: false, error: 'this exit uses the home connection on purpose and serves hoster link resolution and captcha only' };
762
+ }
738
763
  if (!handle || !this.gate.required || handle.egress.type === 'direct' || !handle.ready)
739
764
  return handle;
740
765
  if (this.verdictOf(handle.egress.id) === 'ok')
@@ -761,7 +786,7 @@ let VpnService = VpnService_1 = class VpnService {
761
786
  if (!handle.ready)
762
787
  return { open: false, reason: `the default exit "${handle.egress.name}" is not ready: ${handle.error ?? 'unknown reason'}` };
763
788
  const verdict = this.verdictOf(id);
764
- if (verdict === 'leak')
789
+ if (verdict === 'leak' || verdict === 'home')
765
790
  return { open: false, reason: `the default exit "${handle.egress.name}" leaks: it reports the direct IP` };
766
791
  if (verdict === 'unknown')
767
792
  return { open: false, reason: `the leak check has not yet confirmed the default exit "${handle.egress.name}"` };
@@ -824,3 +849,7 @@ exports.VpnService = VpnService = VpnService_1 = __decorate([
824
849
  __metadata("design:paramtypes", [vpn_providers_repository_1.VpnProvidersRepository,
825
850
  vpn_settings_repository_1.VpnSettingsRepository, Object, Object, egress_gate_1.EgressGate])
826
851
  ], VpnService);
852
+ /** The operator ran this exit on the home connection on purpose (hoster link resolution and captcha only). */
853
+ function isHomeByDesign(egress) {
854
+ return egress.type !== 'direct' && egress.type !== 'wireguard' && egress.homeIpByDesign === true;
855
+ }
package/dist/types.d.ts CHANGED
@@ -278,6 +278,13 @@ export interface ProxyEgress extends EgressBase {
278
278
  port: number;
279
279
  username?: string;
280
280
  password?: string;
281
+ /**
282
+ * An operator decision: this exit leaves with the home connection ON PURPOSE, and serves
283
+ * hoster link resolution and captcha only (media downloads always go through the VPN). The leak guard
284
+ * expects the direct IP from it, and no other request may use it.
285
+ * Allowed only on the captcha fallback exit, never on the default or a rule's exit.
286
+ */
287
+ homeIpByDesign?: boolean;
281
288
  }
282
289
  /** NordVPN helper input: a country or a server hostname, resolved through api.nordvpn.com. */
283
290
  export interface NordTarget {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dominevo/series-scraper-core",
3
- "version": "0.0.89",
3
+ "version": "0.0.91",
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",