nosnitch 0.0.0-stage → 0.2.0

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.
package/db/schema.json ADDED
@@ -0,0 +1,125 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://github.com/Umerrrdo/nosnitch/blob/main/db/schema.json",
4
+ "title": "nosnitch app entry",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": ["name", "slug", "images", "telemetry_default", "disable", "sources", "verified_on", "verified"],
8
+ "properties": {
9
+ "name": { "type": "string", "minLength": 1 },
10
+ "slug": { "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" },
11
+ "images": {
12
+ "description": "Image names without tag or digest. Docker Hub images are written without a registry (n8nio/n8n). A * matches any run of characters.",
13
+ "type": "array",
14
+ "minItems": 1,
15
+ "uniqueItems": true,
16
+ "items": { "type": "string", "pattern": "^[a-z0-9*][a-z0-9._*/:-]*$" }
17
+ },
18
+ "telemetry_default": { "enum": ["on", "off", "partial", "unknown"] },
19
+ "destinations": {
20
+ "description": "Hostnames the telemetry is sent to. Only documented ones.",
21
+ "type": "array",
22
+ "uniqueItems": true,
23
+ "items": { "type": "string", "pattern": "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$" }
24
+ },
25
+ "what_is_sent": { "type": "string", "minLength": 1 },
26
+ "still_sent": {
27
+ "description": "What keeps going out even after the documented opt-out is applied.",
28
+ "type": "string",
29
+ "minLength": 1
30
+ },
31
+ "disable": {
32
+ "type": "array",
33
+ "items": {
34
+ "oneOf": [
35
+ { "$ref": "#/definitions/env" },
36
+ { "$ref": "#/definitions/flag" },
37
+ { "$ref": "#/definitions/config_file" },
38
+ { "$ref": "#/definitions/manual" }
39
+ ]
40
+ }
41
+ },
42
+ "fixed_in": {
43
+ "description": "Version where the default became off.",
44
+ "type": "string",
45
+ "pattern": "^v?\\d+(\\.\\d+){0,2}$"
46
+ },
47
+ "sources": {
48
+ "type": "array",
49
+ "minItems": 1,
50
+ "uniqueItems": true,
51
+ "items": { "type": "string", "pattern": "^https://\\S+$" }
52
+ },
53
+ "verified_on": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
54
+ "verified": { "type": "boolean" },
55
+ "notes": { "type": "string", "minLength": 1 }
56
+ },
57
+ "definitions": {
58
+ "envPair": {
59
+ "type": "object",
60
+ "additionalProperties": false,
61
+ "required": ["name", "value"],
62
+ "properties": {
63
+ "name": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
64
+ "value": { "type": "string" },
65
+ "accepted_values": {
66
+ "description": "Other values that also count as disabled.",
67
+ "type": "array",
68
+ "items": { "type": "string" }
69
+ }
70
+ }
71
+ },
72
+ "env": {
73
+ "type": "object",
74
+ "additionalProperties": false,
75
+ "required": ["type", "name", "value"],
76
+ "properties": {
77
+ "type": { "const": "env" },
78
+ "name": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
79
+ "value": { "type": "string" },
80
+ "accepted_values": { "type": "array", "items": { "type": "string" } },
81
+ "alternatives": {
82
+ "description": "Other variables that achieve the same thing.",
83
+ "type": "array",
84
+ "items": { "$ref": "#/definitions/envPair" }
85
+ },
86
+ "optional": {
87
+ "description": "True when this stops other outbound calls (update checks and so on) rather than telemetry itself.",
88
+ "type": "boolean"
89
+ },
90
+ "note": { "type": "string" }
91
+ }
92
+ },
93
+ "flag": {
94
+ "type": "object",
95
+ "additionalProperties": false,
96
+ "required": ["type", "flag"],
97
+ "properties": {
98
+ "type": { "const": "flag" },
99
+ "flag": { "type": "string", "pattern": "^-" },
100
+ "note": { "type": "string" }
101
+ }
102
+ },
103
+ "config_file": {
104
+ "type": "object",
105
+ "additionalProperties": false,
106
+ "required": ["type", "path", "key", "value"],
107
+ "properties": {
108
+ "type": { "const": "config_file" },
109
+ "path": { "type": "string" },
110
+ "key": { "type": "string" },
111
+ "value": { "type": "string" },
112
+ "note": { "type": "string" }
113
+ }
114
+ },
115
+ "manual": {
116
+ "type": "object",
117
+ "additionalProperties": false,
118
+ "required": ["type", "instructions"],
119
+ "properties": {
120
+ "type": { "const": "manual" },
121
+ "instructions": { "type": "string", "minLength": 1 }
122
+ }
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,42 @@
1
+ export const BLOCKLIST_FORMATS = ["hosts", "pihole", "adguard"];
2
+ export function isBlocklistFormat(value) {
3
+ return BLOCKLIST_FORMATS.includes(value);
4
+ }
5
+ /**
6
+ * Destinations of every matched app in the compose file, whether or not the
7
+ * app is already opted out. Only documented destinations are in the database.
8
+ */
9
+ export function collectDestinations(results) {
10
+ const byHost = new Map();
11
+ for (const r of results) {
12
+ for (const host of r.destinations) {
13
+ const apps = byHost.get(host) ?? [];
14
+ if (r.app && !apps.includes(r.app))
15
+ apps.push(r.app);
16
+ byHost.set(host, apps);
17
+ }
18
+ }
19
+ return new Map([...byHost].sort(([a], [b]) => a.localeCompare(b)));
20
+ }
21
+ /**
22
+ * hosts: 0.0.0.0 example.com (/etc/hosts, also accepted by Pi-hole and AdGuard Home)
23
+ * pihole: example.com (plain domain list)
24
+ * adguard: ||example.com^ (adblock-style rule, also accepted by Pi-hole)
25
+ */
26
+ export function renderBlocklist(results, format = "hosts") {
27
+ const comment = format === "adguard" ? "!" : "#";
28
+ const hosts = collectDestinations(results);
29
+ const lines = [`${comment} nosnitch blocklist (${format}): documented telemetry destinations for the apps in your compose file`];
30
+ if (hosts.size === 0)
31
+ lines.push(`${comment} No documented destinations for these apps.`);
32
+ for (const [host, apps] of hosts) {
33
+ lines.push(`${comment} ${apps.join(", ")}`);
34
+ if (format === "hosts")
35
+ lines.push(`0.0.0.0 ${host}`);
36
+ else if (format === "pihole")
37
+ lines.push(host);
38
+ else
39
+ lines.push(`||${host}^`);
40
+ }
41
+ return lines.join("\n");
42
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { BLOCKLIST_FORMATS, isBlocklistFormat, renderBlocklist } from "./blocklist.js";
7
+ import { DEFAULT_COMPOSE_FILES, displayPath, findComposeFile, loadCompose } from "./compose.js";
8
+ import { loadDatabase } from "./db.js";
9
+ import { NosnitchError, UsageError } from "./errors.js";
10
+ import { writeOverride } from "./fix.js";
11
+ import { renderCheck, renderList, renderScan } from "./render.js";
12
+ import { checkImage, exitCodeFor, scanServices } from "./scanner.js";
13
+ const HELP = `nosnitch: which apps in your Docker Compose file send telemetry by default?
14
+
15
+ Usage:
16
+ nosnitch scan [compose-file] [more-files...] table of services, defaults, destinations and fixes
17
+ nosnitch scan [compose-file] --fix write compose.nosnitch.override.yml (your file is never edited)
18
+ nosnitch blocklist [compose-file] telemetry destinations in hosts-file format
19
+ nosnitch check <image> look up one image
20
+ nosnitch list list every app in the database
21
+
22
+ Without a compose file, nosnitch looks in the current folder for
23
+ ${DEFAULT_COMPOSE_FILES.join(", ")}.
24
+
25
+ Options:
26
+ --json machine-readable output (scan, check, list)
27
+ --format blocklist format: hosts (default), pihole (plain domains) or adguard (||domain^)
28
+ --debug show the full stack trace when something fails
29
+ -h, --help
30
+ -v, --version
31
+
32
+ Exit codes:
33
+ 0 nothing known is left on
34
+ 1 scan found telemetry that is on by default and not disabled
35
+ 2 usage or file error
36
+ `;
37
+ const COMMANDS = ["scan", "blocklist", "check", "list"];
38
+ function version() {
39
+ const pkg = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
40
+ return JSON.parse(readFileSync(pkg, "utf8")).version;
41
+ }
42
+ /** Uses the files given, or finds the compose file in the current folder (or in a folder that was passed). */
43
+ function composeFiles(args, command) {
44
+ if (args.length === 0) {
45
+ const found = findComposeFile(process.cwd());
46
+ if (found)
47
+ return [found];
48
+ throw new UsageError(`No compose file given and none found in ${process.cwd()}.`, `Pass one, for example: nosnitch ${command} docker-compose.yml\nnosnitch looks for: ${DEFAULT_COMPOSE_FILES.join(", ")}.`);
49
+ }
50
+ return args.map((arg) => (existsSync(arg) && statSync(arg).isDirectory() ? (findComposeFile(arg) ?? arg) : arg));
51
+ }
52
+ function quote(path) {
53
+ return /\s/.test(path) ? `"${path}"` : path;
54
+ }
55
+ function parse(argv) {
56
+ try {
57
+ return parseArgs({
58
+ args: argv,
59
+ allowPositionals: true,
60
+ options: {
61
+ json: { type: "boolean", default: false },
62
+ fix: { type: "boolean", default: false },
63
+ format: { type: "string", default: "hosts" },
64
+ debug: { type: "boolean", default: false },
65
+ help: { type: "boolean", short: "h", default: false },
66
+ version: { type: "boolean", short: "v", default: false },
67
+ },
68
+ });
69
+ }
70
+ catch (err) {
71
+ const e = err;
72
+ if (e.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION") {
73
+ const option = /'([^']+)'/.exec(e.message)?.[1] ?? "that option";
74
+ throw new UsageError(`Unknown option: ${option}`);
75
+ }
76
+ if (e.code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE") {
77
+ throw new UsageError(`--format needs a value: ${BLOCKLIST_FORMATS.join(", ")}.`, "For example: nosnitch blocklist docker-compose.yml --format pihole");
78
+ }
79
+ throw err;
80
+ }
81
+ }
82
+ async function main(argv) {
83
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
84
+ if (nodeMajor < 20) {
85
+ throw new NosnitchError(`nosnitch needs Node 20 or newer. This is Node ${process.versions.node}.`, "Install a current Node from https://nodejs.org, or use the Docker image (see the README).");
86
+ }
87
+ const { values, positionals } = parse(argv);
88
+ const [command, ...rest] = positionals;
89
+ if (values.version) {
90
+ console.log(version());
91
+ return 0;
92
+ }
93
+ if (values.help || !command) {
94
+ console.log(HELP);
95
+ return values.help ? 0 : 2;
96
+ }
97
+ if (command && !COMMANDS.includes(command)) {
98
+ const looksLikeFile = /\.ya?ml$/i.test(command) || existsSync(command);
99
+ throw new UsageError(`Unknown command: ${command}`, looksLikeFile ? `Did you mean: nosnitch scan ${quote(command)}` : `The commands are: ${COMMANDS.join(", ")}. Run nosnitch --help for details.`);
100
+ }
101
+ const db = loadDatabase();
102
+ switch (command) {
103
+ case "scan": {
104
+ const files = composeFiles(rest, "scan");
105
+ const project = loadCompose(files);
106
+ const results = scanServices(project.services, db.apps);
107
+ const exitCode = exitCodeFor(results);
108
+ const written = values.fix ? writeOverride(results, files[0]) : null;
109
+ if (values.json) {
110
+ const report = { files, database: { apps: db.apps.length }, services: results, warnings: project.warnings, override_file: written, exit_code: exitCode };
111
+ console.log(JSON.stringify(report, null, 2));
112
+ }
113
+ else {
114
+ console.log(renderScan(results, project.warnings));
115
+ if (written) {
116
+ console.log(`\nWrote ${displayPath(written)}`);
117
+ console.log(`Apply it: docker compose -f ${quote(displayPath(files[0]))} -f ${quote(displayPath(written))} up -d`);
118
+ }
119
+ else if (values.fix) {
120
+ const manual = results.some((r) => !r.ok && r.manual.length > 0);
121
+ console.log(`\nNo override file written: ${manual ? "the remaining opt-outs are manual steps, not environment variables." : "no environment fixes are needed."}`);
122
+ }
123
+ }
124
+ return exitCode;
125
+ }
126
+ case "blocklist": {
127
+ const format = values.format ?? "hosts";
128
+ if (!isBlocklistFormat(format)) {
129
+ throw new UsageError(`Unknown blocklist format: ${format}`, `Use one of: ${BLOCKLIST_FORMATS.join(", ")}. For example: nosnitch blocklist docker-compose.yml --format pihole`);
130
+ }
131
+ const project = loadCompose(composeFiles(rest, "blocklist"));
132
+ console.log(renderBlocklist(scanServices(project.services, db.apps), format));
133
+ return 0;
134
+ }
135
+ case "check": {
136
+ const image = rest[0];
137
+ if (!image)
138
+ throw new UsageError("check needs an image name.", "For example: nosnitch check n8nio/n8n");
139
+ if (/\.ya?ml$/i.test(image) && existsSync(image)) {
140
+ throw new UsageError(`${image} is a file, and check takes an image name.`, `To scan a compose file run: nosnitch scan ${quote(image)}`);
141
+ }
142
+ const result = checkImage(image, db.apps);
143
+ console.log(values.json ? JSON.stringify(result, null, 2) : renderCheck(result));
144
+ return 0;
145
+ }
146
+ default: {
147
+ console.log(values.json ? JSON.stringify(db.apps, null, 2) : renderList(db.apps));
148
+ return 0;
149
+ }
150
+ }
151
+ }
152
+ const debug = process.argv.includes("--debug");
153
+ main(process.argv.slice(2)).then((code) => {
154
+ process.exitCode = code;
155
+ }, (err) => {
156
+ process.exitCode = 2;
157
+ if (err instanceof NosnitchError) {
158
+ console.error(`nosnitch: ${err.message}`);
159
+ if (err.hint)
160
+ console.error(err.hint);
161
+ }
162
+ else {
163
+ // Not an error we planned for. Still no stack trace unless asked.
164
+ const message = err instanceof Error ? err.message : String(err);
165
+ console.error(`nosnitch: something went wrong: ${message}`);
166
+ console.error("Run it again with --debug for details, and please report it: https://github.com/Umerrrdo/nosnitch/issues");
167
+ }
168
+ if (debug && err instanceof Error && err.stack)
169
+ console.error(`\n${err.stack}`);
170
+ });
@@ -0,0 +1,332 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
3
+ import { parse } from "yaml";
4
+ import { NosnitchError } from "./errors.js";
5
+ /** The file names Docker Compose looks for, in its order of preference. */
6
+ export const DEFAULT_COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
7
+ /** Finds the compose file in a directory the way `docker compose` does. */
8
+ export function findComposeFile(dir) {
9
+ return DEFAULT_COMPOSE_FILES.map((name) => resolve(dir, name)).find((path) => existsSync(path) && statSync(path).isFile());
10
+ }
11
+ /** Parses KEY=VALUE lines as used by env_file and .env. */
12
+ export function parseEnvFile(text) {
13
+ const out = new Map();
14
+ for (const rawLine of text.replace(/^/, "").split(/\r?\n/)) {
15
+ const line = rawLine.trim().replace(/^export\s+/, "");
16
+ if (line === "" || line.startsWith("#"))
17
+ continue;
18
+ const eq = line.indexOf("=");
19
+ if (eq === -1) {
20
+ out.set(line, undefined);
21
+ continue;
22
+ }
23
+ const key = line.slice(0, eq).trim();
24
+ let value = line.slice(eq + 1).trim();
25
+ const quoted = /^(["'])(.*)\1$/.exec(value);
26
+ if (quoted)
27
+ value = quoted[2] ?? "";
28
+ else
29
+ value = value.replace(/\s+#.*$/, "");
30
+ if (key !== "")
31
+ out.set(key, value);
32
+ }
33
+ return out;
34
+ }
35
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
36
+ /**
37
+ * Resolves $VAR, ${VAR}, ${VAR:-default}, ${VAR-default}, ${VAR:+alt}, ${VAR+alt}
38
+ * and ${VAR:?error} the way Compose does, including nested defaults such as
39
+ * ${A:-${B:-1}}. "$$" is a literal dollar sign.
40
+ */
41
+ export function interpolate(value, vars, options = {}) {
42
+ let out = "";
43
+ let i = 0;
44
+ while (i < value.length) {
45
+ const ch = value[i];
46
+ if (ch !== "$") {
47
+ out += ch;
48
+ i++;
49
+ continue;
50
+ }
51
+ if (value[i + 1] === "$") {
52
+ out += "$";
53
+ i += 2;
54
+ continue;
55
+ }
56
+ if (value[i + 1] === "{") {
57
+ // Find the matching brace, allowing nested ${...} in the default.
58
+ let depth = 1;
59
+ let j = i + 2;
60
+ while (j < value.length && depth > 0) {
61
+ if (value[j] === "$" && value[j + 1] === "{") {
62
+ depth++;
63
+ j++;
64
+ }
65
+ else if (value[j] === "}")
66
+ depth--;
67
+ j++;
68
+ }
69
+ const body = value.slice(i + 2, j - 1);
70
+ const name = depth === 0 ? NAME.exec(body)?.[0] : undefined;
71
+ if (!name) {
72
+ out += ch;
73
+ i++;
74
+ continue;
75
+ }
76
+ const rest = body.slice(name.length);
77
+ const op = /^(:?[-?+])/.exec(rest)?.[1];
78
+ const arg = op ? rest.slice(op.length) : "";
79
+ const current = vars[name];
80
+ const isSet = op?.startsWith(":") ? Boolean(current) : current !== undefined;
81
+ const literal = value.slice(i, j);
82
+ if (op === undefined)
83
+ out += current ?? missing(name, literal, options);
84
+ else if (op.endsWith("-"))
85
+ out += isSet ? current : interpolate(arg, vars, options);
86
+ else if (op.endsWith("+"))
87
+ out += isSet ? interpolate(arg, vars, options) : "";
88
+ else
89
+ out += isSet ? current : missing(name, literal, options);
90
+ i = j;
91
+ continue;
92
+ }
93
+ const bare = NAME.exec(value.slice(i + 1))?.[0];
94
+ if (!bare) {
95
+ out += ch;
96
+ i++;
97
+ continue;
98
+ }
99
+ out += vars[bare] ?? missing(bare, `$${bare}`, options);
100
+ i += 1 + bare.length;
101
+ }
102
+ return out;
103
+ }
104
+ function missing(name, literal, options) {
105
+ options.missing?.add(name);
106
+ return options.keepMissing ? literal : "";
107
+ }
108
+ function scalarToString(value) {
109
+ return value === null || value === undefined ? "" : String(value);
110
+ }
111
+ /** Reads the environment key in list form (- KEY=value) or map form (KEY: value). */
112
+ export function parseEnvironment(environment, vars = {}) {
113
+ const out = new Map();
114
+ if (Array.isArray(environment)) {
115
+ for (const item of environment) {
116
+ const entry = scalarToString(item);
117
+ const eq = entry.indexOf("=");
118
+ if (eq === -1)
119
+ out.set(entry.trim(), undefined);
120
+ else
121
+ out.set(entry.slice(0, eq).trim(), interpolate(entry.slice(eq + 1), vars));
122
+ }
123
+ }
124
+ else if (typeof environment === "object" && environment !== null) {
125
+ for (const [key, value] of Object.entries(environment)) {
126
+ out.set(key, value === null ? undefined : interpolate(scalarToString(value), vars));
127
+ }
128
+ }
129
+ return out;
130
+ }
131
+ function envFileRefs(envFile, dir, vars) {
132
+ const list = Array.isArray(envFile) ? envFile : envFile === undefined || envFile === null ? [] : [envFile];
133
+ const refs = [];
134
+ for (const item of list) {
135
+ const isObject = typeof item === "object" && item !== null;
136
+ const path = isObject ? item.path : item;
137
+ if (typeof path !== "string")
138
+ continue;
139
+ const required = isObject ? item.required !== false : true;
140
+ refs.push({ path: resolvePath(dir, interpolate(path, vars)), required });
141
+ }
142
+ return refs;
143
+ }
144
+ /** Accepts both slash styles, so a Windows path in a compose file also works. */
145
+ function resolvePath(dir, path) {
146
+ return resolve(dir, process.platform === "win32" ? path : path.replace(/\\/g, "/"));
147
+ }
148
+ function commandToString(...parts) {
149
+ return parts
150
+ .flatMap((part) => (Array.isArray(part) ? part : part === undefined || part === null ? [] : [part]))
151
+ .map(scalarToString)
152
+ .join(" ");
153
+ }
154
+ /** Shows a path the way the user would type it. */
155
+ export function displayPath(path) {
156
+ const rel = relative(process.cwd(), path);
157
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel : path;
158
+ }
159
+ /** Reads and parses one compose file, turning every failure into a message the user can act on. */
160
+ function readComposeFile(file) {
161
+ const shown = displayPath(file);
162
+ if (!existsSync(file)) {
163
+ throw new NosnitchError(`File not found: ${shown}`, "Check the path. Run nosnitch from the folder that holds your compose file, or pass the full path.");
164
+ }
165
+ if (statSync(file).isDirectory()) {
166
+ throw new NosnitchError(`${shown} is a folder and has no compose file in it.`, `Pass the compose file itself. nosnitch looks for: ${DEFAULT_COMPOSE_FILES.join(", ")}.`);
167
+ }
168
+ let text;
169
+ try {
170
+ text = readFileSync(file, "utf8").replace(/^/, "");
171
+ }
172
+ catch (err) {
173
+ throw new NosnitchError(`Could not read ${shown}: ${err.message}`, "Check that the file exists and that you have permission to read it.");
174
+ }
175
+ if (text.trim() === "") {
176
+ throw new NosnitchError(`${shown} is empty.`, "A compose file needs a services: section. Check that you passed the right file.");
177
+ }
178
+ let doc;
179
+ try {
180
+ // Large official compose files (Sentry, for one) reuse anchors hundreds of times.
181
+ doc = parse(text, { merge: true, maxAliasCount: 100000 });
182
+ }
183
+ catch (err) {
184
+ throw new NosnitchError(`${shown} is not valid YAML.\n${err.message.trim()}`, `Fix the line shown above. "docker compose -f ${shown} config" reports the same problem.`);
185
+ }
186
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
187
+ throw new NosnitchError(`${shown} does not look like a Compose file.`, "A compose file is a YAML document with a top-level services: section.");
188
+ }
189
+ return doc;
190
+ }
191
+ function asServices(doc) {
192
+ const services = doc.services;
193
+ return typeof services === "object" && services !== null && !Array.isArray(services) ? services : {};
194
+ }
195
+ /** Works out what one service definition contributes, following extends first. */
196
+ function contribution(name, services, file, ctx, chain = []) {
197
+ const dir = dirname(file);
198
+ const raw = services[name];
199
+ const def = (typeof raw === "object" && raw !== null ? raw : {});
200
+ let out = { envFiles: [], environment: new Map(), command: "" };
201
+ if (def.extends !== undefined && def.extends !== null) {
202
+ const ext = typeof def.extends === "string" ? { service: def.extends } : def.extends;
203
+ const baseName = typeof ext.service === "string" ? ext.service : undefined;
204
+ const baseFile = typeof ext.file === "string" ? resolvePath(dir, interpolate(ext.file, ctx.vars)) : file;
205
+ const key = `${baseFile}#${baseName}`;
206
+ if (!baseName) {
207
+ ctx.warnings.add(`service "${name}": extends has no service name, so it was ignored`);
208
+ }
209
+ else if (chain.includes(key)) {
210
+ ctx.warnings.add(`service "${name}": extends forms a loop, so it was ignored`);
211
+ }
212
+ else if (!existsSync(baseFile)) {
213
+ ctx.warnings.add(`${displayPath(baseFile)} not found, so services that extend it are missing whatever it sets (image, environment)`);
214
+ }
215
+ else {
216
+ const baseServices = baseFile === file ? services : asServices(readComposeFile(baseFile));
217
+ if (baseName in baseServices)
218
+ out = contribution(baseName, baseServices, baseFile, ctx, [...chain, key]);
219
+ else
220
+ ctx.warnings.add(`service "${name}": extends "${baseName}", which is not in ${displayPath(baseFile)}`);
221
+ }
222
+ }
223
+ if (typeof def.image === "string") {
224
+ const unset = new Set();
225
+ out.image = interpolate(def.image, ctx.vars, { missing: unset, keepMissing: true }).trim();
226
+ if (unset.size > 0)
227
+ out.unsetImageVars = [...unset];
228
+ else
229
+ delete out.unsetImageVars;
230
+ }
231
+ out.envFiles = [...out.envFiles, ...envFileRefs(def.env_file, dir, ctx.vars)];
232
+ out.environment = new Map([...out.environment, ...parseEnvironment(def.environment, ctx.vars)]);
233
+ const command = commandToString(def.entrypoint, def.command);
234
+ if (command !== "")
235
+ out.command = interpolate(command, ctx.vars);
236
+ return out;
237
+ }
238
+ function loadFile(file, ctx) {
239
+ const doc = readComposeFile(file);
240
+ const dir = dirname(file);
241
+ const includes = Array.isArray(doc.include) ? doc.include : [];
242
+ for (const item of includes) {
243
+ const paths = typeof item === "string" ? [item] : [item?.path].flat();
244
+ for (const p of paths) {
245
+ if (typeof p !== "string")
246
+ continue;
247
+ const target = resolvePath(dir, interpolate(p, ctx.vars));
248
+ if (ctx.included.has(target))
249
+ continue;
250
+ ctx.included.add(target);
251
+ if (!existsSync(target)) {
252
+ ctx.warnings.add(`${displayPath(file)} includes ${displayPath(target)}, which was not found, so its services were not scanned`);
253
+ continue;
254
+ }
255
+ loadFile(target, ctx);
256
+ }
257
+ }
258
+ const services = asServices(doc);
259
+ for (const name of Object.keys(services)) {
260
+ const next = contribution(name, services, file, ctx);
261
+ const current = ctx.merged.get(name);
262
+ if (!current) {
263
+ ctx.merged.set(name, next);
264
+ continue;
265
+ }
266
+ // A later file overrides an earlier one, like `docker compose -f a.yml -f b.yml`.
267
+ if (next.image !== undefined) {
268
+ current.image = next.image;
269
+ if (next.unsetImageVars)
270
+ current.unsetImageVars = next.unsetImageVars;
271
+ else
272
+ delete current.unsetImageVars;
273
+ }
274
+ current.envFiles.push(...next.envFiles);
275
+ for (const [k, v] of next.environment)
276
+ current.environment.set(k, v);
277
+ if (next.command !== "")
278
+ current.command = next.command;
279
+ }
280
+ }
281
+ /**
282
+ * Loads one or more compose files. Later files override earlier ones, like
283
+ * `docker compose -f a.yml -f b.yml`. include and extends are followed.
284
+ * Nothing is written and nothing is fetched.
285
+ */
286
+ export function loadCompose(files) {
287
+ const paths = files.map((f) => resolve(f));
288
+ const firstDir = dirname(paths[0] ?? resolve("."));
289
+ const dotEnvPath = resolve(firstDir, ".env");
290
+ const dotEnv = existsSync(dotEnvPath) && statSync(dotEnvPath).isFile() ? parseEnvFile(readFileSync(dotEnvPath, "utf8")) : new Map();
291
+ const ctx = {
292
+ vars: { ...Object.fromEntries(dotEnv), ...process.env },
293
+ warnings: new Set(),
294
+ merged: new Map(),
295
+ included: new Set(paths),
296
+ };
297
+ for (const path of paths)
298
+ loadFile(path, ctx);
299
+ if (ctx.merged.size === 0) {
300
+ const shown = paths.map(displayPath).join(", ");
301
+ throw new NosnitchError(`No services found in ${shown}, so there is nothing to scan.`, "Is this a Docker Compose file? It needs a top-level services: section with at least one service.");
302
+ }
303
+ const missingEnvFiles = new Map();
304
+ const services = [];
305
+ for (const [name, svc] of ctx.merged) {
306
+ const env = new Map();
307
+ for (const ref of svc.envFiles) {
308
+ if (!existsSync(ref.path) || !statSync(ref.path).isFile()) {
309
+ if (ref.required)
310
+ missingEnvFiles.set(ref.path, [...(missingEnvFiles.get(ref.path) ?? []), name]);
311
+ continue;
312
+ }
313
+ for (const [k, v] of parseEnvFile(readFileSync(ref.path, "utf8")))
314
+ env.set(k, v === undefined ? undefined : interpolate(v, ctx.vars));
315
+ }
316
+ // environment wins over env_file, as in Compose.
317
+ for (const [k, v] of svc.environment)
318
+ env.set(k, v);
319
+ services.push({
320
+ name,
321
+ ...(svc.image ? { image: svc.image } : {}),
322
+ ...(svc.unsetImageVars ? { unsetImageVars: svc.unsetImageVars } : {}),
323
+ env,
324
+ command: svc.command,
325
+ });
326
+ }
327
+ const warnings = [...ctx.warnings];
328
+ for (const [path, users] of missingEnvFiles) {
329
+ warnings.push(`env_file ${displayPath(path)} not found (used by ${users.join(", ")}). Variables set in it could not be checked.`);
330
+ }
331
+ return { services, warnings };
332
+ }