@ubercode/channelvault 0.3.0-rc.4 → 0.3.0-rc.6
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/CHANGELOG.md +37 -0
- package/README.md +9 -6
- package/dist/cli.js +536 -179
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
5
|
-
import { cp, lstat as lstat4, mkdir as
|
|
6
|
-
import { existsSync as
|
|
5
|
+
import { cp, lstat as lstat4, mkdir as mkdir7, mkdtemp, readdir as readdir6, readFile as readFile6, rm as rm4, writeFile as writeFile6 } from "fs/promises";
|
|
6
|
+
import { existsSync as existsSync9, statSync } from "fs";
|
|
7
7
|
import { tmpdir } from "os";
|
|
8
8
|
import { createRequire } from "module";
|
|
9
|
-
import * as
|
|
9
|
+
import * as path10 from "path";
|
|
10
10
|
import { createInterface } from "readline/promises";
|
|
11
11
|
import { Writable } from "stream";
|
|
12
|
+
import { isDeepStrictEqual } from "util";
|
|
12
13
|
import { Command, CommanderError } from "commander";
|
|
13
14
|
|
|
14
15
|
// src/explode/index.ts
|
|
@@ -958,6 +959,29 @@ function hasPlaceholder(value) {
|
|
|
958
959
|
PLACEHOLDER.lastIndex = 0;
|
|
959
960
|
return PLACEHOLDER.test(value);
|
|
960
961
|
}
|
|
962
|
+
function placeholderNames(config) {
|
|
963
|
+
const names = /* @__PURE__ */ new Set();
|
|
964
|
+
mapLeaves(config, (value) => {
|
|
965
|
+
for (const m of value.matchAll(PLACEHOLDER)) names.add(m[1]);
|
|
966
|
+
return value;
|
|
967
|
+
});
|
|
968
|
+
return names;
|
|
969
|
+
}
|
|
970
|
+
function placeholderUse(tree, server) {
|
|
971
|
+
const onServer = /* @__PURE__ */ new Set();
|
|
972
|
+
mapLeaves(server, (value, leaf) => {
|
|
973
|
+
onServer.add(leaf.location);
|
|
974
|
+
return value;
|
|
975
|
+
});
|
|
976
|
+
const compared = /* @__PURE__ */ new Set();
|
|
977
|
+
const treeOnly = /* @__PURE__ */ new Set();
|
|
978
|
+
mapLeaves(tree, (value, leaf) => {
|
|
979
|
+
for (const m of value.matchAll(PLACEHOLDER)) (onServer.has(leaf.location) ? compared : treeOnly).add(m[1]);
|
|
980
|
+
return value;
|
|
981
|
+
});
|
|
982
|
+
for (const name of compared) treeOnly.delete(name);
|
|
983
|
+
return { compared, treeOnly };
|
|
984
|
+
}
|
|
961
985
|
function fill(value, env, missing) {
|
|
962
986
|
return value.replace(PLACEHOLDER, (whole, name) => {
|
|
963
987
|
const v = env[name];
|
|
@@ -998,17 +1022,22 @@ function elementSegment(el, index) {
|
|
|
998
1022
|
return `[${index}]`;
|
|
999
1023
|
}
|
|
1000
1024
|
function configMapKeyOf(entry) {
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
return
|
|
1025
|
+
const raw = entry["string"];
|
|
1026
|
+
const key = Array.isArray(raw) ? raw[0] : raw;
|
|
1027
|
+
return typeof key === "string" || typeof key === "number" || typeof key === "boolean" ? String(key) : void 0;
|
|
1004
1028
|
}
|
|
1005
1029
|
function mapLeaves(config, visit) {
|
|
1006
|
-
const walk = (node, key,
|
|
1030
|
+
const walk = (node, key, path11, labels, section, cmKey) => {
|
|
1007
1031
|
if (typeof node === "string") {
|
|
1008
|
-
return visit(node, { location:
|
|
1032
|
+
return visit(node, { location: path11.join("/"), key, labels, section, configMapKey: cmKey });
|
|
1033
|
+
}
|
|
1034
|
+
if ((typeof node === "number" || typeof node === "boolean") && cmKey !== void 0 && key === "value") {
|
|
1035
|
+
const text = String(node);
|
|
1036
|
+
const out = visit(text, { location: path11.join("/"), key, labels, section, configMapKey: cmKey });
|
|
1037
|
+
return out === text ? node : out;
|
|
1009
1038
|
}
|
|
1010
1039
|
if (Array.isArray(node)) {
|
|
1011
|
-
return node.map((el, i) => walk(el, key, [...
|
|
1040
|
+
return node.map((el, i) => walk(el, key, [...path11.slice(0, -1), `${path11[path11.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
|
|
1012
1041
|
}
|
|
1013
1042
|
if (node && typeof node === "object") {
|
|
1014
1043
|
const name = node["name"];
|
|
@@ -1016,7 +1045,7 @@ function mapLeaves(config, visit) {
|
|
|
1016
1045
|
const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
|
|
1017
1046
|
const out = {};
|
|
1018
1047
|
for (const [k, v] of Object.entries(node)) {
|
|
1019
|
-
out[k] = walk(v, k, [...
|
|
1048
|
+
out[k] = walk(v, k, [...path11, k], inner, section || k, mapKey);
|
|
1020
1049
|
}
|
|
1021
1050
|
return out;
|
|
1022
1051
|
}
|
|
@@ -1643,6 +1672,10 @@ var MirthClientImpl = class {
|
|
|
1643
1672
|
async putCodeTemplateLibraries(libraries) {
|
|
1644
1673
|
await this.sendJson("PUT", "/codeTemplateLibraries", { list: { codeTemplateLibrary: libraries } }, { override: true });
|
|
1645
1674
|
}
|
|
1675
|
+
/** PUT /server/configurationMap: replaces the whole map. */
|
|
1676
|
+
async putConfigurationMap(map) {
|
|
1677
|
+
await this.sendJson("PUT", "/server/configurationMap", { map });
|
|
1678
|
+
}
|
|
1646
1679
|
async putGlobalScripts(globalScripts) {
|
|
1647
1680
|
await this.sendJson("PUT", "/server/globalScripts", { map: globalScripts });
|
|
1648
1681
|
}
|
|
@@ -1657,15 +1690,15 @@ var MirthClientImpl = class {
|
|
|
1657
1690
|
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1658
1691
|
}
|
|
1659
1692
|
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1660
|
-
async sendJson(method,
|
|
1661
|
-
const response = await this.request(method,
|
|
1693
|
+
async sendJson(method, path11, body, query) {
|
|
1694
|
+
const response = await this.request(method, path11, {
|
|
1662
1695
|
query,
|
|
1663
1696
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1664
1697
|
body: JSON.stringify(body)
|
|
1665
1698
|
});
|
|
1666
1699
|
const text = await response.text();
|
|
1667
1700
|
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1668
|
-
throw new Error(`${method} ${
|
|
1701
|
+
throw new Error(`${method} ${path11}: the server refused the update`);
|
|
1669
1702
|
}
|
|
1670
1703
|
}
|
|
1671
1704
|
// --- internal transport ---------------------------------------------------
|
|
@@ -1674,11 +1707,11 @@ var MirthClientImpl = class {
|
|
|
1674
1707
|
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1675
1708
|
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1676
1709
|
*/
|
|
1677
|
-
async request(method,
|
|
1710
|
+
async request(method, path11, options = {}, isRetry = false) {
|
|
1678
1711
|
if (!this.authenticated) {
|
|
1679
1712
|
await this.login();
|
|
1680
1713
|
}
|
|
1681
|
-
const url = this.buildUrl(
|
|
1714
|
+
const url = this.buildUrl(path11, options.query);
|
|
1682
1715
|
const headers = {
|
|
1683
1716
|
"X-Requested-With": "XMLHttpRequest",
|
|
1684
1717
|
...options.headers
|
|
@@ -1692,7 +1725,7 @@ var MirthClientImpl = class {
|
|
|
1692
1725
|
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1693
1726
|
this.authenticated = false;
|
|
1694
1727
|
await this.login();
|
|
1695
|
-
return this.request(method,
|
|
1728
|
+
return this.request(method, path11, options, true);
|
|
1696
1729
|
}
|
|
1697
1730
|
if (!response.ok) {
|
|
1698
1731
|
throw await this.toApiError(response);
|
|
@@ -1723,8 +1756,8 @@ var MirthClientImpl = class {
|
|
|
1723
1756
|
return response;
|
|
1724
1757
|
}
|
|
1725
1758
|
/** Build an absolute URL with an optional query string. */
|
|
1726
|
-
buildUrl(
|
|
1727
|
-
const url = `${this.baseUrl}${
|
|
1759
|
+
buildUrl(path11, query) {
|
|
1760
|
+
const url = `${this.baseUrl}${path11}`;
|
|
1728
1761
|
if (!query || Object.keys(query).length === 0) {
|
|
1729
1762
|
return url;
|
|
1730
1763
|
}
|
|
@@ -2007,7 +2040,8 @@ async function updateEnvFile(file, updates) {
|
|
|
2007
2040
|
const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
|
|
2008
2041
|
if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
|
|
2009
2042
|
if (!written.has(m[1])) {
|
|
2010
|
-
|
|
2043
|
+
const value = updates[m[1]];
|
|
2044
|
+
if (value !== null) out.push(`${m[1]}=${formatValue(value)}`);
|
|
2011
2045
|
written.add(m[1]);
|
|
2012
2046
|
}
|
|
2013
2047
|
if (opens) [inQuote, dropping] = [opens, true];
|
|
@@ -2017,12 +2051,13 @@ async function updateEnvFile(file, updates) {
|
|
|
2017
2051
|
if (opens) inQuote = opens;
|
|
2018
2052
|
}
|
|
2019
2053
|
for (const name of names) {
|
|
2020
|
-
|
|
2054
|
+
const value = updates[name];
|
|
2055
|
+
if (!written.has(name) && value !== null) out.push(`${name}=${formatValue(value)}`);
|
|
2021
2056
|
}
|
|
2022
|
-
const text = `${out.join("\n")}
|
|
2057
|
+
const text = out.length === 0 ? "" : `${out.join("\n")}
|
|
2023
2058
|
`;
|
|
2024
2059
|
const readBack = parseEnv(text);
|
|
2025
|
-
const wrong = names.filter((n) => readBack[n] !== updates[n]);
|
|
2060
|
+
const wrong = names.filter((n) => readBack[n] !== (updates[n] ?? void 0));
|
|
2026
2061
|
if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
|
|
2027
2062
|
const target = existsSync4(file) ? await realpath3(file) : file;
|
|
2028
2063
|
const temp = `${target}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
|
|
@@ -2195,12 +2230,15 @@ async function saveProfiles(profiles) {
|
|
|
2195
2230
|
`);
|
|
2196
2231
|
}
|
|
2197
2232
|
async function readCredentials() {
|
|
2198
|
-
return readEnvFile(credentialsFile());
|
|
2233
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), await readEnvFile(credentialsFile()));
|
|
2199
2234
|
}
|
|
2200
2235
|
async function setCredential(name, password) {
|
|
2201
2236
|
await ensureConfigDir();
|
|
2202
2237
|
await updateEnvFile(credentialsFile(), { [name]: password });
|
|
2203
2238
|
}
|
|
2239
|
+
async function removeCredential(name) {
|
|
2240
|
+
if (existsSync5(credentialsFile())) await updateEnvFile(credentialsFile(), { [name]: null });
|
|
2241
|
+
}
|
|
2204
2242
|
|
|
2205
2243
|
// src/connection.ts
|
|
2206
2244
|
var SOURCE_LABEL = {
|
|
@@ -2358,20 +2396,139 @@ function connectionJson(conn, serverId, envFile) {
|
|
|
2358
2396
|
}
|
|
2359
2397
|
|
|
2360
2398
|
// src/push/index.ts
|
|
2399
|
+
import { createHash as createHash3 } from "crypto";
|
|
2400
|
+
|
|
2401
|
+
// src/push/configMap.ts
|
|
2361
2402
|
import { createHash as createHash2 } from "crypto";
|
|
2362
2403
|
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2404
|
+
function configMapOf(c) {
|
|
2405
|
+
return isObj(c["configurationMap"]) ? list(c["configurationMap"]["entry"]) : [];
|
|
2406
|
+
}
|
|
2407
|
+
function byKey(entries) {
|
|
2408
|
+
const out = /* @__PURE__ */ new Map();
|
|
2409
|
+
for (const e of entries) {
|
|
2410
|
+
const k = configMapKeyOf(e);
|
|
2411
|
+
if (k !== void 0) out.set(k, e);
|
|
2412
|
+
}
|
|
2413
|
+
return out;
|
|
2414
|
+
}
|
|
2415
|
+
function contentOf(entry) {
|
|
2416
|
+
const p = entry[CONFIG_PROPERTY];
|
|
2417
|
+
const part = (name) => {
|
|
2418
|
+
const v = isObj(p) ? p[name] : void 0;
|
|
2419
|
+
return v === null || v === void 0 ? "" : normalizeEol(typeof v === "string" ? v : JSON.stringify(v));
|
|
2420
|
+
};
|
|
2421
|
+
return JSON.stringify([part("value"), part("comment")]);
|
|
2422
|
+
}
|
|
2423
|
+
function sameEntry(a, b) {
|
|
2424
|
+
if (!a || !b) return a === b;
|
|
2425
|
+
return contentOf(a) === contentOf(b);
|
|
2426
|
+
}
|
|
2427
|
+
function sameConfigMap(a, b) {
|
|
2428
|
+
return otherDifferingKeys(a, b, []).length === 0;
|
|
2429
|
+
}
|
|
2430
|
+
function withSortedConfigMap(c) {
|
|
2431
|
+
const holder = c["configurationMap"];
|
|
2432
|
+
if (!isObj(holder) || holder["entry"] === void 0) return c;
|
|
2433
|
+
const entry = [...configMapOf(c)].sort((x, y) => (configMapKeyOf(x) ?? "").localeCompare(configMapKeyOf(y) ?? "", "en"));
|
|
2434
|
+
return { ...c, configurationMap: { ...holder, entry } };
|
|
2435
|
+
}
|
|
2436
|
+
function digest(name, entry) {
|
|
2437
|
+
return createHash2("sha256").update(`${name}\0${contentOf(entry)}`).digest("hex");
|
|
2438
|
+
}
|
|
2439
|
+
function configMapBaseline(c) {
|
|
2440
|
+
return Object.fromEntries([...byKey(configMapOf(c))].map(([k, e]) => [k, digest(k, e)]));
|
|
2441
|
+
}
|
|
2442
|
+
function baselineAfterPush(baseline, server, names) {
|
|
2443
|
+
if (!baseline) return void 0;
|
|
2444
|
+
const now = byKey(configMapOf(server));
|
|
2445
|
+
const next = { ...baseline };
|
|
2446
|
+
for (const name of names) {
|
|
2447
|
+
const e = now.get(name);
|
|
2448
|
+
if (e) next[name] = digest(name, e);
|
|
2449
|
+
else delete next[name];
|
|
2450
|
+
}
|
|
2451
|
+
return next;
|
|
2452
|
+
}
|
|
2453
|
+
function conflictOf(name, server, baseline) {
|
|
2454
|
+
const what = `configuration-map key "${name}"`;
|
|
2455
|
+
if (!baseline) return `${what}: no configuration-map baseline for this installation on this machine; pull or adopt to record one`;
|
|
2456
|
+
const recorded = baseline[name];
|
|
2457
|
+
if (recorded === void 0) return server ? `${what} was created on the server since the last pull` : void 0;
|
|
2458
|
+
if (!server) return `${what} was deleted on the server since the last pull`;
|
|
2459
|
+
return digest(name, server) === recorded ? void 0 : `${what} changed on the server since the last pull`;
|
|
2460
|
+
}
|
|
2461
|
+
function planConfigMap(local, remote, names, baseline) {
|
|
2462
|
+
const tree = byKey(configMapOf(local));
|
|
2463
|
+
const server = byKey(configMapOf(remote));
|
|
2464
|
+
const plan = { changes: [], conflicts: [], unchanged: [] };
|
|
2465
|
+
for (const name of new Set(names)) {
|
|
2466
|
+
const t = tree.get(name);
|
|
2467
|
+
const s = server.get(name);
|
|
2468
|
+
if (!t && !s) throw new UnknownConfigMapKey(name);
|
|
2469
|
+
if (sameEntry(t, s)) {
|
|
2470
|
+
plan.unchanged.push(name);
|
|
2471
|
+
continue;
|
|
2472
|
+
}
|
|
2473
|
+
plan.changes.push({ kind: "configMapKey", op: !s ? "create" : !t ? "delete" : "update", id: name, label: name });
|
|
2474
|
+
const conflict = conflictOf(name, s, baseline);
|
|
2475
|
+
if (conflict) plan.conflicts.push(conflict);
|
|
2476
|
+
}
|
|
2477
|
+
return plan;
|
|
2478
|
+
}
|
|
2479
|
+
var UnknownConfigMapKey = class extends Error {
|
|
2480
|
+
constructor(key) {
|
|
2481
|
+
super(`no configuration-map key named "${key}" in the tree or on the server`);
|
|
2482
|
+
this.key = key;
|
|
2483
|
+
}
|
|
2484
|
+
key;
|
|
2485
|
+
};
|
|
2486
|
+
function configMapMoved(names, before, after) {
|
|
2487
|
+
const [b, a] = [byKey(configMapOf(before)), byKey(configMapOf(after))];
|
|
2488
|
+
return names.filter((n) => !sameEntry(b.get(n), a.get(n)));
|
|
2489
|
+
}
|
|
2490
|
+
function otherDifferingKeys(a, b, names) {
|
|
2491
|
+
const [x, y] = [byKey(configMapOf(a)), byKey(configMapOf(b))];
|
|
2492
|
+
const skip = new Set(names);
|
|
2493
|
+
return [.../* @__PURE__ */ new Set([...x.keys(), ...y.keys()])].filter((k) => !skip.has(k) && !sameEntry(x.get(k), y.get(k))).sort();
|
|
2494
|
+
}
|
|
2495
|
+
function mergeConfigMap(server, local, names) {
|
|
2496
|
+
const tree = byKey(configMapOf(local));
|
|
2497
|
+
const wanted = new Set(names);
|
|
2498
|
+
const placed = /* @__PURE__ */ new Set();
|
|
2499
|
+
const entry = [];
|
|
2500
|
+
for (const e of configMapOf(server)) {
|
|
2501
|
+
const k = configMapKeyOf(e);
|
|
2502
|
+
if (k === void 0 || !wanted.has(k)) {
|
|
2503
|
+
entry.push(e);
|
|
2504
|
+
continue;
|
|
2505
|
+
}
|
|
2506
|
+
placed.add(k);
|
|
2507
|
+
const t = tree.get(k);
|
|
2508
|
+
if (t) entry.push(structuredClone(t));
|
|
2509
|
+
}
|
|
2510
|
+
for (const n of wanted) {
|
|
2511
|
+
const t = tree.get(n);
|
|
2512
|
+
if (!placed.has(n) && t) entry.push(structuredClone(t));
|
|
2513
|
+
}
|
|
2514
|
+
const holder = isObj(server["configurationMap"]) ? server["configurationMap"] : {};
|
|
2515
|
+
return { ...holder, entry };
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
// src/push/index.ts
|
|
2519
|
+
var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2363
2520
|
function list(v) {
|
|
2364
2521
|
if (v == null || v === "") return [];
|
|
2365
|
-
return (Array.isArray(v) ? v : [v]).filter(
|
|
2522
|
+
return (Array.isArray(v) ? v : [v]).filter(isObj2);
|
|
2366
2523
|
}
|
|
2367
2524
|
function channelsOf(c) {
|
|
2368
|
-
return
|
|
2525
|
+
return isObj2(c["channels"]) ? list(c["channels"]["channel"]) : [];
|
|
2369
2526
|
}
|
|
2370
2527
|
function librariesOf(c) {
|
|
2371
|
-
return
|
|
2528
|
+
return isObj2(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
|
|
2372
2529
|
}
|
|
2373
2530
|
function templatesOf2(library) {
|
|
2374
|
-
return
|
|
2531
|
+
return isObj2(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
|
|
2375
2532
|
}
|
|
2376
2533
|
var idOf = (o) => String(o["id"]);
|
|
2377
2534
|
var nameOf = (o) => String(o["name"] ?? o["id"]);
|
|
@@ -2382,14 +2539,14 @@ function normalizeEol(s) {
|
|
|
2382
2539
|
function normalizeEolDeep(value) {
|
|
2383
2540
|
if (typeof value === "string") return normalizeEol(value);
|
|
2384
2541
|
if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
|
|
2385
|
-
if (
|
|
2542
|
+
if (isObj2(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
|
|
2386
2543
|
return value;
|
|
2387
2544
|
}
|
|
2388
2545
|
function same(a, b) {
|
|
2389
2546
|
if (a === b) return true;
|
|
2390
2547
|
if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
|
|
2391
2548
|
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
|
|
2392
|
-
if (
|
|
2549
|
+
if (isObj2(a) && isObj2(b)) {
|
|
2393
2550
|
const ka = Object.keys(a);
|
|
2394
2551
|
return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
|
|
2395
2552
|
}
|
|
@@ -2398,9 +2555,9 @@ function same(a, b) {
|
|
|
2398
2555
|
var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
|
|
2399
2556
|
function withSortedContexts(o) {
|
|
2400
2557
|
const set = o["contextSet"];
|
|
2401
|
-
const delegate =
|
|
2402
|
-
const types =
|
|
2403
|
-
if (!
|
|
2558
|
+
const delegate = isObj2(set) ? set["delegate"] : void 0;
|
|
2559
|
+
const types = isObj2(delegate) ? delegate["contextType"] : void 0;
|
|
2560
|
+
if (!isObj2(set) || !isObj2(delegate) || !Array.isArray(types)) return o;
|
|
2404
2561
|
const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
|
|
2405
2562
|
return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
|
|
2406
2563
|
}
|
|
@@ -2409,8 +2566,8 @@ function stripVolatile(o) {
|
|
|
2409
2566
|
delete out["revision"];
|
|
2410
2567
|
delete out["lastModified"];
|
|
2411
2568
|
const exportData = out["exportData"];
|
|
2412
|
-
if (
|
|
2413
|
-
const metadata =
|
|
2569
|
+
if (isObj2(exportData)) {
|
|
2570
|
+
const metadata = isObj2(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
|
|
2414
2571
|
if (metadata) {
|
|
2415
2572
|
delete metadata["lastModified"];
|
|
2416
2573
|
delete metadata["userId"];
|
|
@@ -2419,22 +2576,22 @@ function stripVolatile(o) {
|
|
|
2419
2576
|
}
|
|
2420
2577
|
return out;
|
|
2421
2578
|
}
|
|
2422
|
-
var groupsOf = (c) =>
|
|
2579
|
+
var groupsOf = (c) => isObj2(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
|
|
2423
2580
|
function withoutVolatile(c) {
|
|
2424
2581
|
const out = structuredClone(c);
|
|
2425
2582
|
const strip = (o) => {
|
|
2426
2583
|
delete o["revision"];
|
|
2427
2584
|
delete o["lastModified"];
|
|
2428
2585
|
const exportData = o["exportData"];
|
|
2429
|
-
const md =
|
|
2430
|
-
if (
|
|
2586
|
+
const md = isObj2(exportData) ? exportData["metadata"] : void 0;
|
|
2587
|
+
if (isObj2(md)) {
|
|
2431
2588
|
delete md["lastModified"];
|
|
2432
2589
|
delete md["userId"];
|
|
2433
2590
|
}
|
|
2434
|
-
if (
|
|
2591
|
+
if (isObj2(exportData)) {
|
|
2435
2592
|
for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
|
|
2436
2593
|
}
|
|
2437
|
-
if (
|
|
2594
|
+
if (isObj2(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
|
|
2438
2595
|
};
|
|
2439
2596
|
for (const ch of channelsOf(out)) strip(ch);
|
|
2440
2597
|
for (const lib of librariesOf(out)) {
|
|
@@ -2443,7 +2600,7 @@ function withoutVolatile(c) {
|
|
|
2443
2600
|
}
|
|
2444
2601
|
for (const g of groupsOf(out)) {
|
|
2445
2602
|
strip(g);
|
|
2446
|
-
for (const member of
|
|
2603
|
+
for (const member of isObj2(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
|
|
2447
2604
|
}
|
|
2448
2605
|
return out;
|
|
2449
2606
|
}
|
|
@@ -2471,12 +2628,12 @@ function withRetainedMembers(local, remote, localIds, deletedIds) {
|
|
|
2471
2628
|
const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
|
|
2472
2629
|
if (!retained.length) return local;
|
|
2473
2630
|
return { ...local, codeTemplates: {
|
|
2474
|
-
...
|
|
2631
|
+
...isObj2(local["codeTemplates"]) ? local["codeTemplates"] : {},
|
|
2475
2632
|
codeTemplate: [...templatesOf2(local), ...retained]
|
|
2476
2633
|
} };
|
|
2477
2634
|
}
|
|
2478
2635
|
function hashGlobalScripts(c) {
|
|
2479
|
-
return
|
|
2636
|
+
return createHash3("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
|
|
2480
2637
|
}
|
|
2481
2638
|
function resourceIds(c) {
|
|
2482
2639
|
const libs = librariesOf(c);
|
|
@@ -2508,7 +2665,7 @@ function adoptTarget(local, target) {
|
|
|
2508
2665
|
return { config, known };
|
|
2509
2666
|
}
|
|
2510
2667
|
function knownFrom(raw) {
|
|
2511
|
-
if (!
|
|
2668
|
+
if (!isObj2(raw)) return void 0;
|
|
2512
2669
|
const r = raw;
|
|
2513
2670
|
const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
|
|
2514
2671
|
return {
|
|
@@ -2568,7 +2725,7 @@ function librariesInSync(local, remote) {
|
|
|
2568
2725
|
}).map(idOf);
|
|
2569
2726
|
}
|
|
2570
2727
|
function channelsUsing(lib, allChannelIds) {
|
|
2571
|
-
const ids = (v) =>
|
|
2728
|
+
const ids = (v) => isObj2(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
|
|
2572
2729
|
if (lib["includeNewChannels"] === true) {
|
|
2573
2730
|
const disabled = new Set(ids(lib["disabledChannelIds"]));
|
|
2574
2731
|
return allChannelIds.filter((id) => !disabled.has(id));
|
|
@@ -2713,11 +2870,11 @@ rename one of them, or delete or rename the other in a push of its own first`
|
|
|
2713
2870
|
conflicts.push("global scripts changed on the server since the last pull");
|
|
2714
2871
|
}
|
|
2715
2872
|
}
|
|
2716
|
-
const notPushed = everything ? [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].filter((k) => !HANDLED.has(k) && !k.startsWith("@") && !same(local[k], remote[k])).sort() : [];
|
|
2873
|
+
const notPushed = everything ? [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].filter((k) => !HANDLED.has(k) && !k.startsWith("@") && !(k === "configurationMap" ? sameConfigMap(local, remote) : same(local[k], remote[k]))).sort() : [];
|
|
2717
2874
|
const enabled = new Set(
|
|
2718
2875
|
[...effective.values()].filter((c) => {
|
|
2719
|
-
const md =
|
|
2720
|
-
return !(
|
|
2876
|
+
const md = isObj2(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
|
|
2877
|
+
return !(isObj2(md) && md["enabled"] === false);
|
|
2721
2878
|
}).map(idOf)
|
|
2722
2879
|
);
|
|
2723
2880
|
return {
|
|
@@ -2947,24 +3104,47 @@ async function refreshRevisions(root, server, ids) {
|
|
|
2947
3104
|
}
|
|
2948
3105
|
}
|
|
2949
3106
|
|
|
3107
|
+
// src/configMapBaselines.ts
|
|
3108
|
+
import { createHash as createHash4 } from "crypto";
|
|
3109
|
+
import { existsSync as existsSync7 } from "fs";
|
|
3110
|
+
import { mkdir as mkdir5 } from "fs/promises";
|
|
3111
|
+
import * as path7 from "path";
|
|
3112
|
+
var BASELINES_DIR = "config-map-baselines";
|
|
3113
|
+
function fileFor(serverId) {
|
|
3114
|
+
return path7.join(configDir(), BASELINES_DIR, `${createHash4("sha256").update(serverId).digest("hex").slice(0, 32)}.json`);
|
|
3115
|
+
}
|
|
3116
|
+
async function readConfigMapBaseline(serverId) {
|
|
3117
|
+
const file = fileFor(serverId);
|
|
3118
|
+
if (!existsSync7(file)) return void 0;
|
|
3119
|
+
const stored = await readJson(file);
|
|
3120
|
+
if (stored.serverId !== serverId || typeof stored.entries !== "object" || stored.entries === null) return void 0;
|
|
3121
|
+
return stored.entries;
|
|
3122
|
+
}
|
|
3123
|
+
async function writeConfigMapBaseline(serverId, entries) {
|
|
3124
|
+
const file = fileFor(serverId);
|
|
3125
|
+
await mkdir5(path7.dirname(file), { recursive: true, mode: 448 });
|
|
3126
|
+
await writePrivate(file, `${JSON.stringify({ serverId, entries }, null, 2)}
|
|
3127
|
+
`);
|
|
3128
|
+
}
|
|
3129
|
+
|
|
2950
3130
|
// src/xml/chars.ts
|
|
2951
3131
|
import { readFile as readFile5 } from "fs/promises";
|
|
2952
|
-
import * as
|
|
3132
|
+
import * as path9 from "path";
|
|
2953
3133
|
|
|
2954
3134
|
// src/tree/transaction.ts
|
|
2955
3135
|
import { randomUUID } from "crypto";
|
|
2956
|
-
import { constants, existsSync as
|
|
2957
|
-
import { copyFile as copyFile2, lstat as lstat3, mkdir as
|
|
3136
|
+
import { constants, existsSync as existsSync8 } from "fs";
|
|
3137
|
+
import { copyFile as copyFile2, lstat as lstat3, mkdir as mkdir6, readdir as readdir5, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
|
|
2958
3138
|
import { hostname } from "os";
|
|
2959
|
-
import * as
|
|
3139
|
+
import * as path8 from "path";
|
|
2960
3140
|
import { setTimeout as delay } from "timers/promises";
|
|
2961
3141
|
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2962
3142
|
async function treeFiles(base) {
|
|
2963
3143
|
const out = [];
|
|
2964
3144
|
for (const d of MANAGED_DIRS) {
|
|
2965
|
-
if (!
|
|
2966
|
-
for (const entry of await readdir5(
|
|
2967
|
-
if (entry.isFile()) out.push(
|
|
3145
|
+
if (!existsSync8(path8.join(base, d))) continue;
|
|
3146
|
+
for (const entry of await readdir5(path8.join(base, d), { recursive: true, withFileTypes: true })) {
|
|
3147
|
+
if (entry.isFile()) out.push(path8.relative(base, path8.join(entry.parentPath, entry.name)).split(path8.sep).join("/"));
|
|
2968
3148
|
}
|
|
2969
3149
|
}
|
|
2970
3150
|
return out;
|
|
@@ -2985,12 +3165,12 @@ async function move(from, to) {
|
|
|
2985
3165
|
}
|
|
2986
3166
|
}
|
|
2987
3167
|
async function lockTree(root) {
|
|
2988
|
-
await
|
|
3168
|
+
await mkdir6(path8.dirname(root), { recursive: true });
|
|
2989
3169
|
const lock = `${await canonical(root)}.channelvault-lock`;
|
|
2990
|
-
const ownerFile =
|
|
3170
|
+
const ownerFile = path8.join(lock, "owner.json");
|
|
2991
3171
|
const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
|
|
2992
3172
|
try {
|
|
2993
|
-
await
|
|
3173
|
+
await mkdir6(lock);
|
|
2994
3174
|
} catch (err) {
|
|
2995
3175
|
if (err.code !== "EEXIST") throw err;
|
|
2996
3176
|
if ((await lstat3(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
|
|
@@ -3010,9 +3190,9 @@ async function lockTree(root) {
|
|
|
3010
3190
|
}
|
|
3011
3191
|
};
|
|
3012
3192
|
if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
|
|
3013
|
-
const reaping =
|
|
3193
|
+
const reaping = path8.join(lock, "reaping");
|
|
3014
3194
|
try {
|
|
3015
|
-
await
|
|
3195
|
+
await mkdir6(reaping);
|
|
3016
3196
|
} catch {
|
|
3017
3197
|
throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
|
|
3018
3198
|
}
|
|
@@ -3024,7 +3204,7 @@ async function lockTree(root) {
|
|
|
3024
3204
|
await rmdir(reaping);
|
|
3025
3205
|
}
|
|
3026
3206
|
await rmdir(lock);
|
|
3027
|
-
await
|
|
3207
|
+
await mkdir6(lock);
|
|
3028
3208
|
}
|
|
3029
3209
|
try {
|
|
3030
3210
|
await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
|
|
@@ -3041,7 +3221,7 @@ async function lockTree(root) {
|
|
|
3041
3221
|
}
|
|
3042
3222
|
async function assertStage(root) {
|
|
3043
3223
|
for (const suffix of ["", "next", "previous"]) {
|
|
3044
|
-
const stage =
|
|
3224
|
+
const stage = path8.join(root, STAGING_DIR, suffix);
|
|
3045
3225
|
const info = await lstat3(stage).catch((err) => {
|
|
3046
3226
|
if (err.code !== "ENOENT") throw err;
|
|
3047
3227
|
return void 0;
|
|
@@ -3050,10 +3230,10 @@ async function assertStage(root) {
|
|
|
3050
3230
|
}
|
|
3051
3231
|
}
|
|
3052
3232
|
function targetOf(root, journal, name) {
|
|
3053
|
-
return name === "env" ? journal.envFile :
|
|
3233
|
+
return name === "env" ? journal.envFile : path8.join(root, name);
|
|
3054
3234
|
}
|
|
3055
3235
|
function copies(root, journal, name) {
|
|
3056
|
-
return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old:
|
|
3236
|
+
return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path8.join(root, STAGING_DIR, "previous", name), next: path8.join(root, STAGING_DIR, "next", name) };
|
|
3057
3237
|
}
|
|
3058
3238
|
async function cleanup(root, journal) {
|
|
3059
3239
|
if (journal.entries.some((e) => e.name === "env")) {
|
|
@@ -3061,7 +3241,7 @@ async function cleanup(root, journal) {
|
|
|
3061
3241
|
await rm3(old, { force: true });
|
|
3062
3242
|
await rm3(next, { force: true });
|
|
3063
3243
|
}
|
|
3064
|
-
await rm3(
|
|
3244
|
+
await rm3(path8.join(root, STAGING_DIR), RM);
|
|
3065
3245
|
}
|
|
3066
3246
|
async function rollback(root, journal) {
|
|
3067
3247
|
for (const entry of [...journal.entries].reverse()) {
|
|
@@ -3076,14 +3256,14 @@ async function rollback(root, journal) {
|
|
|
3076
3256
|
}
|
|
3077
3257
|
}
|
|
3078
3258
|
async function pendingEnvFile(root) {
|
|
3079
|
-
const file =
|
|
3080
|
-
if (!
|
|
3259
|
+
const file = path8.join(root, JOURNAL);
|
|
3260
|
+
if (!existsSync8(file)) return null;
|
|
3081
3261
|
const journal = await readJson(file).catch(() => null);
|
|
3082
3262
|
return typeof journal?.envFile === "string" ? journal.envFile : null;
|
|
3083
3263
|
}
|
|
3084
3264
|
async function recoverTree(root, envFiles) {
|
|
3085
|
-
const file =
|
|
3086
|
-
if (!
|
|
3265
|
+
const file = path8.join(root, JOURNAL);
|
|
3266
|
+
if (!existsSync8(file)) return;
|
|
3087
3267
|
await assertStage(root);
|
|
3088
3268
|
const journal = await readJson(file);
|
|
3089
3269
|
const allowed = await Promise.all((Array.isArray(envFiles) ? envFiles : [envFiles]).map((f) => canonical(f)));
|
|
@@ -3097,17 +3277,17 @@ async function recoverTree(root, envFiles) {
|
|
|
3097
3277
|
async function replaceTree(root, envFile, prepare) {
|
|
3098
3278
|
await recoverTree(root, envFile);
|
|
3099
3279
|
await assertStage(root);
|
|
3100
|
-
const stage =
|
|
3280
|
+
const stage = path8.join(root, STAGING_DIR);
|
|
3101
3281
|
await rm3(stage, RM);
|
|
3102
|
-
const next =
|
|
3103
|
-
await
|
|
3282
|
+
const next = path8.join(stage, "next");
|
|
3283
|
+
await mkdir6(next, { recursive: true });
|
|
3104
3284
|
let journal;
|
|
3105
3285
|
try {
|
|
3106
3286
|
await prepare(next);
|
|
3107
3287
|
const targetEnv = await canonical(envFile);
|
|
3108
3288
|
journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
|
|
3109
3289
|
for (const name of ITEMS) {
|
|
3110
|
-
if (!MANAGED_DIRS.includes(name) && !
|
|
3290
|
+
if (!MANAGED_DIRS.includes(name) && !existsSync8(path8.join(next, name === "env" ? ".env" : name))) continue;
|
|
3111
3291
|
const target = targetOf(root, journal, name);
|
|
3112
3292
|
const info = await lstat3(target).catch((err) => {
|
|
3113
3293
|
if (err.code !== "ENOENT") throw err;
|
|
@@ -3115,38 +3295,38 @@ async function replaceTree(root, envFile, prepare) {
|
|
|
3115
3295
|
});
|
|
3116
3296
|
journal.entries.push({ name, hadOld: info !== void 0 });
|
|
3117
3297
|
}
|
|
3118
|
-
await
|
|
3119
|
-
await writePrivate(
|
|
3298
|
+
await mkdir6(path8.join(stage, "previous"));
|
|
3299
|
+
await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
|
|
3120
3300
|
if (journal.entries.some((e) => e.name === "env")) {
|
|
3121
|
-
await
|
|
3122
|
-
await copyFile2(
|
|
3301
|
+
await mkdir6(path8.dirname(targetEnv), { recursive: true });
|
|
3302
|
+
await copyFile2(path8.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
|
|
3123
3303
|
}
|
|
3124
3304
|
for (const entry of journal.entries) {
|
|
3125
3305
|
const target = targetOf(root, journal, entry.name);
|
|
3126
3306
|
const files = copies(root, journal, entry.name);
|
|
3127
3307
|
if (entry.hadOld) await move(target, files.old);
|
|
3128
|
-
if (
|
|
3129
|
-
await
|
|
3308
|
+
if (existsSync8(files.next)) {
|
|
3309
|
+
await mkdir6(path8.dirname(target), { recursive: true });
|
|
3130
3310
|
await move(files.next, target);
|
|
3131
3311
|
}
|
|
3132
3312
|
}
|
|
3133
3313
|
journal.state = "committed";
|
|
3134
|
-
await writePrivate(
|
|
3314
|
+
await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
|
|
3135
3315
|
} catch (err) {
|
|
3136
|
-
if (journal &&
|
|
3316
|
+
if (journal && existsSync8(path8.join(root, JOURNAL))) {
|
|
3137
3317
|
try {
|
|
3138
3318
|
await rollback(root, journal);
|
|
3139
3319
|
} catch (recoveryError) {
|
|
3140
|
-
throw new Error(`replacement failed and recovery is pending in ${
|
|
3320
|
+
throw new Error(`replacement failed and recovery is pending in ${path8.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
|
|
3141
3321
|
}
|
|
3142
3322
|
await cleanup(root, journal);
|
|
3143
|
-
await unlink(
|
|
3323
|
+
await unlink(path8.join(root, JOURNAL));
|
|
3144
3324
|
}
|
|
3145
3325
|
await rm3(stage, RM);
|
|
3146
3326
|
throw err;
|
|
3147
3327
|
}
|
|
3148
3328
|
await cleanup(root, journal);
|
|
3149
|
-
await unlink(
|
|
3329
|
+
await unlink(path8.join(root, JOURNAL));
|
|
3150
3330
|
}
|
|
3151
3331
|
|
|
3152
3332
|
// src/xml/chars.ts
|
|
@@ -3173,7 +3353,7 @@ function forbiddenXmlChars(config) {
|
|
|
3173
3353
|
async function forbiddenInFiles(root) {
|
|
3174
3354
|
const out = [];
|
|
3175
3355
|
for (const file of await treeFiles(root)) {
|
|
3176
|
-
for (const p of positions(await readFile5(
|
|
3356
|
+
for (const p of positions(await readFile5(path9.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
|
|
3177
3357
|
}
|
|
3178
3358
|
return out;
|
|
3179
3359
|
}
|
|
@@ -3267,7 +3447,7 @@ function addBackupDirFlags(cmd) {
|
|
|
3267
3447
|
return cmd.option("--backup-dir <dir>", "where backups are kept (default ~/.channelvault/backups, shared by every checkout)").option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
|
|
3268
3448
|
}
|
|
3269
3449
|
function backupDirOf(flags) {
|
|
3270
|
-
return
|
|
3450
|
+
return path10.resolve(flags.backupDir ?? defaultBackupDir());
|
|
3271
3451
|
}
|
|
3272
3452
|
function keepOf(flags) {
|
|
3273
3453
|
if (flags.keep === void 0) return DEFAULT_KEEP;
|
|
@@ -3372,9 +3552,18 @@ function summarize(config) {
|
|
|
3372
3552
|
codeTemplates
|
|
3373
3553
|
};
|
|
3374
3554
|
}
|
|
3555
|
+
async function recordConfigMapBaseline(serverId, baseline) {
|
|
3556
|
+
if (!serverId) return;
|
|
3557
|
+
try {
|
|
3558
|
+
await writeConfigMapBaseline(serverId, baseline);
|
|
3559
|
+
} catch (err) {
|
|
3560
|
+
process.stderr.write(`note: could not record the configuration-map baseline (${err instanceof Error ? err.message : String(err)}); pushing configuration-map keys will need a pull that can
|
|
3561
|
+
`);
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3375
3564
|
async function readMeta(root) {
|
|
3376
|
-
const metaPath =
|
|
3377
|
-
if (!
|
|
3565
|
+
const metaPath = path10.join(root, "channelvault.json");
|
|
3566
|
+
if (!existsSync9(metaPath)) return null;
|
|
3378
3567
|
let meta;
|
|
3379
3568
|
try {
|
|
3380
3569
|
meta = await readJson(metaPath);
|
|
@@ -3399,33 +3588,33 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
|
|
|
3399
3588
|
resources,
|
|
3400
3589
|
serverId
|
|
3401
3590
|
};
|
|
3402
|
-
const file =
|
|
3591
|
+
const file = path10.join(root, "channelvault.json");
|
|
3403
3592
|
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
|
|
3404
3593
|
await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
3405
3594
|
}
|
|
3406
3595
|
async function envFileFor(root, flags, conn) {
|
|
3407
|
-
if (flags.dotenv) return
|
|
3408
|
-
const local =
|
|
3596
|
+
if (flags.dotenv) return path10.resolve(flags.dotenv);
|
|
3597
|
+
const local = path10.join(root, ".env");
|
|
3409
3598
|
if (!conn?.dotenv) return local;
|
|
3410
|
-
if (!
|
|
3599
|
+
if (!existsSync9(local) || samePath(await canonical(local), await canonical(conn.dotenv))) {
|
|
3411
3600
|
await assertNoSwapPending(conn.dotenv);
|
|
3412
3601
|
return conn.dotenv;
|
|
3413
3602
|
}
|
|
3414
3603
|
fail(`both ${local} and profile ${conn.profile}'s env file ${conn.dotenv} exist; pass --dotenv to choose one, or remove the one that is stale`, "env-ambiguous");
|
|
3415
3604
|
}
|
|
3416
3605
|
async function assertNoSwapPending(file) {
|
|
3417
|
-
const dir =
|
|
3418
|
-
if (!
|
|
3419
|
-
const prefix = `${
|
|
3606
|
+
const dir = path10.dirname(file);
|
|
3607
|
+
if (!existsSync9(dir)) return;
|
|
3608
|
+
const prefix = `${path10.basename(file)}.channelvault-`;
|
|
3420
3609
|
const pending = (await readdir6(dir)).filter((n) => n.startsWith(prefix) && /\.(next|previous)$/.test(n));
|
|
3421
3610
|
if (pending.length > 0) {
|
|
3422
3611
|
fail(`${file} is being replaced by a pull in another checkout (${pending.join(", ")} beside it); retry when it finishes, or rerun that checkout's command to finish an interrupted one`, "env-busy");
|
|
3423
3612
|
}
|
|
3424
3613
|
}
|
|
3425
3614
|
async function recoveryCandidates(root, flags) {
|
|
3426
|
-
if (flags.dotenv) return [
|
|
3615
|
+
if (flags.dotenv) return [path10.resolve(flags.dotenv)];
|
|
3427
3616
|
const dotenvs = Object.values(await loadProfiles()).flatMap((p) => p.dotenv ? [p.dotenv] : []);
|
|
3428
|
-
return [
|
|
3617
|
+
return [path10.join(root, ".env"), ...dotenvs];
|
|
3429
3618
|
}
|
|
3430
3619
|
async function loadEnv(file) {
|
|
3431
3620
|
return { ...await readEnvFile(file), ...process.env };
|
|
@@ -3437,7 +3626,7 @@ function addExtractFlag(cmd) {
|
|
|
3437
3626
|
return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
|
|
3438
3627
|
}
|
|
3439
3628
|
async function existingTree(root) {
|
|
3440
|
-
return
|
|
3629
|
+
return existsSync9(path10.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
|
|
3441
3630
|
}
|
|
3442
3631
|
async function renderedTree(root, envFile) {
|
|
3443
3632
|
const tree = await engine.implode({ root });
|
|
@@ -3448,15 +3637,24 @@ async function renderedTree(root, envFile) {
|
|
|
3448
3637
|
var knownSecrets = /* @__PURE__ */ new Set();
|
|
3449
3638
|
var everywhereSecrets = /* @__PURE__ */ new Set();
|
|
3450
3639
|
function rememberSecret(value, opts = {}) {
|
|
3451
|
-
if (value === void 0 || value.length < 4) return;
|
|
3640
|
+
if (value === void 0 || value.length < 4 || /^(true|false)$/i.test(value)) return;
|
|
3452
3641
|
knownSecrets.add(value);
|
|
3453
3642
|
if (opts.stdout && value.length >= 8) everywhereSecrets.add(value);
|
|
3454
3643
|
}
|
|
3455
3644
|
function rememberSecrets(tree, env) {
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
});
|
|
3645
|
+
for (const name of placeholderNames(tree)) rememberSecret(env[name]);
|
|
3646
|
+
}
|
|
3647
|
+
function assertEnvComplete(tree, server, env, envFile, conn) {
|
|
3648
|
+
const { compared, treeOnly } = placeholderUse(tree, server);
|
|
3649
|
+
const unset = (names) => [...names].filter((name) => env[name] === void 0).sort();
|
|
3650
|
+
const missing = unset(compared);
|
|
3651
|
+
if (missing.length > 0) {
|
|
3652
|
+
const fix = conn.dotenv && samePath(envFile, conn.dotenv) ? `set them in profile ${conn.profile}'s env file, or pass --dotenv <file>` : conn.dotenv ? `drop --dotenv to use profile ${conn.profile}'s env file ${conn.dotenv}` : `pass --dotenv <file>, or ${conn.profile ? `give profile ${conn.profile} one at a terminal with \`channelvault profile set ${conn.profile} --dotenv <absolute path>\`` : "use a connection profile with a dotenv"}`;
|
|
3653
|
+
const what = `no value for ${missing.join(", ")}, so those secrets can't be compared`;
|
|
3654
|
+
if (!existsSync9(envFile)) fail(`there is no env file at ${envFile}: ${what}; ${fix}`, "env-missing");
|
|
3655
|
+
fail(`${envFile} has ${what}; add them, or ${fix}`, "env-incomplete");
|
|
3656
|
+
}
|
|
3657
|
+
return unset(treeOnly);
|
|
3460
3658
|
}
|
|
3461
3659
|
for (const stream of [process.stdout, process.stderr]) {
|
|
3462
3660
|
const write = stream.write.bind(stream);
|
|
@@ -3478,8 +3676,8 @@ function scrub(text, secrets = knownSecrets) {
|
|
|
3478
3676
|
}
|
|
3479
3677
|
var ALLOW_FILE = "channelvault.allow.json";
|
|
3480
3678
|
async function readAllow(root) {
|
|
3481
|
-
const file =
|
|
3482
|
-
if (!
|
|
3679
|
+
const file = path10.join(root, ALLOW_FILE);
|
|
3680
|
+
if (!existsSync9(file)) return [];
|
|
3483
3681
|
const parsed = await readJson(file);
|
|
3484
3682
|
return parsed.ignore ?? [];
|
|
3485
3683
|
}
|
|
@@ -3503,30 +3701,31 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
3503
3701
|
const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
|
|
3504
3702
|
rememberSecrets(config, { ...env, ...envUpdates });
|
|
3505
3703
|
const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
|
|
3506
|
-
const rel =
|
|
3507
|
-
const envInTree = !rel.startsWith("..") && !
|
|
3704
|
+
const rel = path10.relative(root, envFile);
|
|
3705
|
+
const envInTree = !rel.startsWith("..") && !path10.isAbsolute(rel);
|
|
3508
3706
|
let backup = null;
|
|
3509
3707
|
await replaceTree(root, envFile, async (next) => {
|
|
3510
3708
|
await engine.explode(config, { root: next });
|
|
3511
3709
|
await writeMeta(next, source, fetched, previousMeta, serverId);
|
|
3512
3710
|
if (Object.keys(envUpdates).length > 0) {
|
|
3513
|
-
const history =
|
|
3514
|
-
if (
|
|
3711
|
+
const history = path10.join(root, ".secrets");
|
|
3712
|
+
if (existsSync9(history)) {
|
|
3515
3713
|
if ((await lstat4(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
|
|
3516
|
-
await cp(history,
|
|
3714
|
+
await cp(history, path10.join(next, ".secrets"), { recursive: true });
|
|
3517
3715
|
}
|
|
3518
|
-
const stagedBackup = await backupEnvFile(envFile, envUpdates,
|
|
3519
|
-
if (stagedBackup) backup =
|
|
3716
|
+
const stagedBackup = await backupEnvFile(envFile, envUpdates, path10.join(next, ".secrets"));
|
|
3717
|
+
if (stagedBackup) backup = path10.join(root, ".secrets", path10.basename(stagedBackup));
|
|
3520
3718
|
if (backup || envInTree) {
|
|
3521
|
-
const ignore =
|
|
3522
|
-
if (
|
|
3719
|
+
const ignore = path10.join(root, ".gitignore");
|
|
3720
|
+
if (existsSync9(ignore)) await writeFile6(path10.join(next, ".gitignore"), await readFile6(ignore));
|
|
3523
3721
|
await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
|
|
3524
3722
|
}
|
|
3525
|
-
const stagedEnv =
|
|
3526
|
-
if (
|
|
3723
|
+
const stagedEnv = path10.join(next, ".env");
|
|
3724
|
+
if (existsSync9(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
|
|
3527
3725
|
await updateEnvFile(stagedEnv, envUpdates);
|
|
3528
3726
|
}
|
|
3529
3727
|
});
|
|
3728
|
+
await recordConfigMapBaseline(serverId, configMapBaseline(fetched));
|
|
3530
3729
|
if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
|
|
3531
3730
|
`);
|
|
3532
3731
|
const updated = Object.keys(envUpdates).length;
|
|
@@ -3540,24 +3739,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
3540
3739
|
process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
|
|
3541
3740
|
`);
|
|
3542
3741
|
}
|
|
3543
|
-
if (
|
|
3742
|
+
if (existsSync9(envFile) && gitWouldCommit(envFile)) {
|
|
3544
3743
|
process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
|
|
3545
3744
|
`);
|
|
3546
3745
|
}
|
|
3547
3746
|
}
|
|
3548
3747
|
function gitWouldCommit(file) {
|
|
3549
|
-
const
|
|
3748
|
+
const target = path10.resolve(file);
|
|
3749
|
+
let dir = path10.dirname(target);
|
|
3750
|
+
while (!existsSync9(dir) && path10.dirname(dir) !== dir) dir = path10.dirname(dir);
|
|
3751
|
+
const r = spawnSync2("git", ["check-ignore", "-q", path10.relative(dir, target).split(path10.sep).join("/")], { cwd: dir });
|
|
3550
3752
|
return r.status === 1;
|
|
3551
3753
|
}
|
|
3552
3754
|
async function preflightTree(root, envFile) {
|
|
3553
3755
|
const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
|
|
3554
3756
|
const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
|
|
3555
|
-
(d) => isWithin(
|
|
3757
|
+
(d) => isWithin(path10.resolve(envFile), path10.resolve(root, d)) || isWithin(realEnv, path10.join(realRoot, d))
|
|
3556
3758
|
);
|
|
3557
3759
|
if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
|
|
3558
3760
|
const meta = await readMeta(root);
|
|
3559
3761
|
if (meta) return meta;
|
|
3560
|
-
const foreign = MANAGED_DIRS.filter((d) =>
|
|
3762
|
+
const foreign = MANAGED_DIRS.filter((d) => existsSync9(path10.join(root, d)));
|
|
3561
3763
|
if (foreign.length > 0) {
|
|
3562
3764
|
fail(
|
|
3563
3765
|
`${root} is not a channelvault tree (no channelvault.json) but has ${foreign.map((d) => `${d}/`).join(", ")}, which this command would replace; nothing was written. Use a new or empty directory (or, if an earlier pull or explode into it was interrupted, delete those directories).`
|
|
@@ -3566,7 +3768,7 @@ async function preflightTree(root, envFile) {
|
|
|
3566
3768
|
return null;
|
|
3567
3769
|
}
|
|
3568
3770
|
function assertTree(root) {
|
|
3569
|
-
if (!
|
|
3771
|
+
if (!existsSync9(path10.join(root, "server", "configuration.json"))) {
|
|
3570
3772
|
fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
|
|
3571
3773
|
}
|
|
3572
3774
|
}
|
|
@@ -3618,15 +3820,24 @@ async function writeKnown(root, known) {
|
|
|
3618
3820
|
const meta = await readMeta(root);
|
|
3619
3821
|
if (!meta?.resources) return;
|
|
3620
3822
|
meta.resources = known;
|
|
3621
|
-
await writeFile6(
|
|
3823
|
+
await writeFile6(path10.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
3622
3824
|
}
|
|
3623
3825
|
function printNameChange(incoming, current) {
|
|
3624
3826
|
const [to, from] = [configuredName(incoming), configuredName(current)];
|
|
3625
3827
|
if (to !== from) process.stdout.write(`server name changes: ${from || "(none)"} -> ${to || "(none)"}
|
|
3626
3828
|
`);
|
|
3627
3829
|
}
|
|
3830
|
+
function withConfigMap(plan, map) {
|
|
3831
|
+
return { ...plan, changes: [...map.changes, ...plan.changes], conflicts: [...map.conflicts, ...plan.conflicts] };
|
|
3832
|
+
}
|
|
3628
3833
|
function printChanges(plan) {
|
|
3629
|
-
const kindLabel = {
|
|
3834
|
+
const kindLabel = {
|
|
3835
|
+
channel: "channel",
|
|
3836
|
+
library: "library",
|
|
3837
|
+
codeTemplate: "code template",
|
|
3838
|
+
globalScripts: "",
|
|
3839
|
+
configMapKey: "configuration-map key"
|
|
3840
|
+
};
|
|
3630
3841
|
for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}
|
|
3631
3842
|
`);
|
|
3632
3843
|
}
|
|
@@ -3641,7 +3852,7 @@ pull (and merge) first, or pass --force to overwrite the server's version`
|
|
|
3641
3852
|
}
|
|
3642
3853
|
const deletes = plan.changes.filter((c) => c.op === "delete").length;
|
|
3643
3854
|
if (deletes > 0 && !flags.allowDeletes) {
|
|
3644
|
-
problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow
|
|
3855
|
+
problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow the push`);
|
|
3645
3856
|
}
|
|
3646
3857
|
return problems;
|
|
3647
3858
|
}
|
|
@@ -3675,11 +3886,55 @@ function reportPlanOnly(flags, plan, problems, live, extra) {
|
|
|
3675
3886
|
`);
|
|
3676
3887
|
process.stdout.write("plan only: nothing was changed\n");
|
|
3677
3888
|
}
|
|
3889
|
+
var mapKeyLabel = (key) => `configuration-map key "${key}"`;
|
|
3890
|
+
async function pushConfigMapKeys(client, local, planned, named, changed, baseline, serverId, flags) {
|
|
3891
|
+
const current = await client.getServerConfiguration();
|
|
3892
|
+
const moved = configMapMoved(named, planned, current);
|
|
3893
|
+
if (moved.length > 0 && !flags.force) {
|
|
3894
|
+
fail(`changed on the server just before saving the configuration map: ${moved.map(mapKeyLabel).join(", ")}; nothing was saved. Pull and try again, or pass --force`);
|
|
3895
|
+
}
|
|
3896
|
+
try {
|
|
3897
|
+
await client.putConfigurationMap(mergeConfigMap(current, local, changed));
|
|
3898
|
+
} catch (err) {
|
|
3899
|
+
fail(`saving the configuration map failed; nothing else was pushed: ${err instanceof Error ? err.message : String(err)}`);
|
|
3900
|
+
}
|
|
3901
|
+
let after;
|
|
3902
|
+
try {
|
|
3903
|
+
after = await client.getServerConfiguration();
|
|
3904
|
+
} catch (err) {
|
|
3905
|
+
fail(`saved the configuration map, but could not read it back to check it: ${err instanceof Error ? err.message : String(err)}. Nothing else was pushed. ${exportBrokenHint(flags)}`);
|
|
3906
|
+
}
|
|
3907
|
+
const tree = new Map(configMapOf(local).map((e) => [configMapKeyOf(e), e]));
|
|
3908
|
+
const saved = new Map(configMapOf(after).map((e) => [configMapKeyOf(e), e]));
|
|
3909
|
+
const wrong = changed.filter((k) => !sameEntry(tree.get(k), saved.get(k)));
|
|
3910
|
+
if (wrong.length > 0) {
|
|
3911
|
+
fail(`saved the configuration map, but these keys do not read back as the tree has them: ${wrong.join(", ")}. Nothing else was pushed. Review the server; the undo command above restores the whole server as it was before this push`);
|
|
3912
|
+
}
|
|
3913
|
+
const others = otherDifferingKeys(current, after, changed);
|
|
3914
|
+
if (others.length > 0) {
|
|
3915
|
+
fail(`saved the named configuration-map keys, but other keys changed at the same time (probably a concurrent edit): ${others.join(", ")}. Nothing else was pushed. Review them on the server before pushing again`);
|
|
3916
|
+
}
|
|
3917
|
+
const next = baselineAfterPush(baseline, after, changed);
|
|
3918
|
+
if (next) await recordConfigMapBaseline(serverId, next);
|
|
3919
|
+
process.stdout.write(`saved ${changed.length} configuration-map key(s): ${changed.join(", ")}
|
|
3920
|
+
`);
|
|
3921
|
+
}
|
|
3678
3922
|
async function scopedPush(client, root, local, scope, target, flags, live) {
|
|
3679
3923
|
const remote = await client.getServerConfiguration();
|
|
3680
3924
|
const known = await readKnown(root);
|
|
3681
3925
|
const plan = planPush(local, remote, scope, known);
|
|
3682
|
-
const
|
|
3926
|
+
const mapKeys = flags.configMapKey ?? [];
|
|
3927
|
+
const mapBaseline = mapKeys.length > 0 ? await readConfigMapBaseline(live.serverId) : void 0;
|
|
3928
|
+
let mapPlan = { changes: [], conflicts: [], unchanged: [] };
|
|
3929
|
+
try {
|
|
3930
|
+
if (mapKeys.length > 0) mapPlan = planConfigMap(local, remote, mapKeys, mapBaseline);
|
|
3931
|
+
} catch (err) {
|
|
3932
|
+
if (err instanceof UnknownConfigMapKey) fail(err.message, "config-map-key-unknown");
|
|
3933
|
+
throw err;
|
|
3934
|
+
}
|
|
3935
|
+
const mapChanged = mapPlan.changes.map((c) => c.id);
|
|
3936
|
+
const shown = withConfigMap(plan, mapPlan);
|
|
3937
|
+
const problems = [...await bindingProblems(root, live.serverId), ...planProblems(shown, flags), ...await xmlProblems(root, local)];
|
|
3683
3938
|
const names = new Map(
|
|
3684
3939
|
[...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
|
|
3685
3940
|
);
|
|
@@ -3689,16 +3944,16 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
|
|
|
3689
3944
|
const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
|
|
3690
3945
|
if (flags.planOnly && flags.json) {
|
|
3691
3946
|
const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
|
|
3692
|
-
reportPlanOnly(flags,
|
|
3947
|
+
reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped", ...redeploy });
|
|
3693
3948
|
return;
|
|
3694
3949
|
}
|
|
3695
|
-
if (
|
|
3950
|
+
if (shown.changes.length === 0) {
|
|
3696
3951
|
process.stdout.write(`nothing to push: ${target} already matches the tree
|
|
3697
3952
|
`);
|
|
3698
3953
|
} else {
|
|
3699
3954
|
process.stdout.write(`Push to ${target}:
|
|
3700
3955
|
`);
|
|
3701
|
-
printChanges(
|
|
3956
|
+
printChanges(shown);
|
|
3702
3957
|
if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf2).join(", ")}
|
|
3703
3958
|
`);
|
|
3704
3959
|
if (notDeployed.length > 0) {
|
|
@@ -3707,7 +3962,15 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
|
|
|
3707
3962
|
}
|
|
3708
3963
|
}
|
|
3709
3964
|
if (plan.notPushed.length > 0) {
|
|
3710
|
-
|
|
3965
|
+
const mapHint = plan.notPushed.includes("configurationMap") ? ", or --config-map-key for named configuration-map keys" : "";
|
|
3966
|
+
process.stdout.write(`not pushed (differs; use --whole-server${mapHint}): ${plan.notPushed.join(", ")}
|
|
3967
|
+
`);
|
|
3968
|
+
}
|
|
3969
|
+
if (mapPlan.unchanged.length > 0) process.stdout.write(`configuration-map keys already as in the tree: ${mapPlan.unchanged.join(", ")}
|
|
3970
|
+
`);
|
|
3971
|
+
if (mapKeys.length > 0) {
|
|
3972
|
+
const others = otherDifferingKeys(local, remote, mapKeys);
|
|
3973
|
+
if (others.length > 0) process.stdout.write(`other configuration-map keys differ (not pushed): ${others.join(", ")}
|
|
3711
3974
|
`);
|
|
3712
3975
|
}
|
|
3713
3976
|
if (plan.serverOnly.length > 0) {
|
|
@@ -3715,29 +3978,30 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
|
|
|
3715
3978
|
`);
|
|
3716
3979
|
}
|
|
3717
3980
|
if (flags.planOnly) {
|
|
3718
|
-
reportPlanOnly(flags,
|
|
3981
|
+
reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped" });
|
|
3719
3982
|
return;
|
|
3720
3983
|
}
|
|
3721
3984
|
if (problems.length > 0) fail(problems.join("\n"));
|
|
3722
|
-
if (
|
|
3985
|
+
if (shown.changes.length === 0) return;
|
|
3723
3986
|
if (!flags.yes && !await confirm("Continue?")) {
|
|
3724
3987
|
process.stdout.write("aborted.\n");
|
|
3725
3988
|
return;
|
|
3726
3989
|
}
|
|
3727
3990
|
const fresh = await client.getServerConfiguration();
|
|
3728
|
-
const moved = changedSince(plan, remote, fresh);
|
|
3991
|
+
const moved = [...configMapMoved(mapKeys, remote, fresh).map(mapKeyLabel), ...changedSince(plan, remote, fresh)];
|
|
3729
3992
|
if (moved.length > 0 && !flags.force) {
|
|
3730
3993
|
fail(`changed on the server while this push was being confirmed:
|
|
3731
3994
|
${moved.join("\n ")}
|
|
3732
3995
|
pull and try again, or pass --force`);
|
|
3733
3996
|
}
|
|
3734
|
-
await backupBeforePush(client, live.conn, flags);
|
|
3997
|
+
await backupBeforePush(client, live.conn, { ...flags, overwriteConfigMap: mapChanged.length > 0 });
|
|
3735
3998
|
const afterBackup = await client.getServerConfiguration();
|
|
3736
|
-
const changedDuringBackup = changedSince(plan, fresh, afterBackup);
|
|
3999
|
+
const changedDuringBackup = [...configMapMoved(mapKeys, fresh, afterBackup).map(mapKeyLabel), ...changedSince(plan, fresh, afterBackup)];
|
|
3737
4000
|
if (!flags.force && changedDuringBackup.length) {
|
|
3738
4001
|
fail(`changed on the server during backup: ${changedDuringBackup.join(", ")}; pull and try again`);
|
|
3739
4002
|
}
|
|
3740
4003
|
await assertBinding(client, root);
|
|
4004
|
+
if (mapChanged.length > 0) await pushConfigMapKeys(client, local, afterBackup, mapKeys, mapChanged, mapBaseline, live.serverId, flags);
|
|
3741
4005
|
const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
|
|
3742
4006
|
let baselineError;
|
|
3743
4007
|
let changedAgain = [];
|
|
@@ -3771,13 +4035,13 @@ changed again after saving (pull and review before retrying): ${changedAgain.joi
|
|
|
3771
4035
|
if (baselineError) process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(baselineError)}
|
|
3772
4036
|
`);
|
|
3773
4037
|
const { change, error } = result.failed;
|
|
3774
|
-
fail(`applied ${result.applied.length} of ${
|
|
4038
|
+
fail(`applied ${result.applied.length + mapChanged.length} of ${shown.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
|
|
3775
4039
|
}
|
|
3776
4040
|
if (changedAgain.length > 0) {
|
|
3777
|
-
fail(`applied ${result.applied.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
|
|
4041
|
+
fail(`applied ${result.applied.length + mapChanged.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
|
|
3778
4042
|
${baselineError}` : ""}`);
|
|
3779
4043
|
}
|
|
3780
|
-
process.stdout.write(`pushed ${result.applied.length} change(s)
|
|
4044
|
+
process.stdout.write(`pushed ${result.applied.length + mapChanged.length} change(s)
|
|
3781
4045
|
`);
|
|
3782
4046
|
if (toDeploy.length > 0) {
|
|
3783
4047
|
const { deployed: deployed2, skipped, failures } = await deployChannels(client, toDeploy, nameOf2);
|
|
@@ -3792,7 +4056,7 @@ ${baselineError}` : ""}`);
|
|
|
3792
4056
|
if (baselineError) {
|
|
3793
4057
|
const note = unverified.length > 0 ? `
|
|
3794
4058
|
not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
|
|
3795
|
-
fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
|
|
4059
|
+
fail(`pushed ${result.applied.length + mapChanged.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
|
|
3796
4060
|
}
|
|
3797
4061
|
printCommitHint(root);
|
|
3798
4062
|
}
|
|
@@ -3902,6 +4166,7 @@ async function wholeServerPush(client, root, local, target, flags, live) {
|
|
|
3902
4166
|
const ids = resourceIds(local);
|
|
3903
4167
|
await refreshRevisions(root, after, /* @__PURE__ */ new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));
|
|
3904
4168
|
if (known) await writeKnown(root, resourceIds(after));
|
|
4169
|
+
if (flags.overwriteConfigMap) await recordConfigMapBaseline(live.serverId, configMapBaseline(after));
|
|
3905
4170
|
process.stdout.write(`pushed ${root} -> ${target}
|
|
3906
4171
|
`);
|
|
3907
4172
|
printCommitHint(root);
|
|
@@ -3912,8 +4177,8 @@ addExtractFlag(addEnvFlag(
|
|
|
3912
4177
|
program.command("explode").description("Explode a Mirth backup XML into a working tree").argument("<backup.xml>", "path to a Mirth backup config XML file").argument("<dir>", "output working-tree directory")
|
|
3913
4178
|
)).action(async (backupPath, dir, flags) => {
|
|
3914
4179
|
const config = xml.parse(await readFile6(backupPath, "utf8"));
|
|
3915
|
-
const root =
|
|
3916
|
-
await writeTree(root, config, `file:${
|
|
4180
|
+
const root = path10.resolve(dir);
|
|
4181
|
+
await writeTree(root, config, `file:${path10.resolve(backupPath)}`, flags, await envFileFor(root, flags));
|
|
3917
4182
|
const s = summarize(config);
|
|
3918
4183
|
process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
3919
4184
|
`);
|
|
@@ -3921,22 +4186,22 @@ addExtractFlag(addEnvFlag(
|
|
|
3921
4186
|
addEnvFlag(
|
|
3922
4187
|
program.command("implode").description("Reassemble a working tree into a Mirth backup XML").argument("<dir>", "working-tree directory").argument("<backup.xml>", "output XML path").option("--force", "implode even if the tree was pulled from a live server", false)
|
|
3923
4188
|
).action(async (dir, outPath, flags) => {
|
|
3924
|
-
const root =
|
|
4189
|
+
const root = path10.resolve(dir);
|
|
3925
4190
|
assertTree(root);
|
|
3926
4191
|
const config = await renderedTree(root, await envFileFor(root, flags));
|
|
3927
4192
|
await assertCompatibleOrigin(root, config, "xml", flags.force === true);
|
|
3928
4193
|
const xmlStr = xml.build(config);
|
|
3929
4194
|
await writeFile6(outPath, xmlStr, "utf8");
|
|
3930
|
-
process.stdout.write(`imploded ${root} -> ${
|
|
4195
|
+
process.stdout.write(`imploded ${root} -> ${path10.resolve(outPath)}
|
|
3931
4196
|
`);
|
|
3932
4197
|
});
|
|
3933
4198
|
addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
3934
4199
|
program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
|
|
3935
4200
|
))).action(async (dir, flags) => {
|
|
3936
|
-
const root =
|
|
4201
|
+
const root = path10.resolve(dir);
|
|
3937
4202
|
const conn = await selectConnection(root, flags);
|
|
3938
4203
|
const envFile = await envFileFor(root, flags, conn);
|
|
3939
|
-
if (!isWithin(
|
|
4204
|
+
if (!isWithin(path10.resolve(envFile), root)) await lockAlso(envFile);
|
|
3940
4205
|
const previous = await preflightTree(root, envFile);
|
|
3941
4206
|
const { config, serverId } = await withClient(conn, async (client, serverId2) => {
|
|
3942
4207
|
if (previous?.serverId && previous.serverId !== serverId2) {
|
|
@@ -3946,7 +4211,12 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
|
3946
4211
|
if (await client.getServerId() !== serverId2) fail("the installation changed while pulling; nothing was written");
|
|
3947
4212
|
return { config: config2, serverId: serverId2 };
|
|
3948
4213
|
}, { envFile });
|
|
4214
|
+
const envFileExisted = existsSync9(envFile);
|
|
3949
4215
|
await writeTree(root, config, urlOf(conn), flags, envFile, serverId);
|
|
4216
|
+
if (conn.profile && !conn.dotenv && !flags.dotenv && !envFileExisted && existsSync9(envFile)) {
|
|
4217
|
+
process.stderr.write(`note: profile ${conn.profile} has no env file of its own, so these values are only in ${envFile}, in this checkout; other checkouts and worktrees of this tree won't have them. To keep them in one place, run \`channelvault profile set ${conn.profile} --dotenv <absolute path>\` at a terminal, then move ${envFile} to that path
|
|
4218
|
+
`);
|
|
4219
|
+
}
|
|
3950
4220
|
const s = summarize(config);
|
|
3951
4221
|
process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
3952
4222
|
`);
|
|
@@ -3954,7 +4224,7 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
|
3954
4224
|
addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
3955
4225
|
program.command("adopt").description("Review and capture this installation as the tree baseline, preserving local content; writes no server resources").argument("<dir>", "working-tree directory").option("--plan-only", "preview the resulting push plan without changing the tree", false).option("-y, --yes", "accept the reviewed destination baseline without a prompt", false)
|
|
3956
4226
|
))).action(async (dir, flags) => {
|
|
3957
|
-
const root =
|
|
4227
|
+
const root = path10.resolve(dir);
|
|
3958
4228
|
assertTree(root);
|
|
3959
4229
|
if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
|
|
3960
4230
|
if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
|
|
@@ -3996,19 +4266,20 @@ Local content is preserved; the following differences become reviewed edits for
|
|
|
3996
4266
|
await engine.explode(rebased.config, { root: next });
|
|
3997
4267
|
await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
|
|
3998
4268
|
});
|
|
4269
|
+
await recordConfigMapBaseline(serverId, configMapBaseline(remote));
|
|
3999
4270
|
process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
|
|
4000
4271
|
`);
|
|
4001
4272
|
}, { envFile, quiet: flags.json });
|
|
4002
4273
|
});
|
|
4003
4274
|
addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
4004
|
-
program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
|
|
4275
|
+
program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--config-map-key <name>", "push this configuration-map key (alone: only the named keys); repeatable", collect).option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
|
|
4005
4276
|
))).action(
|
|
4006
4277
|
async (dir, flags) => {
|
|
4007
|
-
if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
|
|
4008
|
-
fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --
|
|
4278
|
+
if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts || flags.configMapKey)) {
|
|
4279
|
+
fail("--whole-server replaces everything; it cannot be combined with --channel, --library, --global-scripts or --config-map-key");
|
|
4009
4280
|
}
|
|
4010
4281
|
if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
|
|
4011
|
-
const root =
|
|
4282
|
+
const root = path10.resolve(dir);
|
|
4012
4283
|
assertTree(root);
|
|
4013
4284
|
if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
|
|
4014
4285
|
if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {
|
|
@@ -4024,7 +4295,8 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
|
4024
4295
|
await withClient(conn, (client, serverId) => wholeServerPush(client, root, config, target, flags, { conn, serverId, envFile }), { envFile, quiet });
|
|
4025
4296
|
return;
|
|
4026
4297
|
}
|
|
4027
|
-
const
|
|
4298
|
+
const keysOnly = flags.configMapKey !== void 0 && !flags.channel && !flags.library && !flags.globalScripts;
|
|
4299
|
+
const scope = keysOnly ? { channels: [], libraries: [] } : { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
|
|
4028
4300
|
await withClient(conn, (client, serverId) => scopedPush(client, root, config, scope, target, flags, { conn, serverId, envFile }), { envFile, quiet });
|
|
4029
4301
|
}
|
|
4030
4302
|
);
|
|
@@ -4036,10 +4308,10 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
4036
4308
|
const file = await withClient(conn, async (client) => {
|
|
4037
4309
|
const text = await client.getServerConfigurationXml();
|
|
4038
4310
|
if (!flags.out) return saveServerBackup(client, text, conn, flags);
|
|
4039
|
-
const out =
|
|
4311
|
+
const out = path10.resolve(flags.out);
|
|
4040
4312
|
parseBackup(text, "the server configuration");
|
|
4041
|
-
if (
|
|
4042
|
-
await
|
|
4313
|
+
if (existsSync9(out)) fail(`${out} already exists; choose another name`);
|
|
4314
|
+
await mkdir7(path10.dirname(out), { recursive: true });
|
|
4043
4315
|
await writePrivate(out, text);
|
|
4044
4316
|
if (gitWouldCommit(out)) {
|
|
4045
4317
|
process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
|
|
@@ -4052,14 +4324,14 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
4052
4324
|
});
|
|
4053
4325
|
async function chooseBackup(dir, file, serverId, target) {
|
|
4054
4326
|
if (file) {
|
|
4055
|
-
const chosen =
|
|
4056
|
-
if (!
|
|
4327
|
+
const chosen = path10.resolve(file);
|
|
4328
|
+
if (!existsSync9(chosen)) fail(`${chosen} does not exist`);
|
|
4057
4329
|
return chosen;
|
|
4058
4330
|
}
|
|
4059
4331
|
const mine = await backupsOf(dir, serverId);
|
|
4060
4332
|
if (mine.length === 0) {
|
|
4061
4333
|
const others = (await originsIn(dir)).map((o) => o.host);
|
|
4062
|
-
const legacy =
|
|
4334
|
+
const legacy = path10.resolve(LEGACY_BACKUP_DIR);
|
|
4063
4335
|
const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
|
|
4064
4336
|
fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}` + (inLegacy ? `; ${legacy} has backups of this server (the default before 0.3.0-rc.3): pass --backup-dir ${shellArgument(legacy)}` : ""));
|
|
4065
4337
|
}
|
|
@@ -4083,7 +4355,7 @@ async function restoreWithBrokenExport(client, serverId, file, flags, target) {
|
|
|
4083
4355
|
if (unsafe) fail(`${chosen} holds ${unsafe}`);
|
|
4084
4356
|
const origin = await originOf(dir, chosen);
|
|
4085
4357
|
if (!origin && !flags.force) {
|
|
4086
|
-
fail(`${chosen} is not in ${
|
|
4358
|
+
fail(`${chosen} is not in ${path10.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
|
|
4087
4359
|
}
|
|
4088
4360
|
if (origin && origin.serverId !== serverId && !flags.force) {
|
|
4089
4361
|
fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
|
|
@@ -4146,7 +4418,7 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
4146
4418
|
if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
|
|
4147
4419
|
fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
|
|
4148
4420
|
}
|
|
4149
|
-
process.stderr.write(`warning: ${chosen} is not in ${
|
|
4421
|
+
process.stderr.write(`warning: ${chosen} is not in ${path10.join(dir, MANIFEST)}, so which server it came from cannot be checked
|
|
4150
4422
|
`);
|
|
4151
4423
|
}
|
|
4152
4424
|
const [bv, sv] = [backup["@_version"], current["@_version"]];
|
|
@@ -4205,7 +4477,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
4205
4477
|
})
|
|
4206
4478
|
))).action(async (dir, flags) => {
|
|
4207
4479
|
errorExitCode = 2;
|
|
4208
|
-
const root =
|
|
4480
|
+
const root = path10.resolve(dir);
|
|
4209
4481
|
assertTree(root);
|
|
4210
4482
|
const conn = await selectConnection(root, flags);
|
|
4211
4483
|
const envFile = await envFileFor(root, flags, conn);
|
|
@@ -4217,10 +4489,13 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
4217
4489
|
return { fetched: await client.getServerConfiguration(), serverId: serverId2 };
|
|
4218
4490
|
}, { envFile, quiet: flags.json });
|
|
4219
4491
|
const tree = await engine.implode({ root });
|
|
4220
|
-
const
|
|
4492
|
+
const env = await loadEnv(envFile);
|
|
4493
|
+
const unsetTreeOnly = assertEnvComplete(tree, fetched, env, envFile, conn);
|
|
4494
|
+
const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, env);
|
|
4221
4495
|
const messages = [
|
|
4222
4496
|
...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
|
|
4223
4497
|
...notes,
|
|
4498
|
+
...unsetTreeOnly.length > 0 ? [`no value yet for ${unsetTreeOnly.join(", ")}, used only by resources the server doesn't have`] : [],
|
|
4224
4499
|
...await xmlProblems(root, tree)
|
|
4225
4500
|
];
|
|
4226
4501
|
const allow = await readAllow(root);
|
|
@@ -4228,23 +4503,23 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
4228
4503
|
if (staleRevisions.length > 0) {
|
|
4229
4504
|
messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline, or adopt it when the content already matches`);
|
|
4230
4505
|
}
|
|
4231
|
-
const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
|
|
4232
|
-
const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
|
|
4506
|
+
const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(tree)))), { mode: "redact", allow });
|
|
4507
|
+
const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(templatedRemote)))), { mode: "redact", allow });
|
|
4233
4508
|
if (treeView.findings.length > 0) {
|
|
4234
4509
|
messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);
|
|
4235
4510
|
}
|
|
4236
4511
|
if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
|
|
4237
4512
|
if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
|
|
4238
4513
|
`);
|
|
4239
|
-
const tmp = await mkdtemp(
|
|
4514
|
+
const tmp = await mkdtemp(path10.join(tmpdir(), "channelvault-diff-"));
|
|
4240
4515
|
try {
|
|
4241
|
-
await engine.explode(treeView.config, { root:
|
|
4242
|
-
await engine.explode(serverView.config, { root:
|
|
4243
|
-
await
|
|
4516
|
+
await engine.explode(treeView.config, { root: path10.join(tmp, "tree") });
|
|
4517
|
+
await engine.explode(serverView.config, { root: path10.join(tmp, "server") });
|
|
4518
|
+
await mkdir7(path10.join(tmp, ".empty"));
|
|
4244
4519
|
const chunks = [];
|
|
4245
4520
|
for (const d of MANAGED_DIRS) {
|
|
4246
|
-
const local =
|
|
4247
|
-
const server =
|
|
4521
|
+
const local = existsSync9(path10.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
|
|
4522
|
+
const server = existsSync9(path10.join(tmp, "server", d)) ? `server/${d}` : ".empty";
|
|
4248
4523
|
if (local === ".empty" && server === ".empty") continue;
|
|
4249
4524
|
const result = spawnSync2(
|
|
4250
4525
|
"git",
|
|
@@ -4266,7 +4541,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
4266
4541
|
const clean = out === "" && secretDrift.length === 0;
|
|
4267
4542
|
if (!clean) process.exitCode = 1;
|
|
4268
4543
|
if (flags.json) {
|
|
4269
|
-
const files = await changedFiles(
|
|
4544
|
+
const files = await changedFiles(path10.join(tmp, "tree"), path10.join(tmp, "server"));
|
|
4270
4545
|
writeJson2({ clean, serverId, connection: connectionJson(conn, serverId, envFile), files, secretDrift, staleRevisions, notes: messages, patch: out });
|
|
4271
4546
|
} else if (clean) {
|
|
4272
4547
|
process.stdout.write("no differences \u2014 working tree matches the server.\n");
|
|
@@ -4287,7 +4562,7 @@ async function changedFiles(treeDir, serverDir) {
|
|
|
4287
4562
|
const files = [];
|
|
4288
4563
|
for (const p of local) {
|
|
4289
4564
|
if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
|
|
4290
|
-
else if (await readFile6(
|
|
4565
|
+
else if (await readFile6(path10.join(treeDir, p), "utf8") !== await readFile6(path10.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
|
|
4291
4566
|
}
|
|
4292
4567
|
const localSet = new Set(local);
|
|
4293
4568
|
for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
|
|
@@ -4296,7 +4571,7 @@ async function changedFiles(treeDir, serverDir) {
|
|
|
4296
4571
|
addJsonFlag(addEnvFlag(
|
|
4297
4572
|
program.command("status").description("Summarize a working tree, and say which connection profile live commands would use").argument("<dir>", "working-tree directory")
|
|
4298
4573
|
)).action(async (dir, flags) => {
|
|
4299
|
-
const root =
|
|
4574
|
+
const root = path10.resolve(dir);
|
|
4300
4575
|
assertTree(root);
|
|
4301
4576
|
const config = await engine.implode({ root });
|
|
4302
4577
|
const s = summarize(config);
|
|
@@ -4385,11 +4660,25 @@ async function loginCheck(conn) {
|
|
|
4385
4660
|
return withClient(conn, async (_client, serverId) => serverId, { quiet: true });
|
|
4386
4661
|
}
|
|
4387
4662
|
function existingProfile(profiles, name) {
|
|
4388
|
-
const profile = profiles[name];
|
|
4663
|
+
const profile = Object.hasOwn(profiles, name) ? profiles[name] : void 0;
|
|
4389
4664
|
if (!profile) fail(`no profile named ${name} (${Object.keys(profiles).join(", ") || "none saved"})`, "profile-unknown");
|
|
4390
4665
|
return profile;
|
|
4391
4666
|
}
|
|
4392
|
-
|
|
4667
|
+
function assertProfileValid(profiles, name, profile) {
|
|
4668
|
+
const problems = profileProblems({ ...profiles, [name]: profile });
|
|
4669
|
+
if (profile.dotenv && existsSync9(profile.dotenv) && statSync(profile.dotenv).isDirectory()) {
|
|
4670
|
+
problems.push(`profile ${name}: dotenv ${profile.dotenv} is a folder; name the env file inside it`);
|
|
4671
|
+
} else if (profile.dotenv && gitWouldCommit(profile.dotenv)) {
|
|
4672
|
+
problems.push(`profile ${name}: git does not ignore ${profile.dotenv}, which will hold secret values; add it to .gitignore, or choose a file outside every repository`);
|
|
4673
|
+
}
|
|
4674
|
+
if (problems.length > 0) fail(problems.join("\n"), "profile-invalid");
|
|
4675
|
+
}
|
|
4676
|
+
async function profilesUnchanged(name, expected) {
|
|
4677
|
+
const latest = await loadProfiles();
|
|
4678
|
+
if (!isDeepStrictEqual(Object.hasOwn(latest, name) ? latest[name] : void 0, expected)) fail(`profile ${name} was changed meanwhile; nothing was saved`, "profile-changed");
|
|
4679
|
+
return latest;
|
|
4680
|
+
}
|
|
4681
|
+
var profileCommand = program.command("profile").description(`Manage connection profiles (${path10.join("~", ".channelvault", "profiles.json")}; passwords in its credentials file)`);
|
|
4393
4682
|
addJsonFlag(profileCommand.command("list").description("List the saved profiles (never their passwords)")).action(async (flags) => {
|
|
4394
4683
|
const profiles = await loadProfiles();
|
|
4395
4684
|
const credentials = await readCredentials();
|
|
@@ -4422,19 +4711,20 @@ profileCommand.command("add").description("Add a profile at a terminal: confirm
|
|
|
4422
4711
|
needTerminal("profile add");
|
|
4423
4712
|
if (!PROFILE_NAME.test(name)) fail(`profile names are letters, digits, '.', '_' and '-', starting with a letter or digit: ${name}`, "profile-invalid");
|
|
4424
4713
|
const profiles = await loadProfiles();
|
|
4425
|
-
if (profiles
|
|
4714
|
+
if (Object.hasOwn(profiles, name)) {
|
|
4715
|
+
fail(`profile ${name} already exists; change it with \`channelvault profile set ${name}\` (env file, user, port) or \`channelvault profile set-password ${name}\`, or remove it with \`channelvault profile remove ${name}\``, "profile-exists");
|
|
4716
|
+
}
|
|
4426
4717
|
const port = Number(flags.port);
|
|
4427
4718
|
const profile = { host: flags.host, port, user: flags.user };
|
|
4428
4719
|
if (flags.https === false) profile.https = false;
|
|
4429
4720
|
if (flags.insecure) profile.insecure = true;
|
|
4430
|
-
if (flags.dotenv) profile.dotenv =
|
|
4721
|
+
if (flags.dotenv) profile.dotenv = path10.resolve(flags.dotenv);
|
|
4431
4722
|
if (flags.tlsFingerprint !== void 0) {
|
|
4432
4723
|
const pin = normalizeFingerprint(flags.tlsFingerprint);
|
|
4433
4724
|
if (!pin) fail("--tls-fingerprint must be a SHA-256 certificate fingerprint: 64 hex digits, colons allowed", "bad-fingerprint");
|
|
4434
4725
|
profile.tlsFingerprint = pin;
|
|
4435
4726
|
}
|
|
4436
|
-
|
|
4437
|
-
if (problems.length > 0) fail(problems.join("\n"), "profile-invalid");
|
|
4727
|
+
assertProfileValid(profiles, name, profile);
|
|
4438
4728
|
const conn = connectionOfProfile(name, profile, "");
|
|
4439
4729
|
process.stdout.write(`Add profile ${name}: ${urlOf(conn)} as ${profile.user}
|
|
4440
4730
|
`);
|
|
@@ -4455,7 +4745,7 @@ channelvault will accept only this certificate from this server. Compare it with
|
|
|
4455
4745
|
const password = await askPassword(`Password for ${profile.user}: `);
|
|
4456
4746
|
profile.serverId = await loginCheck(connectionOfProfile(name, profile, password));
|
|
4457
4747
|
const latest = await loadProfiles();
|
|
4458
|
-
if (latest
|
|
4748
|
+
if (Object.hasOwn(latest, name)) fail(`profile ${name} was added meanwhile; nothing was saved`, "profile-exists");
|
|
4459
4749
|
await saveProfiles({ ...latest, [name]: profile });
|
|
4460
4750
|
await setCredential(name, password);
|
|
4461
4751
|
process.stdout.write(`added profile ${name} (installation ${profile.serverId}); password stored in ${credentialsFile()}
|
|
@@ -4472,6 +4762,73 @@ profileCommand.command("set-password").description("Change a profile's stored pa
|
|
|
4472
4762
|
process.stdout.write(`stored the password for profile ${name}
|
|
4473
4763
|
`);
|
|
4474
4764
|
});
|
|
4765
|
+
profileCommand.command("set").description("Change a profile's env file, user or port at a terminal; never its installation or certificate pin").argument("<name>", "profile name").option("--dotenv <path>", "env file for this server's trees, used when a tree has no .env of its own").option("--user <user>", "username; asks for that user's password and logs in before saving").option("--port <port>", "Mirth server port; logs in before saving, so it must reach the same installation and certificate").action(async (name, flags) => {
|
|
4766
|
+
needTerminal("profile set");
|
|
4767
|
+
const profiles = await loadProfiles();
|
|
4768
|
+
const profile = existingProfile(profiles, name);
|
|
4769
|
+
if (flags.dotenv === void 0 && flags.user === void 0 && flags.port === void 0) {
|
|
4770
|
+
fail("nothing to change: pass --dotenv, --user or --port", "profile-invalid");
|
|
4771
|
+
}
|
|
4772
|
+
const updated = { ...profile };
|
|
4773
|
+
if (flags.dotenv !== void 0) updated.dotenv = path10.resolve(flags.dotenv);
|
|
4774
|
+
if (flags.user !== void 0) updated.user = flags.user;
|
|
4775
|
+
if (flags.port !== void 0) updated.port = Number(flags.port);
|
|
4776
|
+
assertProfileValid(profiles, name, updated);
|
|
4777
|
+
const changes = ["dotenv", "user", "port"].filter((field) => updated[field] !== profile[field]).map((field) => `${field} ${profile[field] ?? "(none)"} -> ${updated[field]}`);
|
|
4778
|
+
if (changes.length === 0) {
|
|
4779
|
+
process.stdout.write(`profile ${name} already has those settings
|
|
4780
|
+
`);
|
|
4781
|
+
return;
|
|
4782
|
+
}
|
|
4783
|
+
process.stdout.write(`Profile ${name}: ${changes.join(", ")}
|
|
4784
|
+
`);
|
|
4785
|
+
const loginNeeded = updated.user !== profile.user || updated.port !== profile.port;
|
|
4786
|
+
if (loginNeeded && !profile.serverId) {
|
|
4787
|
+
fail(`profile ${name} has no recorded installation to check a new user or port against; remove it and add it again`, "profile-invalid");
|
|
4788
|
+
}
|
|
4789
|
+
const verifiesServer = updated.https !== false && !updated.insecure;
|
|
4790
|
+
let newPassword;
|
|
4791
|
+
if (updated.user !== profile.user || updated.port !== profile.port && !verifiesServer) {
|
|
4792
|
+
newPassword = await askPassword(`Password for ${updated.user}: `);
|
|
4793
|
+
await loginCheck(connectionOfProfile(name, updated, newPassword));
|
|
4794
|
+
} else if (updated.port !== profile.port) {
|
|
4795
|
+
const password = (await readCredentials())[name];
|
|
4796
|
+
if (password === void 0) fail(`profile ${name} has no password yet; run \`channelvault profile set-password ${name}\` first`, "no-password");
|
|
4797
|
+
await loginCheck(connectionOfProfile(name, updated, password));
|
|
4798
|
+
}
|
|
4799
|
+
const latest = await profilesUnchanged(name, profile);
|
|
4800
|
+
assertProfileValid(latest, name, updated);
|
|
4801
|
+
await saveProfiles({ ...latest, [name]: updated });
|
|
4802
|
+
if (newPassword !== void 0) {
|
|
4803
|
+
try {
|
|
4804
|
+
await setCredential(name, newPassword);
|
|
4805
|
+
} catch (err) {
|
|
4806
|
+
await saveProfiles({ ...latest, [name]: profile });
|
|
4807
|
+
throw err;
|
|
4808
|
+
}
|
|
4809
|
+
}
|
|
4810
|
+
process.stdout.write(`updated profile ${name}: ${changes.join(", ")}
|
|
4811
|
+
` + (flags.dotenv !== void 0 ? `values already in another env file are not moved; move them to ${updated.dotenv} yourself
|
|
4812
|
+
` : ""));
|
|
4813
|
+
});
|
|
4814
|
+
profileCommand.command("remove").description("Remove a profile and its stored password, at a terminal, after confirming").argument("<name>", "profile name").action(async (name) => {
|
|
4815
|
+
needTerminal("profile remove");
|
|
4816
|
+
const profile = existingProfile(await loadProfiles(), name);
|
|
4817
|
+
process.stdout.write(`Profile ${name}: ${urlOf(connectionOfProfile(name, profile, ""))} as ${profile.user}, installation ${profile.serverId ?? "(not recorded)"}
|
|
4818
|
+
` + (profile.dotenv ? `Its env file ${profile.dotenv} is kept.
|
|
4819
|
+
` : ""));
|
|
4820
|
+
if (!await confirm(`Remove profile ${name} and its stored password?`)) {
|
|
4821
|
+
process.stdout.write("aborted.\n");
|
|
4822
|
+
return;
|
|
4823
|
+
}
|
|
4824
|
+
const latest = await profilesUnchanged(name, profile);
|
|
4825
|
+
const rest = Object.fromEntries(Object.entries(latest).filter(([n]) => n !== name));
|
|
4826
|
+
const hadPassword = Object.hasOwn(await readCredentials(), name);
|
|
4827
|
+
await removeCredential(name);
|
|
4828
|
+
await saveProfiles(rest);
|
|
4829
|
+
process.stdout.write(`removed profile ${name}${hadPassword ? ` and its password from ${credentialsFile()}` : ""}
|
|
4830
|
+
`);
|
|
4831
|
+
});
|
|
4475
4832
|
addJsonFlag(profileCommand.command("check").description("Log in with each profile (or the one named) and verify its certificate and installation").argument("[name]", "profile name")).action(async (name, flags) => {
|
|
4476
4833
|
const profiles = await loadProfiles();
|
|
4477
4834
|
const credentials = await readCredentials();
|
|
@@ -4534,14 +4891,14 @@ var locked = [];
|
|
|
4534
4891
|
async function lockAlso(file) {
|
|
4535
4892
|
const key = await canonical(file);
|
|
4536
4893
|
if (locked.some((l) => samePath(l, key))) return;
|
|
4537
|
-
unlocks.push(await lockTree(
|
|
4894
|
+
unlocks.push(await lockTree(path10.resolve(file)));
|
|
4538
4895
|
locked.push(key);
|
|
4539
4896
|
}
|
|
4540
4897
|
program.hook("preAction", async (_program, command) => {
|
|
4541
4898
|
const name = command.name();
|
|
4542
4899
|
if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name) || command.parent !== program) return;
|
|
4543
4900
|
if (name === "diff") errorExitCode = 2;
|
|
4544
|
-
const root =
|
|
4901
|
+
const root = path10.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
|
|
4545
4902
|
unlocks.push(await lockTree(root));
|
|
4546
4903
|
const pending = await pendingEnvFile(root);
|
|
4547
4904
|
if (pending === null) return;
|