@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
@@ -1,14 +1,15 @@
1
1
  import { Response } from 'express';
2
- import type { LogFiles } from '../ports/log-files';
2
+ import { type LogFiles } from '../ports/log-files';
3
+ export declare function clampPage(raw: string | undefined): number;
3
4
  export declare class LogsController {
4
5
  private readonly logFiles?;
5
6
  constructor(logFiles?: LogFiles | undefined);
6
- get(page?: string, level?: string, file?: string): import("../ports/log-files").LogPage;
7
- listFiles(): import("../ports/log-files").LogFileInfo[];
8
- raw(file: string | undefined, res: Response): void;
9
- clear(): {
7
+ get(page?: string, level?: string, file?: string): Promise<import("../ports/log-files").LogPage>;
8
+ listFiles(): import("../ports/log-files").MaybePromise<import("../ports/log-files").LogFileInfo[]>;
9
+ raw(file: string | undefined, res: Response): Promise<void>;
10
+ clear(): Promise<{
10
11
  ok: boolean;
11
- };
12
+ }>;
12
13
  /** The host's log files, or a plain 404 when it keeps none. */
13
14
  private files;
14
15
  }
@@ -13,28 +13,45 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.LogsController = void 0;
16
+ exports.clampPage = clampPage;
16
17
  const common_1 = require("@nestjs/common");
17
18
  const tokens_1 = require("../ports/tokens");
19
+ const log_files_1 = require("../ports/log-files");
20
+ /** The newest page is 0; a negative, fractional, NaN or absurd value is brought into range. */
21
+ const MAX_LOG_PAGE = 10_000;
22
+ function clampPage(raw) {
23
+ const n = Math.floor(Number(raw));
24
+ if (!Number.isFinite(n) || n < 0)
25
+ return 0;
26
+ return Math.min(n, MAX_LOG_PAGE);
27
+ }
18
28
  let LogsController = class LogsController {
19
29
  constructor(logFiles) {
20
30
  this.logFiles = logFiles;
21
31
  }
22
- get(page, level, file) {
23
- return this.files().getPage(Number(page) || 0, level || undefined, file || undefined);
32
+ async get(page, level, file) {
33
+ return this.files().getPage(clampPage(page), level || undefined, file || undefined);
24
34
  }
25
35
  listFiles() {
26
36
  return this.files().listFiles();
27
37
  }
28
- raw(file, res) {
29
- const result = this.files().getRaw(file);
38
+ async raw(file, res) {
39
+ const result = await this.files().getRaw(file);
30
40
  if (!result)
31
41
  throw new common_1.HttpException('Log file not found or compressed', common_1.HttpStatus.NOT_FOUND);
32
42
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
33
43
  res.setHeader('Content-Disposition', `attachment; filename="${result.fileName}"`);
34
44
  res.send(result.content);
35
45
  }
36
- clear() {
37
- this.files().clear();
46
+ async clear() {
47
+ try {
48
+ await this.files().clear();
49
+ }
50
+ catch (error) {
51
+ if (error instanceof log_files_1.LogFilesRefused)
52
+ throw new common_1.HttpException(error.message, common_1.HttpStatus.CONFLICT);
53
+ throw error;
54
+ }
38
55
  return { ok: true };
39
56
  }
40
57
  /** The host's log files, or a plain 404 when it keeps none. */
@@ -52,7 +69,7 @@ __decorate([
52
69
  __param(2, (0, common_1.Query)('file')),
53
70
  __metadata("design:type", Function),
54
71
  __metadata("design:paramtypes", [String, String, String]),
55
- __metadata("design:returntype", void 0)
72
+ __metadata("design:returntype", Promise)
56
73
  ], LogsController.prototype, "get", null);
57
74
  __decorate([
58
75
  (0, common_1.Get)('files'),
@@ -66,13 +83,13 @@ __decorate([
66
83
  __param(1, (0, common_1.Res)()),
67
84
  __metadata("design:type", Function),
68
85
  __metadata("design:paramtypes", [Object, Object]),
69
- __metadata("design:returntype", void 0)
86
+ __metadata("design:returntype", Promise)
70
87
  ], LogsController.prototype, "raw", null);
71
88
  __decorate([
72
89
  (0, common_1.Delete)(),
73
90
  __metadata("design:type", Function),
74
91
  __metadata("design:paramtypes", []),
75
- __metadata("design:returntype", void 0)
92
+ __metadata("design:returntype", Promise)
76
93
  ], LogsController.prototype, "clear", null);
77
94
  exports.LogsController = LogsController = __decorate([
78
95
  (0, common_1.Controller)('api/logs'),
@@ -36,6 +36,8 @@ export declare class VpnController {
36
36
  rules: import("../types").HostRule[];
37
37
  }>;
38
38
  getStatus(): import("../services/vpn.service").VpnStatus;
39
+ /** Whether work may go out: open, or closed with the reason. Always answers, whatever the gate says. */
40
+ getGate(): import("..").GateStatus;
39
41
  getBlocks(): import("../services/egress/block-registry").ActiveBlock[];
40
42
  /** Forget active (host, exit) blocks: one pair, a host, an exit, or all. */
41
43
  clearBlocks(host?: string, egressId?: string): {
@@ -34,12 +34,12 @@ function validated(fn) {
34
34
  }
35
35
  }
36
36
  /** Resolve a NordVPN country/server named in a body, when it needs it. */
37
- async function resolveNord(body) {
37
+ async function resolveNord(vpn, body) {
38
38
  const target = (0, egress_input_1.nordTargetOf)(body);
39
39
  if (!target)
40
40
  return undefined;
41
41
  try {
42
- return await (0, nord_lookup_1.resolveNordTarget)(target);
42
+ return await (0, nord_lookup_1.resolveNordTarget)(target, (url) => vpn.fetchProviderJson(url));
43
43
  }
44
44
  catch (err) {
45
45
  throw new common_1.HttpException(`NordVPN lookup failed: ${err instanceof Error ? err.message : String(err)}`, common_1.HttpStatus.BAD_REQUEST);
@@ -61,7 +61,7 @@ let VpnController = class VpnController {
61
61
  return this.providersRepo.getAll().map(egress_migration_1.toEgressView);
62
62
  }
63
63
  async createProvider(body) {
64
- const resolved = await resolveNord(body);
64
+ const resolved = await resolveNord(this.vpn, body);
65
65
  const created = this.providersRepo.create(validated(() => (0, egress_input_1.parseNewEgress)(body, resolved)));
66
66
  await this.vpn.reload();
67
67
  return (0, egress_migration_1.toEgressView)(created);
@@ -70,7 +70,7 @@ let VpnController = class VpnController {
70
70
  const existing = this.providersRepo.getById(id);
71
71
  if (!existing)
72
72
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
73
- const resolved = await resolveNord(body);
73
+ const resolved = await resolveNord(this.vpn, body);
74
74
  const saved = this.providersRepo.update(id, validated(() => (0, egress_input_1.applyEgressPatch)(existing, body, resolved)));
75
75
  if (!saved)
76
76
  throw new common_1.HttpException('Exit not found', common_1.HttpStatus.NOT_FOUND);
@@ -111,6 +111,10 @@ let VpnController = class VpnController {
111
111
  getStatus() {
112
112
  return this.vpn.getStatus();
113
113
  }
114
+ /** Whether work may go out: open, or closed with the reason. Always answers, whatever the gate says. */
115
+ getGate() {
116
+ return this.vpn.gate.status();
117
+ }
114
118
  getBlocks() {
115
119
  return this.vpn.getBlocks();
116
120
  }
@@ -181,6 +185,12 @@ __decorate([
181
185
  __metadata("design:paramtypes", []),
182
186
  __metadata("design:returntype", void 0)
183
187
  ], VpnController.prototype, "getStatus", null);
188
+ __decorate([
189
+ (0, common_1.Get)('gate'),
190
+ __metadata("design:type", Function),
191
+ __metadata("design:paramtypes", []),
192
+ __metadata("design:returntype", void 0)
193
+ ], VpnController.prototype, "getGate", null);
184
194
  __decorate([
185
195
  (0, common_1.Get)('blocks'),
186
196
  __metadata("design:type", Function),
@@ -0,0 +1,15 @@
1
+ import { type StateCollectionName } from '../ports/state-store';
2
+ /** What a Docker data directory holds, split the way the SecretStore maps it. */
3
+ export interface DockerLayout {
4
+ /** Every collection as the core sees it: secret fields removed. `undefined` when its file is absent. */
5
+ collections: Record<StateCollectionName, unknown>;
6
+ /** Every secret by the name the core asks for it under (`sonarrApiKey`, `egress.<id>.password`, ...). */
7
+ secrets: Record<string, string>;
8
+ /** File names under `plugins/` that the plugin loader reads (`*.js` and `*.json`, as the plugin loader reads them; no dotfiles such as a tar's `._x.js`), sorted. */
9
+ plugins: string[];
10
+ }
11
+ /**
12
+ * Read a container data directory (`<name>.json` per collection, `plugins/*.js|json`) without
13
+ * starting anything. Pure over the directory: nothing is written, the directory is a parameter.
14
+ */
15
+ export declare function readDockerLayout(dir: string): DockerLayout;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readDockerLayout = readDockerLayout;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const state_store_1 = require("../ports/state-store");
7
+ const secret_layout_1 = require("./secret-layout");
8
+ function readCollectionFile(dir, name) {
9
+ const file = (0, path_1.join)(dir, `${name}.json`);
10
+ if (!(0, fs_1.existsSync)(file))
11
+ return undefined;
12
+ try {
13
+ return JSON.parse((0, fs_1.readFileSync)(file, 'utf-8'));
14
+ }
15
+ catch {
16
+ // The file name only, and no cause: a parse error quotes the text, and the text may hold a secret.
17
+ throw new Error(`${name}.json is not valid JSON or cannot be read`);
18
+ }
19
+ }
20
+ /**
21
+ * Read a container data directory (`<name>.json` per collection, `plugins/*.js|json`) without
22
+ * starting anything. Pure over the directory: nothing is written, the directory is a parameter.
23
+ */
24
+ function readDockerLayout(dir) {
25
+ // Spelled out so a collection added to STATE_COLLECTIONS fails the type check here.
26
+ const collections = {
27
+ settings: undefined,
28
+ table: undefined,
29
+ tags: undefined,
30
+ webhooks: undefined,
31
+ sites: undefined,
32
+ 'download-history': undefined,
33
+ 'failed-episodes': undefined,
34
+ 'partial-downloads': undefined,
35
+ 'plugin-settings': undefined,
36
+ 'vpn-settings': undefined,
37
+ 'vpn-providers': undefined,
38
+ 'captcha-challenges': undefined,
39
+ };
40
+ const secrets = {};
41
+ for (const name of state_store_1.STATE_COLLECTIONS) {
42
+ const raw = readCollectionFile(dir, name);
43
+ const owner = secret_layout_1.DOCKER_SECRET_LAYOUT.find((layout) => layout.collection === name);
44
+ collections[name] = owner ? owner.strip(raw) : raw;
45
+ if (owner)
46
+ Object.assign(secrets, owner.list(raw));
47
+ }
48
+ const pluginsDir = (0, path_1.join)(dir, 'plugins');
49
+ const plugins = (0, fs_1.existsSync)(pluginsDir)
50
+ ? (0, fs_1.readdirSync)(pluginsDir, { withFileTypes: true })
51
+ .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && (entry.name.endsWith('.js') || entry.name.endsWith('.json')))
52
+ .map((entry) => entry.name)
53
+ .sort()
54
+ : [];
55
+ return { collections, secrets, plugins };
56
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Where the container keeps each secret: inside the same JSON file as the record it
3
+ * belongs to, under the field it has always been in. `settings.json` holds the API keys
4
+ * and the Plex token, `vpn-providers.json` the proxy passwords and tunnel keys,
5
+ * `webhooks.json` the webhook headers. The core never sees those fields in a collection;
6
+ * it asks for them by name through the SecretStore.
7
+ */
8
+ export interface SecretCollection {
9
+ /** The state collection (file name without `.json`). */
10
+ readonly collection: string;
11
+ owns(secretName: string): boolean;
12
+ read(raw: unknown, secretName: string): string | undefined;
13
+ /** `raw` with the secret set (`undefined` removes it). Pure: never mutates `raw`. */
14
+ write(raw: unknown, secretName: string, value: string | undefined): unknown;
15
+ /** `raw` without any secret field. */
16
+ strip(raw: unknown): unknown;
17
+ /** Every secret `raw` holds, by the name the SecretStore knows it under. Empty values are left out. */
18
+ list(raw: unknown): Record<string, string>;
19
+ /** A freshly saved (secret-free) value with the secrets of `previousRaw` put back. */
20
+ restore(saved: unknown, previousRaw: unknown): unknown;
21
+ }
22
+ export declare const DOCKER_SECRET_LAYOUT: readonly SecretCollection[];
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DOCKER_SECRET_LAYOUT = void 0;
4
+ function isObject(value) {
5
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ }
7
+ function without(source, keys) {
8
+ return Object.fromEntries(Object.entries(source).filter(([key]) => !keys.includes(key)));
9
+ }
10
+ /** Copy `value` onto `source`, or drop the key when `value` is `undefined`. */
11
+ function withField(source, key, value) {
12
+ return value === undefined ? without(source, [key]) : { ...source, [key]: value };
13
+ }
14
+ const SETTINGS_SECRETS = ['sonarrApiKey', 'radarrApiKey', 'plexToken'];
15
+ const settingsLayout = {
16
+ collection: 'settings',
17
+ owns: (name) => SETTINGS_SECRETS.some((key) => key === name),
18
+ read: (raw, name) => {
19
+ const value = isObject(raw) ? raw[name] : undefined;
20
+ return typeof value === 'string' ? value : undefined;
21
+ },
22
+ write: (raw, name, value) => withField(isObject(raw) ? raw : {}, name, value),
23
+ list: (raw) => Object.fromEntries(SETTINGS_SECRETS.flatMap((key) => {
24
+ const value = isObject(raw) ? raw[key] : undefined;
25
+ return typeof value === 'string' && value !== '' ? [[key, value]] : [];
26
+ })),
27
+ strip: (raw) => (isObject(raw) ? without(raw, SETTINGS_SECRETS) : raw),
28
+ restore: (saved, previousRaw) => {
29
+ if (!isObject(saved) || !isObject(previousRaw))
30
+ return saved;
31
+ const kept = Object.fromEntries(SETTINGS_SECRETS.filter((key) => key in previousRaw).map((key) => [key, previousRaw[key]]));
32
+ return { ...saved, ...kept };
33
+ },
34
+ };
35
+ /** A list of records keyed by `id`, each carrying secret fields named by `fieldOf(secretName)`. */
36
+ function recordListLayout(options) {
37
+ const { collection, prefix, fields, listKey } = options;
38
+ const decode = options.decode ?? ((_field, value) => (typeof value === 'string' ? value : undefined));
39
+ const encode = options.encode ?? ((_field, value) => value);
40
+ const parse = (secretName) => {
41
+ if (!secretName.startsWith(prefix))
42
+ return undefined;
43
+ const rest = secretName.slice(prefix.length);
44
+ const dot = rest.lastIndexOf('.');
45
+ if (dot <= 0)
46
+ return undefined;
47
+ const field = rest.slice(dot + 1);
48
+ return fields.includes(field) ? { id: rest.slice(0, dot), field } : undefined;
49
+ };
50
+ const listOf = (raw) => {
51
+ const list = listKey === undefined ? raw : isObject(raw) ? raw[listKey] : undefined;
52
+ return Array.isArray(list) ? list : undefined;
53
+ };
54
+ const withList = (raw, list) => listKey === undefined ? list : { ...(isObject(raw) ? raw : {}), [listKey]: list };
55
+ const mapItems = (raw, fn) => {
56
+ const list = listOf(raw);
57
+ return list ? withList(raw, list.map((item) => (isObject(item) ? fn(item) : item))) : raw;
58
+ };
59
+ return {
60
+ collection,
61
+ owns: (name) => parse(name) !== undefined,
62
+ read: (raw, name) => {
63
+ const target = parse(name);
64
+ if (!target)
65
+ return undefined;
66
+ const item = listOf(raw)?.find((candidate) => isObject(candidate) && candidate.id === target.id);
67
+ return isObject(item) ? decode(target.field, item[target.field]) : undefined;
68
+ },
69
+ write: (raw, name, value) => {
70
+ const target = parse(name);
71
+ if (!target)
72
+ return raw;
73
+ return mapItems(raw, (item) => item.id === target.id ? withField(item, target.field, value === undefined ? undefined : encode(target.field, value)) : item);
74
+ },
75
+ list: (raw) => Object.fromEntries((listOf(raw) ?? []).flatMap((item) => {
76
+ if (!isObject(item) || typeof item.id !== 'string')
77
+ return [];
78
+ return fields.flatMap((field) => {
79
+ const value = decode(field, item[field]);
80
+ return value !== undefined && value !== '' ? [[`${prefix}${item.id}.${field}`, value]] : [];
81
+ });
82
+ })),
83
+ strip: (raw) => mapItems(raw, (item) => without(item, fields)),
84
+ restore: (saved, previousRaw) => {
85
+ const previous = listOf(previousRaw);
86
+ if (!previous)
87
+ return saved;
88
+ return mapItems(saved, (item) => {
89
+ const old = previous.find((candidate) => isObject(candidate) && candidate.id === item.id);
90
+ if (!isObject(old))
91
+ return item;
92
+ const kept = Object.fromEntries(fields.filter((field) => field in old).map((field) => [field, old[field]]));
93
+ return { ...item, ...kept };
94
+ });
95
+ },
96
+ };
97
+ }
98
+ const egressLayout = recordListLayout({
99
+ collection: 'vpn-providers',
100
+ prefix: 'egress.',
101
+ fields: ['password', 'privateKey'],
102
+ });
103
+ /** Webhook headers are an object in the file and one JSON text through the port. */
104
+ const webhookLayout = recordListLayout({
105
+ collection: 'webhooks',
106
+ prefix: 'webhook.',
107
+ fields: ['headers'],
108
+ listKey: 'webhooks',
109
+ encode: (_field, value) => {
110
+ try {
111
+ const parsed = JSON.parse(value);
112
+ return parsed;
113
+ }
114
+ catch {
115
+ return {};
116
+ }
117
+ },
118
+ decode: (_field, value) => (isObject(value) ? JSON.stringify(value) : undefined),
119
+ });
120
+ exports.DOCKER_SECRET_LAYOUT = [settingsLayout, egressLayout, webhookLayout];
package/dist/index.d.ts CHANGED
@@ -1,8 +1,16 @@
1
1
  export { createScraperModule, ScraperModule } from './scraper.module';
2
2
  export { createScraperApp } from './scraper-app';
3
3
  export * from './ports';
4
+ export { EgressGate, WaitingForVpnError } from './services/egress/egress-gate';
5
+ export type { GateStatus, GateExitStatus } from './services/egress/egress-gate';
4
6
  export { WebhookRepository } from './repositories/webhook.repository';
5
7
  export type { WebhookConfig } from './repositories/webhook.repository';
6
8
  export { buildWebhookPayload } from './services/webhook-payload';
7
9
  export { outsideEntryFetch } from './services/egress/egress-context';
8
10
  export { egressContext, runForEntry } from './services/egress/egress-context';
11
+ export { DOCKER_SECRET_LAYOUT } from './docker-layout/secret-layout';
12
+ export type { SecretCollection } from './docker-layout/secret-layout';
13
+ export { readDockerLayout } from './docker-layout/read-docker-layout';
14
+ export type { DockerLayout } from './docker-layout/read-docker-layout';
15
+ export { DEFAULT_SETTINGS } from './repositories/settings.repository';
16
+ export { scrubSecrets } from './ports/log-scrub';
package/dist/index.js CHANGED
@@ -14,13 +14,16 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.runForEntry = exports.egressContext = exports.outsideEntryFetch = exports.buildWebhookPayload = exports.WebhookRepository = exports.createScraperApp = exports.ScraperModule = exports.createScraperModule = void 0;
17
+ exports.scrubSecrets = exports.DEFAULT_SETTINGS = exports.readDockerLayout = exports.DOCKER_SECRET_LAYOUT = exports.runForEntry = exports.egressContext = exports.outsideEntryFetch = exports.buildWebhookPayload = exports.WebhookRepository = exports.WaitingForVpnError = exports.EgressGate = exports.createScraperApp = exports.ScraperModule = exports.createScraperModule = void 0;
18
18
  var scraper_module_1 = require("./scraper.module");
19
19
  Object.defineProperty(exports, "createScraperModule", { enumerable: true, get: function () { return scraper_module_1.createScraperModule; } });
20
20
  Object.defineProperty(exports, "ScraperModule", { enumerable: true, get: function () { return scraper_module_1.ScraperModule; } });
21
21
  var scraper_app_1 = require("./scraper-app");
22
22
  Object.defineProperty(exports, "createScraperApp", { enumerable: true, get: function () { return scraper_app_1.createScraperApp; } });
23
23
  __exportStar(require("./ports"), exports);
24
+ var egress_gate_1 = require("./services/egress/egress-gate");
25
+ Object.defineProperty(exports, "EgressGate", { enumerable: true, get: function () { return egress_gate_1.EgressGate; } });
26
+ Object.defineProperty(exports, "WaitingForVpnError", { enumerable: true, get: function () { return egress_gate_1.WaitingForVpnError; } });
24
27
  var webhook_repository_1 = require("./repositories/webhook.repository");
25
28
  Object.defineProperty(exports, "WebhookRepository", { enumerable: true, get: function () { return webhook_repository_1.WebhookRepository; } });
26
29
  var webhook_payload_1 = require("./services/webhook-payload");
@@ -30,3 +33,11 @@ Object.defineProperty(exports, "outsideEntryFetch", { enumerable: true, get: fun
30
33
  var egress_context_2 = require("./services/egress/egress-context");
31
34
  Object.defineProperty(exports, "egressContext", { enumerable: true, get: function () { return egress_context_2.egressContext; } });
32
35
  Object.defineProperty(exports, "runForEntry", { enumerable: true, get: function () { return egress_context_2.runForEntry; } });
36
+ var secret_layout_1 = require("./docker-layout/secret-layout");
37
+ Object.defineProperty(exports, "DOCKER_SECRET_LAYOUT", { enumerable: true, get: function () { return secret_layout_1.DOCKER_SECRET_LAYOUT; } });
38
+ var read_docker_layout_1 = require("./docker-layout/read-docker-layout");
39
+ Object.defineProperty(exports, "readDockerLayout", { enumerable: true, get: function () { return read_docker_layout_1.readDockerLayout; } });
40
+ var settings_repository_1 = require("./repositories/settings.repository");
41
+ Object.defineProperty(exports, "DEFAULT_SETTINGS", { enumerable: true, get: function () { return settings_repository_1.DEFAULT_SETTINGS; } });
42
+ var log_scrub_1 = require("./ports/log-scrub");
43
+ Object.defineProperty(exports, "scrubSecrets", { enumerable: true, get: function () { return log_scrub_1.scrubSecrets; } });
@@ -4,4 +4,10 @@ export interface HostInfo {
4
4
  version: string;
5
5
  /** The host runs behind its own egress firewall, so a request with no exit must be refused. */
6
6
  egressFirewall: boolean;
7
+ /**
8
+ * The host has no firewall but demands a VPN exit anyway: strict mode is forced on and nothing
9
+ * goes out until the default exit is up, tested and verified by the leak check. An
10
+ * application-level guarantee, not a network one. Absent means off.
11
+ */
12
+ requireExit?: boolean;
7
13
  }
@@ -14,17 +14,27 @@ export interface LogPage {
14
14
  total: number;
15
15
  page: number;
16
16
  }
17
+ /** A host that keeps its log elsewhere answers asynchronously; a file-backed one stays synchronous. */
18
+ export type MaybePromise<T> = T | Promise<T>;
17
19
  /**
18
- * Optional: a host that keeps its log in files lets the logs page list, page through,
19
- * download and clear them. Without it the logs routes answer 404 with a plain reason.
20
+ * Thrown by a `LogFiles` host for an operation its log store does not offer (a shared log
21
+ * that one application cannot wipe). The logs route answers 409 with the message, not 500.
22
+ */
23
+ export declare class LogFilesRefused extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * Optional: a host that keeps its log lets the logs page list, page through, download and
28
+ * clear it. Without it the logs routes answer 404 with a plain reason.
20
29
  */
21
30
  export interface LogFiles {
22
- listFiles(): LogFileInfo[];
23
- getPage(page: number, level?: string, fileName?: string): LogPage;
31
+ listFiles(): MaybePromise<LogFileInfo[]>;
32
+ getPage(page: number, level?: string, fileName?: string): MaybePromise<LogPage>;
24
33
  /** `null` when there is no such file or it cannot be read as text. */
25
- getRaw(fileName?: string): {
34
+ getRaw(fileName?: string): MaybePromise<{
26
35
  fileName: string;
27
36
  content: string;
28
- } | null;
29
- clear(): void;
37
+ } | null>;
38
+ /** May throw `LogFilesRefused` when the store cannot be cleared. */
39
+ clear(): MaybePromise<void>;
30
40
  }
@@ -1,2 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LogFilesRefused = void 0;
4
+ /**
5
+ * Thrown by a `LogFiles` host for an operation its log store does not offer (a shared log
6
+ * that one application cannot wipe). The logs route answers 409 with the message, not 500.
7
+ */
8
+ class LogFilesRefused extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = 'LogFilesRefused';
12
+ }
13
+ }
14
+ exports.LogFilesRefused = LogFilesRefused;
@@ -0,0 +1,2 @@
1
+ export declare const REDACTED = "[redacted]";
2
+ export declare function scrubSecrets(message: string): string;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDACTED = void 0;
4
+ exports.scrubSecrets = scrubSecrets;
5
+ /**
6
+ * Log lines name URLs, and a URL can carry a credential: a hoster's signed `token=` and `expires=`, a
7
+ * Plex `X-Plex-Token`, an `apikey` parameter, a `user:password@` prefix. This is the one place that
8
+ * removes them, applied by `ScopedLogger` to every line of every host.
9
+ */
10
+ const SECRET_PARAMS = [
11
+ 'token',
12
+ 'access_token',
13
+ 'refresh_token',
14
+ 'x-plex-token',
15
+ 'apikey',
16
+ 'api_key',
17
+ 'api-key',
18
+ 'x-api-key',
19
+ 'key',
20
+ 'secret',
21
+ 'password',
22
+ 'passwd',
23
+ 'pwd',
24
+ 'auth',
25
+ 'authorization',
26
+ 'sig',
27
+ 'signature',
28
+ 'expires',
29
+ 'hash',
30
+ 'session',
31
+ 'sessionid',
32
+ 'sid',
33
+ ];
34
+ const PARAM_VALUE = new RegExp(`([?&;\\s"'](?:${SECRET_PARAMS.join('|')}))=([^&#\\s"'<>]+)`, 'gi');
35
+ const USER_INFO = /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi;
36
+ const BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
37
+ const HEADER_VALUE = /\b(x-plex-token|x-api-key|authorization)(["']?\s*[:=]\s*["']?)[^\s"',;]+/gi;
38
+ /** A Cookie / Set-Cookie header: every pair, to the end of the line (`cf_clearance` and session ids included). */
39
+ const COOKIE_HEADER = /\b(set-cookie|cookie)(["']?\s*[:=]\s*)[^\r\n]*/gi;
40
+ /** A JSON member whose key names a credential: `"token":"x"`, `"apiKey":"x"`, `"privateKey":"x"`. */
41
+ const JSON_SECRET = /("[\w.-]*(?:token|password|passwd|secret|api_?key|private_?key|authorization|cookie|credential)[\w.-]*"\s*:\s*)"(?:[^"\\]|\\.)*"/gi;
42
+ /** Credentials that live in a URL path: Discord and Slack webhooks, a Telegram bot token. */
43
+ const DISCORD_WEBHOOK = /(\/api\/(?:v\d+\/)?webhooks\/)[^\s/?#"']+(?:\/[^\s/?#"']+)?/gi;
44
+ const SLACK_WEBHOOK = /(hooks\.slack\.com\/(?:services|workflows|triggers)\/)[^\s?#"']+/gi;
45
+ const TELEGRAM_BOT = /(\/bot)\d+:[A-Za-z0-9_-]+(?=\/|\s|$|["'?])/gi;
46
+ exports.REDACTED = '[redacted]';
47
+ function scrubSecrets(message) {
48
+ return message
49
+ .replace(USER_INFO, `$1${exports.REDACTED}@`)
50
+ .replace(DISCORD_WEBHOOK, `$1${exports.REDACTED}`)
51
+ .replace(SLACK_WEBHOOK, `$1${exports.REDACTED}`)
52
+ .replace(TELEGRAM_BOT, `$1${exports.REDACTED}`)
53
+ .replace(COOKIE_HEADER, `$1$2${exports.REDACTED}`)
54
+ .replace(JSON_SECRET, `$1"${exports.REDACTED}"`)
55
+ .replace(PARAM_VALUE, `$1=${exports.REDACTED}`)
56
+ .replace(BEARER, `$1 ${exports.REDACTED}`)
57
+ .replace(HEADER_VALUE, `$1$2${exports.REDACTED}`);
58
+ }
@@ -1,8 +1,3 @@
1
- /**
2
- * What the core logs through. The host supplies one `LoggerPort`; every class that
3
- * logs holds a `ScopedLogger` that stamps its own context on each line and hands it
4
- * to that port. Nothing in the core reaches for a logging library or a global.
5
- */
6
1
  export interface LoggerPort {
7
2
  log(message: string, context?: string): void;
8
3
  warn(message: string, context?: string): void;
@@ -2,6 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ScopedLogger = void 0;
4
4
  exports.bindLogger = bindLogger;
5
+ /**
6
+ * What the core logs through. The host supplies one `LoggerPort`; every class that
7
+ * logs holds a `ScopedLogger` that stamps its own context on each line and hands it
8
+ * to that port. Nothing in the core reaches for a logging library or a global.
9
+ */
10
+ const log_scrub_1 = require("./log-scrub");
5
11
  let bound;
6
12
  /**
7
13
  * Point every `ScopedLogger` at the host's logger (`createScraperModule` does it).
@@ -12,13 +18,17 @@ let bound;
12
18
  function bindLogger(port) {
13
19
  bound = port;
14
20
  }
15
- function text(message) {
21
+ function raw(message) {
16
22
  if (typeof message === 'string')
17
23
  return message;
18
24
  if (message instanceof Error)
19
25
  return message.stack ?? message.message;
20
26
  return String(message);
21
27
  }
28
+ /** Every line the core logs passes here: credentials in a URL or header never reach the host's logger. */
29
+ function text(message) {
30
+ return (0, log_scrub_1.scrubSecrets)(raw(message));
31
+ }
22
32
  class ScopedLogger {
23
33
  constructor(context) {
24
34
  this.context = context;
@@ -36,7 +46,7 @@ class ScopedLogger {
36
46
  bound?.verbose(text(message), this.context);
37
47
  }
38
48
  error(message, trace) {
39
- bound?.error(text(message), typeof trace === 'string' ? trace : undefined, this.context);
49
+ bound?.error(text(message), typeof trace === 'string' ? (0, log_scrub_1.scrubSecrets)(trace) : undefined, this.context);
40
50
  }
41
51
  }
42
52
  exports.ScopedLogger = ScopedLogger;
@@ -2,6 +2,8 @@ import { AppSettings } from '../types';
2
2
  import { SecretStore } from '../ports/secret-store';
3
3
  import { SettingsSeed } from '../ports/settings-seed';
4
4
  import { StateStore } from '../ports/state-store';
5
+ /** The core's own defaults, before a host's seed. Exported so a host can tell stored defaults from operator edits. */
6
+ export declare const DEFAULT_SETTINGS: AppSettings;
5
7
  export declare class SettingsRepository {
6
8
  private readonly secrets;
7
9
  private readonly repo;
@@ -12,12 +12,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.SettingsRepository = void 0;
15
+ exports.SettingsRepository = exports.DEFAULT_SETTINGS = void 0;
16
16
  const common_1 = require("@nestjs/common");
17
17
  const tokens_1 = require("../ports/tokens");
18
18
  const secret_store_1 = require("../ports/secret-store");
19
19
  const state_store_1 = require("../ports/state-store");
20
- const DEFAULT_SETTINGS = {
20
+ /** The core's own defaults, before a host's seed. Exported so a host can tell stored defaults from operator edits. */
21
+ exports.DEFAULT_SETTINGS = {
21
22
  sonarrUrl: '',
22
23
  sonarrApiKey: '',
23
24
  radarrUrl: '',
@@ -53,7 +54,7 @@ const DEFAULT_SETTINGS = {
53
54
  let SettingsRepository = class SettingsRepository {
54
55
  constructor(state, secrets, seed) {
55
56
  this.secrets = secrets;
56
- this.defaults = { ...DEFAULT_SETTINGS, ...seed };
57
+ this.defaults = { ...exports.DEFAULT_SETTINGS, ...seed };
57
58
  this.repo = new state_store_1.StoredCollection(state, 'settings', this.defaults);
58
59
  }
59
60
  get() {