@ubercode/channelvault 0.3.0-rc.3 → 0.3.0-rc.5

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/dist/cli.js CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { spawnSync } from "child_process";
5
- import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readFile as readFile6, realpath as realpath4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
- import { existsSync as existsSync6 } from "fs";
4
+ import { spawnSync as spawnSync2 } from "child_process";
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 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path8 from "path";
9
+ import * as path10 from "path";
10
10
  import { createInterface } from "readline/promises";
11
+ import { Writable } from "stream";
11
12
  import { Command, CommanderError } from "commander";
12
13
 
13
14
  // src/explode/index.ts
@@ -939,7 +940,9 @@ var XmlConfigAdapter = class {
939
940
 
940
941
  // src/client/index.ts
941
942
  import { CookieJar } from "tough-cookie";
942
- import { Agent } from "undici";
943
+ import { isIP } from "net";
944
+ import { connect as tlsConnect } from "tls";
945
+ import { Agent, buildConnector } from "undici";
943
946
 
944
947
  // src/secrets/detect.ts
945
948
  import { createHash } from "crypto";
@@ -955,6 +958,29 @@ function hasPlaceholder(value) {
955
958
  PLACEHOLDER.lastIndex = 0;
956
959
  return PLACEHOLDER.test(value);
957
960
  }
961
+ function placeholderNames(config) {
962
+ const names = /* @__PURE__ */ new Set();
963
+ mapLeaves(config, (value) => {
964
+ for (const m of value.matchAll(PLACEHOLDER)) names.add(m[1]);
965
+ return value;
966
+ });
967
+ return names;
968
+ }
969
+ function placeholderUse(tree, server) {
970
+ const onServer = /* @__PURE__ */ new Set();
971
+ mapLeaves(server, (value, leaf) => {
972
+ onServer.add(leaf.location);
973
+ return value;
974
+ });
975
+ const compared = /* @__PURE__ */ new Set();
976
+ const treeOnly = /* @__PURE__ */ new Set();
977
+ mapLeaves(tree, (value, leaf) => {
978
+ for (const m of value.matchAll(PLACEHOLDER)) (onServer.has(leaf.location) ? compared : treeOnly).add(m[1]);
979
+ return value;
980
+ });
981
+ for (const name of compared) treeOnly.delete(name);
982
+ return { compared, treeOnly };
983
+ }
958
984
  function fill(value, env, missing) {
959
985
  return value.replace(PLACEHOLDER, (whole, name) => {
960
986
  const v = env[name];
@@ -1000,12 +1026,12 @@ function configMapKeyOf(entry) {
1000
1026
  return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
1001
1027
  }
1002
1028
  function mapLeaves(config, visit) {
1003
- const walk = (node, key, path9, labels, section, cmKey) => {
1029
+ const walk = (node, key, path11, labels, section, cmKey) => {
1004
1030
  if (typeof node === "string") {
1005
- return visit(node, { location: path9.join("/"), key, labels, section, configMapKey: cmKey });
1031
+ return visit(node, { location: path11.join("/"), key, labels, section, configMapKey: cmKey });
1006
1032
  }
1007
1033
  if (Array.isArray(node)) {
1008
- return node.map((el, i) => walk(el, key, [...path9.slice(0, -1), `${path9[path9.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1034
+ return node.map((el, i) => walk(el, key, [...path11.slice(0, -1), `${path11[path11.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1009
1035
  }
1010
1036
  if (node && typeof node === "object") {
1011
1037
  const name = node["name"];
@@ -1013,7 +1039,7 @@ function mapLeaves(config, visit) {
1013
1039
  const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
1014
1040
  const out = {};
1015
1041
  for (const [k, v] of Object.entries(node)) {
1016
- out[k] = walk(v, k, [...path9, k], inner, section || k, mapKey);
1042
+ out[k] = walk(v, k, [...path11, k], inner, section || k, mapKey);
1017
1043
  }
1018
1044
  return out;
1019
1045
  }
@@ -1411,6 +1437,38 @@ function connectionError(url, err) {
1411
1437
  error.code = code;
1412
1438
  return error;
1413
1439
  }
1440
+ function fingerprintOf(socket) {
1441
+ return (socket.getPeerCertificate().fingerprint256 ?? "").replace(/:/g, "").toLowerCase();
1442
+ }
1443
+ function pinnedConnector(pin) {
1444
+ const base = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0 });
1445
+ return (options, callback) => {
1446
+ base(options, (err, socket) => {
1447
+ if (err) return callback(err, null);
1448
+ const presented = fingerprintOf(socket);
1449
+ if (presented === pin) return callback(null, socket);
1450
+ socket.destroy();
1451
+ const mismatch = new Error(
1452
+ `the server presented certificate SHA-256 ${presented || "(none)"}, but the pinned fingerprint is ${pin}; nothing was sent`
1453
+ );
1454
+ mismatch.code = "TLS_PIN_MISMATCH";
1455
+ mismatch.presented = presented;
1456
+ callback(mismatch, null);
1457
+ });
1458
+ };
1459
+ }
1460
+ function presentedFingerprint(host, port, timeoutMs = 1e4) {
1461
+ return new Promise((resolve6, reject) => {
1462
+ const socket = tlsConnect({ host, port, rejectUnauthorized: false, ...isIP(host) ? {} : { servername: host } });
1463
+ socket.setTimeout(timeoutMs, () => socket.destroy(new Error(`no TLS handshake from ${host}:${port} within ${timeoutMs / 1e3} s`)));
1464
+ socket.once("secureConnect", () => {
1465
+ const fp = fingerprintOf(socket);
1466
+ socket.end();
1467
+ resolve6(fp);
1468
+ });
1469
+ socket.once("error", reject);
1470
+ });
1471
+ }
1414
1472
  function redirectTarget(url, response) {
1415
1473
  const location = response.headers.get("location");
1416
1474
  if (!location) return "";
@@ -1442,7 +1500,7 @@ var MirthClientImpl = class {
1442
1500
  const protocol = config.https !== false ? "https" : "http";
1443
1501
  this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;
1444
1502
  this.cookieJar = new CookieJar();
1445
- this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
1503
+ this.dispatcher = new Agent(config.tlsFingerprint ? { connect: pinnedConnector(config.tlsFingerprint) } : config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
1446
1504
  }
1447
1505
  isAuthenticated() {
1448
1506
  return this.authenticated;
@@ -1608,6 +1666,10 @@ var MirthClientImpl = class {
1608
1666
  async putCodeTemplateLibraries(libraries) {
1609
1667
  await this.sendJson("PUT", "/codeTemplateLibraries", { list: { codeTemplateLibrary: libraries } }, { override: true });
1610
1668
  }
1669
+ /** PUT /server/configurationMap: replaces the whole map. */
1670
+ async putConfigurationMap(map) {
1671
+ await this.sendJson("PUT", "/server/configurationMap", { map });
1672
+ }
1611
1673
  async putGlobalScripts(globalScripts) {
1612
1674
  await this.sendJson("PUT", "/server/globalScripts", { map: globalScripts });
1613
1675
  }
@@ -1622,15 +1684,15 @@ var MirthClientImpl = class {
1622
1684
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1623
1685
  }
1624
1686
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1625
- async sendJson(method, path9, body, query) {
1626
- const response = await this.request(method, path9, {
1687
+ async sendJson(method, path11, body, query) {
1688
+ const response = await this.request(method, path11, {
1627
1689
  query,
1628
1690
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1629
1691
  body: JSON.stringify(body)
1630
1692
  });
1631
1693
  const text = await response.text();
1632
1694
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1633
- throw new Error(`${method} ${path9}: the server refused the update`);
1695
+ throw new Error(`${method} ${path11}: the server refused the update`);
1634
1696
  }
1635
1697
  }
1636
1698
  // --- internal transport ---------------------------------------------------
@@ -1639,11 +1701,11 @@ var MirthClientImpl = class {
1639
1701
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1640
1702
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1641
1703
  */
1642
- async request(method, path9, options = {}, isRetry = false) {
1704
+ async request(method, path11, options = {}, isRetry = false) {
1643
1705
  if (!this.authenticated) {
1644
1706
  await this.login();
1645
1707
  }
1646
- const url = this.buildUrl(path9, options.query);
1708
+ const url = this.buildUrl(path11, options.query);
1647
1709
  const headers = {
1648
1710
  "X-Requested-With": "XMLHttpRequest",
1649
1711
  ...options.headers
@@ -1657,7 +1719,7 @@ var MirthClientImpl = class {
1657
1719
  if (response.status === 401 && this.authenticated && !isRetry) {
1658
1720
  this.authenticated = false;
1659
1721
  await this.login();
1660
- return this.request(method, path9, options, true);
1722
+ return this.request(method, path11, options, true);
1661
1723
  }
1662
1724
  if (!response.ok) {
1663
1725
  throw await this.toApiError(response);
@@ -1688,8 +1750,8 @@ var MirthClientImpl = class {
1688
1750
  return response;
1689
1751
  }
1690
1752
  /** Build an absolute URL with an optional query string. */
1691
- buildUrl(path9, query) {
1692
- const url = `${this.baseUrl}${path9}`;
1753
+ buildUrl(path11, query) {
1754
+ const url = `${this.baseUrl}${path11}`;
1693
1755
  if (!query || Object.keys(query).length === 0) {
1694
1756
  return url;
1695
1757
  }
@@ -1756,173 +1818,858 @@ function createMirthClient(config) {
1756
1818
  return new MirthClientImpl(config);
1757
1819
  }
1758
1820
 
1759
- // src/push/index.ts
1760
- import { createHash as createHash2 } from "crypto";
1761
- var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1762
- function list(v) {
1763
- if (v == null || v === "") return [];
1764
- return (Array.isArray(v) ? v : [v]).filter(isObj);
1821
+ // src/profiles.ts
1822
+ import { spawnSync } from "child_process";
1823
+ import { existsSync as existsSync5 } from "fs";
1824
+ import { mkdir as mkdir4 } from "fs/promises";
1825
+ import { homedir } from "os";
1826
+ import * as path5 from "path";
1827
+
1828
+ // src/backup/index.ts
1829
+ import { randomBytes } from "crypto";
1830
+ import { existsSync as existsSync2, realpathSync } from "fs";
1831
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rename, rm, writeFile as writeFile2 } from "fs/promises";
1832
+ import * as path2 from "path";
1833
+ function defaultBackupDir() {
1834
+ return path2.join(configDir(), "backups");
1765
1835
  }
1766
- function channelsOf(c) {
1767
- return isObj(c["channels"]) ? list(c["channels"]["channel"]) : [];
1836
+ var LEGACY_BACKUP_DIR = ".backup";
1837
+ var DEFAULT_KEEP = 10;
1838
+ var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
1839
+ function serverSlug(name) {
1840
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1768
1841
  }
1769
- function librariesOf(c) {
1770
- return isObj(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
1842
+ function backupName(config, fallback) {
1843
+ return configuredName(config) || serverSlug(fallback) || "mirth";
1771
1844
  }
1772
- function templatesOf2(library) {
1773
- return isObj(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
1845
+ function configuredName(config) {
1846
+ const settings = config["serverSettings"];
1847
+ const field = (key) => {
1848
+ const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
1849
+ return typeof v === "string" ? serverSlug(v) : "";
1850
+ };
1851
+ return field("serverName") || field("environmentName");
1774
1852
  }
1775
- var idOf = (o) => String(o["id"]);
1776
- var nameOf = (o) => String(o["name"] ?? o["id"]);
1777
- var revisionOf = (o) => Number(o["revision"] ?? 0);
1778
- function normalizeEol(s) {
1779
- return s.replace(/\r\n?/g, "\n");
1853
+ function stamp(date) {
1854
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
1780
1855
  }
1781
- function normalizeEolDeep(value) {
1782
- if (typeof value === "string") return normalizeEol(value);
1783
- if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
1784
- if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
1785
- return value;
1856
+ async function listBackups(dir) {
1857
+ if (!existsSync2(dir)) return [];
1858
+ const out = [];
1859
+ for (const name of await readdir2(dir)) {
1860
+ const m = FILE_NAME.exec(name);
1861
+ if (m) out.push({ file: path2.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
1862
+ }
1863
+ return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
1786
1864
  }
1787
- function same(a, b) {
1788
- if (a === b) return true;
1789
- if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
1790
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
1791
- if (isObj(a) && isObj(b)) {
1792
- const ka = Object.keys(a);
1793
- return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
1865
+ var MANIFEST = "channelvault-backups.json";
1866
+ async function readManifest(dir) {
1867
+ const file = path2.join(dir, MANIFEST);
1868
+ if (!existsSync2(file)) return {};
1869
+ try {
1870
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
1871
+ return parsed.files ?? {};
1872
+ } catch (err) {
1873
+ throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
1794
1874
  }
1795
- return false;
1796
1875
  }
1797
- var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
1798
- function withSortedContexts(o) {
1799
- const set = o["contextSet"];
1800
- const delegate = isObj(set) ? set["delegate"] : void 0;
1801
- const types = isObj(delegate) ? delegate["contextType"] : void 0;
1802
- if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
1803
- const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
1804
- return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
1876
+ async function writeManifest(dir, files) {
1877
+ const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync2(path2.join(dir, name))));
1878
+ await writePrivate(path2.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
1879
+ `);
1805
1880
  }
1806
- function stripVolatile(o) {
1807
- const out = withSortedContexts({ ...o });
1808
- delete out["revision"];
1809
- delete out["lastModified"];
1810
- const exportData = out["exportData"];
1811
- if (isObj(exportData)) {
1812
- const metadata = isObj(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
1813
- if (metadata) {
1814
- delete metadata["lastModified"];
1815
- delete metadata["userId"];
1816
- }
1817
- out["exportData"] = metadata ? { metadata } : {};
1881
+ async function backupsOf(dir, serverId) {
1882
+ const manifest = await readManifest(dir);
1883
+ return (await listBackups(dir)).filter((b) => manifest[path2.basename(b.file)]?.serverId === serverId);
1884
+ }
1885
+ async function originOf(dir, file) {
1886
+ if (!existsSync2(dir) || !sameFile(path2.dirname(file), dir)) return null;
1887
+ return (await readManifest(dir))[path2.basename(file)] ?? null;
1888
+ }
1889
+ async function originsIn(dir) {
1890
+ if (!existsSync2(dir)) return [];
1891
+ const seen = /* @__PURE__ */ new Map();
1892
+ for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);
1893
+ return [...seen.values()];
1894
+ }
1895
+ async function saveBackup(dir, name, xml2, opts) {
1896
+ await ensureBackupDir(dir);
1897
+ const manifest = await readManifest(dir);
1898
+ const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
1899
+ let file = path2.join(dir, `${base}.xml`);
1900
+ for (let n = 2; existsSync2(file); n += 1) file = path2.join(dir, `${base}-${n}.xml`);
1901
+ await writePrivate(file, xml2);
1902
+ manifest[path2.basename(file)] = opts.origin;
1903
+ await writeManifest(dir, manifest);
1904
+ const mine = (await listBackups(dir)).filter((b) => manifest[path2.basename(b.file)]?.serverId === opts.origin.serverId);
1905
+ for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
1906
+ if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
1907
+ await rm(old.file);
1818
1908
  }
1819
- return out;
1909
+ await writeManifest(dir, manifest);
1910
+ return file;
1820
1911
  }
1821
- var groupsOf = (c) => isObj(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
1822
- function withoutVolatile(c) {
1823
- const out = structuredClone(c);
1824
- const strip = (o) => {
1825
- delete o["revision"];
1826
- delete o["lastModified"];
1827
- const exportData = o["exportData"];
1828
- const md = isObj(exportData) ? exportData["metadata"] : void 0;
1829
- if (isObj(md)) {
1830
- delete md["lastModified"];
1831
- delete md["userId"];
1832
- }
1833
- if (isObj(exportData)) {
1834
- for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
1835
- }
1836
- if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
1912
+ function sameFile(a, b) {
1913
+ const real = (p) => {
1914
+ const resolved = existsSync2(p) ? realpathSync.native(p) : path2.resolve(p);
1915
+ return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
1837
1916
  };
1838
- for (const ch of channelsOf(out)) strip(ch);
1839
- for (const lib of librariesOf(out)) {
1840
- strip(lib);
1841
- for (const t of templatesOf2(lib)) strip(t);
1917
+ return real(a) === real(b);
1918
+ }
1919
+ async function ensureBackupDir(dir) {
1920
+ if (existsSync2(dir)) return;
1921
+ await mkdir2(dir, { recursive: true, mode: 448 });
1922
+ await writeFile2(path2.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
1923
+ }
1924
+ async function writePrivate(file, text) {
1925
+ const temp = `${file}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
1926
+ try {
1927
+ await writeFile2(temp, text, { encoding: "utf8", mode: 384 });
1928
+ await rename(temp, file);
1929
+ } catch (err) {
1930
+ await rm(temp, { force: true });
1931
+ throw err;
1842
1932
  }
1843
- for (const g of groupsOf(out)) {
1844
- strip(g);
1845
- for (const member of isObj(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
1933
+ }
1934
+ function numericVersion(v) {
1935
+ const m = /^\d+(?:\.\d+)*/.exec(v.trim());
1936
+ return m ? m[0].split(".").map(Number) : null;
1937
+ }
1938
+ function compareVersions(a, b) {
1939
+ const pa = numericVersion(a);
1940
+ const pb = numericVersion(b);
1941
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
1942
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1943
+ if (d !== 0) return d;
1846
1944
  }
1847
- return out;
1945
+ return 0;
1848
1946
  }
1849
- function newerOnServer(tree, server) {
1850
- const out = [];
1851
- const compare = (kind, local, remote) => {
1852
- const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
1853
- for (const r of remote) {
1854
- const rev = mine.get(idOf(r));
1855
- if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
1856
- }
1857
- };
1858
- compare("channel", channelsOf(tree), channelsOf(server));
1859
- compare("library", librariesOf(tree), librariesOf(server));
1860
- compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
1861
- compare("channel group", groupsOf(tree), groupsOf(server));
1862
- return out;
1947
+
1948
+ // src/paths.ts
1949
+ import { existsSync as existsSync3, realpathSync as realpathSync2 } from "fs";
1950
+ import { lstat as lstat2, readlink, realpath as realpath2 } from "fs/promises";
1951
+ import * as path3 from "path";
1952
+ function samePath(a, b) {
1953
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
1863
1954
  }
1864
- function libraryShape(lib) {
1865
- const out = stripVolatile(lib);
1866
- out["codeTemplates"] = templatesOf2(lib).map(idOf);
1867
- return out;
1955
+ function isWithin(child, parent) {
1956
+ const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
1957
+ const rel = path3.relative(norm(parent), norm(child));
1958
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${path3.sep}`) && !path3.isAbsolute(rel);
1868
1959
  }
1869
- function withRetainedMembers(local, remote, localIds, deletedIds) {
1870
- const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
1871
- if (!retained.length) return local;
1872
- return { ...local, codeTemplates: {
1873
- ...isObj(local["codeTemplates"]) ? local["codeTemplates"] : {},
1874
- codeTemplate: [...templatesOf2(local), ...retained]
1875
- } };
1960
+ async function resolvedPath(p) {
1961
+ const abs = path3.resolve(p);
1962
+ let existing = abs;
1963
+ while (!existsSync3(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1964
+ return path3.join(await realpath2(existing), path3.relative(existing, abs));
1876
1965
  }
1877
- function hashGlobalScripts(c) {
1878
- return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
1966
+ function resolvedPathSync(p) {
1967
+ const abs = path3.resolve(p);
1968
+ let existing = abs;
1969
+ while (!existsSync3(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1970
+ return path3.join(realpathSync2.native(existing), path3.relative(existing, abs));
1879
1971
  }
1880
- function resourceIds(c) {
1881
- const libs = librariesOf(c);
1882
- const revs = (items) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));
1883
- return {
1884
- channels: revs(channelsOf(c)),
1885
- libraries: revs(libs),
1886
- codeTemplates: revs(libs.flatMap(templatesOf2)),
1887
- globalScripts: hashGlobalScripts(c)
1888
- };
1972
+ async function present(file) {
1973
+ return lstat2(file).then(() => true, (err) => {
1974
+ if (err.code === "ENOENT") return false;
1975
+ throw err;
1976
+ });
1889
1977
  }
1890
- function adoptTarget(local, target) {
1891
- const config = structuredClone(local);
1892
- const mine = resourceIds(local);
1893
- const theirs = resourceIds(target);
1894
- const intersect = (key) => Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));
1895
- const known = {
1896
- channels: intersect("channels"),
1897
- libraries: intersect("libraries"),
1898
- codeTemplates: intersect("codeTemplates"),
1899
- globalScripts: theirs.globalScripts
1900
- };
1901
- const rebase = (items, revisions) => {
1902
- for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
1903
- };
1904
- rebase(channelsOf(config), theirs.channels);
1905
- rebase(librariesOf(config), theirs.libraries);
1906
- rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
1907
- return { config, known };
1978
+ async function canonical(file, depth = 0) {
1979
+ if (depth > 64) throw new Error(`too many links in path: ${file}`);
1980
+ let existing = path3.resolve(file);
1981
+ while (!await present(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1982
+ const info = await lstat2(existing);
1983
+ const base = info.isSymbolicLink() ? await canonical(path3.resolve(path3.dirname(existing), await readlink(existing)), depth + 1) : await realpath2(existing);
1984
+ return path3.join(base, path3.relative(existing, path3.resolve(file)));
1908
1985
  }
1909
- function knownFrom(raw) {
1910
- if (!isObj(raw)) return void 0;
1911
- const r = raw;
1912
- const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
1913
- return {
1914
- channels: map(r["channels"]),
1915
- libraries: map(r["libraries"]),
1916
- codeTemplates: map(r["codeTemplates"]),
1917
- globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
1918
- };
1986
+
1987
+ // src/secrets/envfile.ts
1988
+ import { randomBytes as randomBytes2 } from "crypto";
1989
+ import { existsSync as existsSync4 } from "fs";
1990
+ import { appendFile, chmod, copyFile, mkdir as mkdir3, readFile as readFile4, readdir as readdir3, realpath as realpath3, rename as rename2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
1991
+ import * as path4 from "path";
1992
+ import { parse } from "dotenv";
1993
+ var BASE64_PREFIX = "cv-base64:";
1994
+ function parseEnv(text) {
1995
+ const out = parse(text);
1996
+ for (const [k, v] of Object.entries(out)) {
1997
+ if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
1998
+ }
1999
+ return out;
1919
2000
  }
1920
- function knownAfterPush(known, applied, touched, fresh) {
1921
- const now = resourceIds(fresh);
1922
- const next = {
1923
- channels: { ...known.channels },
1924
- libraries: { ...known.libraries },
1925
- codeTemplates: { ...known.codeTemplates },
2001
+ async function readEnvFile(file) {
2002
+ if (!existsSync4(file)) return {};
2003
+ return parseEnv(await readFile4(file, "utf8"));
2004
+ }
2005
+ function formatValue(value) {
2006
+ const candidates = [
2007
+ /^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
2008
+ value.includes("'") ? null : `'${value}'`,
2009
+ value.includes("`") ? null : `\`${value}\``,
2010
+ value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
2011
+ ];
2012
+ for (const c of candidates) {
2013
+ if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
2014
+ }
2015
+ return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
2016
+ }
2017
+ async function updateEnvFile(file, updates) {
2018
+ const names = Object.keys(updates);
2019
+ if (names.length === 0) return;
2020
+ const existing = existsSync4(file) ? await readFile4(file, "utf8") : "";
2021
+ const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
2022
+ const written = /* @__PURE__ */ new Set();
2023
+ const out = [];
2024
+ let inQuote = null;
2025
+ let dropping = false;
2026
+ for (const line of lines) {
2027
+ if (inQuote !== null) {
2028
+ if (!dropping) out.push(line);
2029
+ if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
2030
+ continue;
2031
+ }
2032
+ const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
2033
+ const q = m?.[2][0];
2034
+ const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
2035
+ if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
2036
+ if (!written.has(m[1])) {
2037
+ out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
2038
+ written.add(m[1]);
2039
+ }
2040
+ if (opens) [inQuote, dropping] = [opens, true];
2041
+ continue;
2042
+ }
2043
+ out.push(line);
2044
+ if (opens) inQuote = opens;
2045
+ }
2046
+ for (const name of names) {
2047
+ if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
2048
+ }
2049
+ const text = `${out.join("\n")}
2050
+ `;
2051
+ const readBack = parseEnv(text);
2052
+ const wrong = names.filter((n) => readBack[n] !== updates[n]);
2053
+ if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
2054
+ const target = existsSync4(file) ? await realpath3(file) : file;
2055
+ const temp = `${target}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
2056
+ try {
2057
+ await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
2058
+ await rename2(temp, target);
2059
+ } catch (err) {
2060
+ await rm2(temp, { force: true });
2061
+ throw err;
2062
+ }
2063
+ }
2064
+ var ENV_BACKUPS_KEPT = 5;
2065
+ async function backupEnvFile(file, updates, dir) {
2066
+ if (!existsSync4(file)) return null;
2067
+ const current = parseEnv(await readFile4(file, "utf8"));
2068
+ if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
2069
+ await mkdir3(dir, { recursive: true });
2070
+ const prefix = `${path4.basename(file)}-`;
2071
+ const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
2072
+ let target = path4.join(dir, `${prefix}${stamp2}`);
2073
+ for (let n = 2; existsSync4(target); n += 1) target = path4.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
2074
+ await copyFile(file, target);
2075
+ await chmod(target, 384);
2076
+ const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path4.basename(target)).sort();
2077
+ for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
2078
+ await rm2(path4.join(dir, old));
2079
+ }
2080
+ return target;
2081
+ }
2082
+ var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
2083
+ async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
2084
+ const file = path4.join(dir, ".gitignore");
2085
+ const text = existsSync4(file) ? await readFile4(file, "utf8") : "";
2086
+ const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
2087
+ const wanted = [...IGNORE_LINES];
2088
+ if (envFile) {
2089
+ const rel = path4.relative(treeRoot, envFile).split(path4.sep).join("/");
2090
+ const base = path4.basename(envFile);
2091
+ const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
2092
+ if (!covered && !rel.startsWith("..") && !path4.isAbsolute(rel)) wanted.push(`/${rel}`);
2093
+ }
2094
+ const missing = wanted.filter((l) => !present2.has(l));
2095
+ if (missing.length === 0) return false;
2096
+ const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
2097
+ await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
2098
+ ${missing.join("\n")}
2099
+ `);
2100
+ return true;
2101
+ }
2102
+
2103
+ // src/profiles.ts
2104
+ var ReasonError = class extends Error {
2105
+ constructor(message, reason) {
2106
+ super(message);
2107
+ this.reason = reason;
2108
+ }
2109
+ reason;
2110
+ };
2111
+ function problem(message, reason) {
2112
+ throw new ReasonError(message, reason);
2113
+ }
2114
+ function configDir() {
2115
+ const override = process.env.CHANNELVAULT_CONFIG_DIR;
2116
+ if (!override) return path5.join(homedir(), ".channelvault");
2117
+ const dir = path5.resolve(override);
2118
+ let existing = dir;
2119
+ while (!existsSync5(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
2120
+ const git = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: existing, encoding: "utf8" });
2121
+ if (git.status === 0 && git.stdout.trim() === "true") {
2122
+ problem(`CHANNELVAULT_CONFIG_DIR (${dir}) is inside a git work tree; keep channelvault's folder outside every repository`, "config-in-repo");
2123
+ }
2124
+ return dir;
2125
+ }
2126
+ var PROFILES_FILE = "profiles.json";
2127
+ var CREDENTIALS_FILE = "credentials";
2128
+ var FIELDS = ["host", "port", "user", "https", "insecure", "tlsFingerprint", "serverId", "dotenv"];
2129
+ var PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
2130
+ function isLoopback(host) {
2131
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
2132
+ return h === "localhost" || h === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
2133
+ }
2134
+ function normalizeFingerprint(value) {
2135
+ const hex2 = value.replace(/:/g, "").toLowerCase();
2136
+ return /^[0-9a-f]{64}$/.test(hex2) ? hex2 : null;
2137
+ }
2138
+ function formatFingerprint(hex2) {
2139
+ return hex2.toUpperCase().match(/../g).join(":");
2140
+ }
2141
+ function profileProblems(profiles) {
2142
+ if (profiles === null || typeof profiles !== "object" || Array.isArray(profiles)) return ["profiles must be an object of named profiles"];
2143
+ const problems = [];
2144
+ const dotenvs = [];
2145
+ for (const [name, raw] of Object.entries(profiles)) {
2146
+ const at = `profile ${name}`;
2147
+ if (!PROFILE_NAME.test(name)) problems.push(`${at}: a name is letters, digits, '.', '_' and '-', starting with a letter or digit`);
2148
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
2149
+ problems.push(`${at}: must be an object`);
2150
+ continue;
2151
+ }
2152
+ const p = raw;
2153
+ for (const key of Object.keys(p)) {
2154
+ if (key === "password") problems.push(`${at}: a password does not belong in profiles.json; remove it and run \`channelvault profile set-password ${name}\` at a terminal`);
2155
+ else if (!FIELDS.includes(key)) problems.push(`${at}: unknown field ${key} (fields: ${FIELDS.join(", ")})`);
2156
+ }
2157
+ if (typeof p.host !== "string" || p.host === "" || /[\s/]/.test(p.host)) problems.push(`${at}: host must be a host name or address`);
2158
+ if (!Number.isInteger(p.port) || p.port < 1 || p.port > 65535) problems.push(`${at}: port must be a whole number from 1 to 65535`);
2159
+ if (typeof p.user !== "string" || p.user === "") problems.push(`${at}: user must be a non-empty string`);
2160
+ for (const flag of ["https", "insecure"]) {
2161
+ if (p[flag] !== void 0 && typeof p[flag] !== "boolean") problems.push(`${at}: ${flag} must be true or false`);
2162
+ }
2163
+ if (p.serverId !== void 0 && (typeof p.serverId !== "string" || p.serverId === "")) problems.push(`${at}: serverId must be a non-empty string`);
2164
+ if (p.tlsFingerprint !== void 0 && (typeof p.tlsFingerprint !== "string" || normalizeFingerprint(p.tlsFingerprint) === null)) {
2165
+ problems.push(`${at}: tlsFingerprint must be a SHA-256 certificate fingerprint (64 hex digits, colons allowed)`);
2166
+ }
2167
+ if (p.dotenv !== void 0) {
2168
+ if (typeof p.dotenv !== "string" || !path5.isAbsolute(p.dotenv)) problems.push(`${at}: dotenv must be an absolute path`);
2169
+ else dotenvs.push([name, resolvedPathSync(p.dotenv)]);
2170
+ }
2171
+ if (typeof p.host === "string" && !isLoopback(p.host)) {
2172
+ if (p.https === false) problems.push(`${at}: https cannot be false for ${p.host}; plain http sends the password readable on the network (only loopback hosts may use it)`);
2173
+ if (p.insecure === true) problems.push(`${at}: insecure is refused for ${p.host}; pin the certificate with tlsFingerprint instead (only loopback hosts may turn verification off)`);
2174
+ }
2175
+ if (p.https === false && p.tlsFingerprint !== void 0) problems.push(`${at}: tlsFingerprint needs https`);
2176
+ if (p.insecure === true && p.tlsFingerprint !== void 0) problems.push(`${at}: insecure and tlsFingerprint cannot both be set`);
2177
+ }
2178
+ for (let i = 0; i < dotenvs.length; i++) {
2179
+ for (let j = i + 1; j < dotenvs.length; j++) {
2180
+ if (samePath(dotenvs[i][1], dotenvs[j][1])) problems.push(`profiles ${dotenvs[i][0]} and ${dotenvs[j][0]} share the env file ${dotenvs[i][1]}; each server needs its own`);
2181
+ }
2182
+ }
2183
+ return problems;
2184
+ }
2185
+ function profilesFile() {
2186
+ return path5.join(configDir(), PROFILES_FILE);
2187
+ }
2188
+ function credentialsFile() {
2189
+ return path5.join(configDir(), CREDENTIALS_FILE);
2190
+ }
2191
+ async function loadProfiles() {
2192
+ const file = profilesFile();
2193
+ if (!existsSync5(file)) return {};
2194
+ let parsed;
2195
+ try {
2196
+ parsed = await readJson(file);
2197
+ } catch {
2198
+ problem(`${file} is not valid JSON; fix or remove it`, "profiles-invalid");
2199
+ }
2200
+ const profiles = parsed?.profiles;
2201
+ const keys = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? Object.keys(parsed) : [];
2202
+ const problems = keys.some((k) => k !== "profiles") || profiles === void 0 ? [`the file holds one object, { "profiles": { "<name>": { ... } } }`] : profileProblems(profiles);
2203
+ if (problems.length > 0) problem(`${file} cannot be used:
2204
+ ${problems.join("\n ")}`, "profiles-invalid");
2205
+ const out = {};
2206
+ for (const [name, p] of Object.entries(profiles)) {
2207
+ out[name] = { ...p, ...p.tlsFingerprint ? { tlsFingerprint: normalizeFingerprint(p.tlsFingerprint) } : {} };
2208
+ }
2209
+ return out;
2210
+ }
2211
+ async function ensureConfigDir() {
2212
+ const dir = configDir();
2213
+ await mkdir4(dir, { recursive: true, mode: 448 });
2214
+ return dir;
2215
+ }
2216
+ async function saveProfiles(profiles) {
2217
+ const problems = profileProblems(profiles);
2218
+ if (problems.length > 0) problem(`not saved:
2219
+ ${problems.join("\n ")}`, "profiles-invalid");
2220
+ await ensureConfigDir();
2221
+ await writePrivate(profilesFile(), `${JSON.stringify({ profiles }, null, 2)}
2222
+ `);
2223
+ }
2224
+ async function readCredentials() {
2225
+ return readEnvFile(credentialsFile());
2226
+ }
2227
+ async function setCredential(name, password) {
2228
+ await ensureConfigDir();
2229
+ await updateEnvFile(credentialsFile(), { [name]: password });
2230
+ }
2231
+
2232
+ // src/connection.ts
2233
+ var SOURCE_LABEL = {
2234
+ "profile-flag": "typed --profile",
2235
+ flags: "login flags",
2236
+ "env-profile": "MIRTH_PROFILE",
2237
+ env: "MIRTH_* environment",
2238
+ tree: "the tree's serverId"
2239
+ };
2240
+ function refuse(message, reason) {
2241
+ throw new ReasonError(message, reason);
2242
+ }
2243
+ function urlOf(conn) {
2244
+ return `${conn.https ? "https" : "http"}://${conn.host}:${conn.port}`;
2245
+ }
2246
+ function profileList(profiles) {
2247
+ const names = Object.keys(profiles);
2248
+ return names.length ? `profiles: ${names.join(", ")}` : "no profiles yet; add one at a terminal with `channelvault profile add <name> --host <host> --port <port> --user <user>`";
2249
+ }
2250
+ function sameHost(a, b) {
2251
+ return a.toLowerCase() === b.toLowerCase();
2252
+ }
2253
+ function fromProfile(name, input, source) {
2254
+ const profile = input.profiles[name];
2255
+ if (!profile) refuse(`no profile named ${name} (${profileList(input.profiles)})`, "profile-unknown");
2256
+ const typed = ["host", "port", "user", "pass", "tlsFingerprint"].filter((k) => input.flags[k] !== void 0).map((k) => `--${k === "tlsFingerprint" ? "tls-fingerprint" : k}`);
2257
+ if (input.flags.insecure) typed.push("--insecure");
2258
+ if (input.flags.https === false) typed.push("--no-https");
2259
+ if (typed.length > 0) refuse(`profile ${name} sets the whole connection; drop ${typed.join(", ")} (or use the login flags without a profile)`, "flag-conflict");
2260
+ const password = input.credentials[name];
2261
+ if (password === void 0) refuse(`profile ${name} has no password yet; run \`channelvault profile set-password ${name}\` at a terminal`, "no-password");
2262
+ if (input.treeServerId && profile.serverId && input.treeServerId !== profile.serverId) {
2263
+ refuse(`this tree belongs to installation ${input.treeServerId}, but profile ${name} is installation ${profile.serverId}; choose the profile for this tree`, "profile-mismatch");
2264
+ }
2265
+ return {
2266
+ host: profile.host,
2267
+ port: profile.port,
2268
+ user: profile.user,
2269
+ password,
2270
+ https: profile.https !== false,
2271
+ insecure: profile.insecure === true,
2272
+ ...profile.tlsFingerprint ? { tlsFingerprint: profile.tlsFingerprint } : {},
2273
+ source,
2274
+ passwordSource: "credentials",
2275
+ profile: name,
2276
+ ...profile.serverId ? { serverId: profile.serverId } : {},
2277
+ ...profile.dotenv ? { dotenv: profile.dotenv } : {}
2278
+ };
2279
+ }
2280
+ function fromFlagsAndEnv(input, source) {
2281
+ const { flags, env } = input;
2282
+ const foreign = flags.host !== void 0 && env.MIRTH_HOST && !sameHost(flags.host, env.MIRTH_HOST);
2283
+ const fallback = (name) => foreign ? void 0 : env[name];
2284
+ const host = flags.host ?? env.MIRTH_HOST;
2285
+ const portStr = flags.port ?? fallback("MIRTH_PORT");
2286
+ const user = flags.user ?? fallback("MIRTH_USER");
2287
+ const password = flags.pass ?? fallback("MIRTH_PASS");
2288
+ function missing(field, envName2) {
2289
+ if (foreign && env[envName2] !== void 0) {
2290
+ refuse(`${envName2} belongs to MIRTH_HOST=${env.MIRTH_HOST}, not --host ${flags.host}; type the matching --${field}, or use --profile`, "env-conflict");
2291
+ }
2292
+ refuse(`no ${field} for ${host ?? "the server"}: use --profile <name> (${profileList(input.profiles)})`, "no-connection");
2293
+ }
2294
+ if (!host) refuse(`no server: use --profile <name> (${profileList(input.profiles)})`, "no-connection");
2295
+ if (portStr === void 0) missing("port", "MIRTH_PORT");
2296
+ if (user === void 0) missing("user", "MIRTH_USER");
2297
+ if (password === void 0) missing("pass", "MIRTH_PASS");
2298
+ const port = Number(portStr);
2299
+ if (!Number.isInteger(port) || port < 1 || port > 65535) refuse(`invalid port: ${portStr}`, "bad-port");
2300
+ const rawPin = flags.tlsFingerprint ?? (foreign ? void 0 : env.MIRTH_TLS_FINGERPRINT);
2301
+ const tlsFingerprint = rawPin === void 0 ? void 0 : normalizeFingerprint(rawPin);
2302
+ if (rawPin !== void 0 && !tlsFingerprint) refuse("--tls-fingerprint (or MIRTH_TLS_FINGERPRINT) must be a SHA-256 certificate fingerprint: 64 hex digits, colons allowed", "bad-fingerprint");
2303
+ if (tlsFingerprint && flags.insecure) refuse("--insecure turns off the certificate check that --tls-fingerprint (or MIRTH_TLS_FINGERPRINT) pins; drop --insecure", "flag-conflict");
2304
+ if (tlsFingerprint && flags.https === false) refuse("--tls-fingerprint needs https; drop --no-https", "flag-conflict");
2305
+ return {
2306
+ host,
2307
+ port,
2308
+ user,
2309
+ password,
2310
+ https: flags.https !== false,
2311
+ insecure: flags.insecure === true,
2312
+ ...tlsFingerprint ? { tlsFingerprint } : {},
2313
+ source,
2314
+ passwordSource: flags.pass !== void 0 ? "--pass" : "MIRTH_PASS"
2315
+ };
2316
+ }
2317
+ function profilesFor(profiles, serverId) {
2318
+ return Object.entries(profiles).filter(([, p]) => p.serverId === serverId).map(([n]) => n);
2319
+ }
2320
+ function profileOwning(profiles, serverId) {
2321
+ return profilesFor(profiles, serverId)[0];
2322
+ }
2323
+ function resolveConnection(given) {
2324
+ const input = { ...given, env: Object.fromEntries(Object.entries(given.env).filter(([, v]) => v !== "")) };
2325
+ const { flags, env, profiles } = input;
2326
+ const loginTyped = flags.host !== void 0 || flags.port !== void 0 || flags.user !== void 0 || flags.pass !== void 0;
2327
+ let conn;
2328
+ if (flags.profile !== void 0) {
2329
+ conn = fromProfile(flags.profile, input, "profile-flag");
2330
+ } else if (flags.host !== void 0) {
2331
+ conn = fromFlagsAndEnv(input, "flags");
2332
+ } else if (env.MIRTH_PROFILE) {
2333
+ conn = fromProfile(env.MIRTH_PROFILE, input, "env-profile");
2334
+ } else if (env.MIRTH_HOST) {
2335
+ const owner = input.treeServerId ? profilesFor(profiles, input.treeServerId) : [];
2336
+ if (owner.length > 0) {
2337
+ refuse(`MIRTH_HOST is set, but this tree belongs to profile ${owner.join(" or ")}; use --profile ${owner[0]}, or unset MIRTH_HOST`, "env-shadowed");
2338
+ }
2339
+ conn = fromFlagsAndEnv(input, "env");
2340
+ } else if (loginTyped) {
2341
+ refuse(`--port, --user and --pass need --host (or use --profile <name>; ${profileList(profiles)})`, "no-connection");
2342
+ } else {
2343
+ const owner = input.treeServerId ? profilesFor(profiles, input.treeServerId) : [];
2344
+ if (owner.length > 1) refuse(`profiles ${owner.join(", ")} all name this tree's installation (${input.treeServerId}); pass --profile`, "profile-ambiguous");
2345
+ if (owner.length === 0) {
2346
+ refuse(`no connection: pass --profile <name> (${profileList(profiles)})`, "no-connection");
2347
+ }
2348
+ conn = fromProfile(owner[0], input, "tree");
2349
+ }
2350
+ if (input.write && conn.source === "tree") {
2351
+ refuse(`writing to a server needs the profile typed: add --profile ${conn.profile} (this tree's serverId selects it, which is enough only for reading)`, "profile-not-typed");
2352
+ }
2353
+ if (input.write && conn.source === "env-profile" && input.yes) {
2354
+ refuse(`with --yes, writing to a server needs the profile typed: add --profile ${conn.profile} (MIRTH_PROFILE selects a write only when you confirm it at a terminal)`, "profile-not-typed");
2355
+ }
2356
+ if (input.write && input.explicit && conn.source !== "profile-flag" && conn.source !== "flags") {
2357
+ refuse("this command needs its server typed: pass --profile <name>, or --host with the login (environment variables can be stale)", "connection-not-typed");
2358
+ }
2359
+ return conn;
2360
+ }
2361
+ function describeConnection(conn, serverId, envFile) {
2362
+ const parts = [
2363
+ conn.profile ? `profile ${conn.profile}` : "no profile",
2364
+ `${urlOf(conn)} as ${conn.user}`,
2365
+ serverId ? `installation ${serverId}` : "installation not checked",
2366
+ `chosen by ${SOURCE_LABEL[conn.source]}`,
2367
+ `password from ${conn.passwordSource}`,
2368
+ conn.tlsFingerprint ? `certificate pinned ${formatFingerprint(conn.tlsFingerprint).slice(0, 23)}\u2026` : conn.insecure ? "certificate not checked" : conn.https ? "certificate verified" : "plain http"
2369
+ ];
2370
+ if (envFile) parts.push(`env file ${envFile}`);
2371
+ return `connection: ${parts.join(", ")}`;
2372
+ }
2373
+ function connectionJson(conn, serverId, envFile) {
2374
+ return {
2375
+ profile: conn.profile ?? null,
2376
+ url: urlOf(conn),
2377
+ user: conn.user,
2378
+ source: conn.source,
2379
+ passwordSource: conn.passwordSource,
2380
+ serverId: serverId ?? null,
2381
+ tlsFingerprint: conn.tlsFingerprint ?? null,
2382
+ insecure: conn.insecure,
2383
+ envFile: envFile ?? null
2384
+ };
2385
+ }
2386
+
2387
+ // src/push/index.ts
2388
+ import { createHash as createHash3 } from "crypto";
2389
+
2390
+ // src/push/configMap.ts
2391
+ import { createHash as createHash2 } from "crypto";
2392
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2393
+ function configMapOf(c) {
2394
+ return isObj(c["configurationMap"]) ? list(c["configurationMap"]["entry"]) : [];
2395
+ }
2396
+ function byKey(entries) {
2397
+ const out = /* @__PURE__ */ new Map();
2398
+ for (const e of entries) {
2399
+ const k = configMapKeyOf(e);
2400
+ if (k !== void 0) out.set(k, e);
2401
+ }
2402
+ return out;
2403
+ }
2404
+ function contentOf(entry) {
2405
+ const p = entry[CONFIG_PROPERTY];
2406
+ const part = (name) => {
2407
+ const v = isObj(p) ? p[name] : void 0;
2408
+ return v === null || v === void 0 ? "" : normalizeEol(typeof v === "string" ? v : JSON.stringify(v));
2409
+ };
2410
+ return JSON.stringify([part("value"), part("comment")]);
2411
+ }
2412
+ function sameEntry(a, b) {
2413
+ if (!a || !b) return a === b;
2414
+ return contentOf(a) === contentOf(b);
2415
+ }
2416
+ function sameConfigMap(a, b) {
2417
+ return otherDifferingKeys(a, b, []).length === 0;
2418
+ }
2419
+ function withSortedConfigMap(c) {
2420
+ const holder = c["configurationMap"];
2421
+ if (!isObj(holder) || holder["entry"] === void 0) return c;
2422
+ const entry = [...configMapOf(c)].sort((x, y) => (configMapKeyOf(x) ?? "").localeCompare(configMapKeyOf(y) ?? "", "en"));
2423
+ return { ...c, configurationMap: { ...holder, entry } };
2424
+ }
2425
+ function digest(name, entry) {
2426
+ return createHash2("sha256").update(`${name}\0${contentOf(entry)}`).digest("hex");
2427
+ }
2428
+ function configMapBaseline(c) {
2429
+ return Object.fromEntries([...byKey(configMapOf(c))].map(([k, e]) => [k, digest(k, e)]));
2430
+ }
2431
+ function baselineAfterPush(baseline, server, names) {
2432
+ if (!baseline) return void 0;
2433
+ const now = byKey(configMapOf(server));
2434
+ const next = { ...baseline };
2435
+ for (const name of names) {
2436
+ const e = now.get(name);
2437
+ if (e) next[name] = digest(name, e);
2438
+ else delete next[name];
2439
+ }
2440
+ return next;
2441
+ }
2442
+ function conflictOf(name, server, baseline) {
2443
+ const what = `configuration-map key "${name}"`;
2444
+ if (!baseline) return `${what}: no configuration-map baseline for this installation on this machine; pull or adopt to record one`;
2445
+ const recorded = baseline[name];
2446
+ if (recorded === void 0) return server ? `${what} was created on the server since the last pull` : void 0;
2447
+ if (!server) return `${what} was deleted on the server since the last pull`;
2448
+ return digest(name, server) === recorded ? void 0 : `${what} changed on the server since the last pull`;
2449
+ }
2450
+ function planConfigMap(local, remote, names, baseline) {
2451
+ const tree = byKey(configMapOf(local));
2452
+ const server = byKey(configMapOf(remote));
2453
+ const plan = { changes: [], conflicts: [], unchanged: [] };
2454
+ for (const name of new Set(names)) {
2455
+ const t = tree.get(name);
2456
+ const s = server.get(name);
2457
+ if (!t && !s) throw new UnknownConfigMapKey(name);
2458
+ if (sameEntry(t, s)) {
2459
+ plan.unchanged.push(name);
2460
+ continue;
2461
+ }
2462
+ plan.changes.push({ kind: "configMapKey", op: !s ? "create" : !t ? "delete" : "update", id: name, label: name });
2463
+ const conflict = conflictOf(name, s, baseline);
2464
+ if (conflict) plan.conflicts.push(conflict);
2465
+ }
2466
+ return plan;
2467
+ }
2468
+ var UnknownConfigMapKey = class extends Error {
2469
+ constructor(key) {
2470
+ super(`no configuration-map key named "${key}" in the tree or on the server`);
2471
+ this.key = key;
2472
+ }
2473
+ key;
2474
+ };
2475
+ function configMapMoved(names, before, after) {
2476
+ const [b, a] = [byKey(configMapOf(before)), byKey(configMapOf(after))];
2477
+ return names.filter((n) => !sameEntry(b.get(n), a.get(n)));
2478
+ }
2479
+ function otherDifferingKeys(a, b, names) {
2480
+ const [x, y] = [byKey(configMapOf(a)), byKey(configMapOf(b))];
2481
+ const skip = new Set(names);
2482
+ return [.../* @__PURE__ */ new Set([...x.keys(), ...y.keys()])].filter((k) => !skip.has(k) && !sameEntry(x.get(k), y.get(k))).sort();
2483
+ }
2484
+ function mergeConfigMap(server, local, names) {
2485
+ const tree = byKey(configMapOf(local));
2486
+ const wanted = new Set(names);
2487
+ const placed = /* @__PURE__ */ new Set();
2488
+ const entry = [];
2489
+ for (const e of configMapOf(server)) {
2490
+ const k = configMapKeyOf(e);
2491
+ if (k === void 0 || !wanted.has(k)) {
2492
+ entry.push(e);
2493
+ continue;
2494
+ }
2495
+ placed.add(k);
2496
+ const t = tree.get(k);
2497
+ if (t) entry.push(structuredClone(t));
2498
+ }
2499
+ for (const n of wanted) {
2500
+ const t = tree.get(n);
2501
+ if (!placed.has(n) && t) entry.push(structuredClone(t));
2502
+ }
2503
+ const holder = isObj(server["configurationMap"]) ? server["configurationMap"] : {};
2504
+ return { ...holder, entry };
2505
+ }
2506
+
2507
+ // src/push/index.ts
2508
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2509
+ function list(v) {
2510
+ if (v == null || v === "") return [];
2511
+ return (Array.isArray(v) ? v : [v]).filter(isObj2);
2512
+ }
2513
+ function channelsOf(c) {
2514
+ return isObj2(c["channels"]) ? list(c["channels"]["channel"]) : [];
2515
+ }
2516
+ function librariesOf(c) {
2517
+ return isObj2(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
2518
+ }
2519
+ function templatesOf2(library) {
2520
+ return isObj2(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
2521
+ }
2522
+ var idOf = (o) => String(o["id"]);
2523
+ var nameOf = (o) => String(o["name"] ?? o["id"]);
2524
+ var revisionOf = (o) => Number(o["revision"] ?? 0);
2525
+ function normalizeEol(s) {
2526
+ return s.replace(/\r\n?/g, "\n");
2527
+ }
2528
+ function normalizeEolDeep(value) {
2529
+ if (typeof value === "string") return normalizeEol(value);
2530
+ if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
2531
+ if (isObj2(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
2532
+ return value;
2533
+ }
2534
+ function same(a, b) {
2535
+ if (a === b) return true;
2536
+ if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
2537
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
2538
+ if (isObj2(a) && isObj2(b)) {
2539
+ const ka = Object.keys(a);
2540
+ return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
2541
+ }
2542
+ return false;
2543
+ }
2544
+ var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
2545
+ function withSortedContexts(o) {
2546
+ const set = o["contextSet"];
2547
+ const delegate = isObj2(set) ? set["delegate"] : void 0;
2548
+ const types = isObj2(delegate) ? delegate["contextType"] : void 0;
2549
+ if (!isObj2(set) || !isObj2(delegate) || !Array.isArray(types)) return o;
2550
+ const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
2551
+ return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
2552
+ }
2553
+ function stripVolatile(o) {
2554
+ const out = withSortedContexts({ ...o });
2555
+ delete out["revision"];
2556
+ delete out["lastModified"];
2557
+ const exportData = out["exportData"];
2558
+ if (isObj2(exportData)) {
2559
+ const metadata = isObj2(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
2560
+ if (metadata) {
2561
+ delete metadata["lastModified"];
2562
+ delete metadata["userId"];
2563
+ }
2564
+ out["exportData"] = metadata ? { metadata } : {};
2565
+ }
2566
+ return out;
2567
+ }
2568
+ var groupsOf = (c) => isObj2(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
2569
+ function withoutVolatile(c) {
2570
+ const out = structuredClone(c);
2571
+ const strip = (o) => {
2572
+ delete o["revision"];
2573
+ delete o["lastModified"];
2574
+ const exportData = o["exportData"];
2575
+ const md = isObj2(exportData) ? exportData["metadata"] : void 0;
2576
+ if (isObj2(md)) {
2577
+ delete md["lastModified"];
2578
+ delete md["userId"];
2579
+ }
2580
+ if (isObj2(exportData)) {
2581
+ for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
2582
+ }
2583
+ if (isObj2(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
2584
+ };
2585
+ for (const ch of channelsOf(out)) strip(ch);
2586
+ for (const lib of librariesOf(out)) {
2587
+ strip(lib);
2588
+ for (const t of templatesOf2(lib)) strip(t);
2589
+ }
2590
+ for (const g of groupsOf(out)) {
2591
+ strip(g);
2592
+ for (const member of isObj2(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
2593
+ }
2594
+ return out;
2595
+ }
2596
+ function newerOnServer(tree, server) {
2597
+ const out = [];
2598
+ const compare = (kind, local, remote) => {
2599
+ const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
2600
+ for (const r of remote) {
2601
+ const rev = mine.get(idOf(r));
2602
+ if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
2603
+ }
2604
+ };
2605
+ compare("channel", channelsOf(tree), channelsOf(server));
2606
+ compare("library", librariesOf(tree), librariesOf(server));
2607
+ compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
2608
+ compare("channel group", groupsOf(tree), groupsOf(server));
2609
+ return out;
2610
+ }
2611
+ function libraryShape(lib) {
2612
+ const out = stripVolatile(lib);
2613
+ out["codeTemplates"] = templatesOf2(lib).map(idOf);
2614
+ return out;
2615
+ }
2616
+ function withRetainedMembers(local, remote, localIds, deletedIds) {
2617
+ const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
2618
+ if (!retained.length) return local;
2619
+ return { ...local, codeTemplates: {
2620
+ ...isObj2(local["codeTemplates"]) ? local["codeTemplates"] : {},
2621
+ codeTemplate: [...templatesOf2(local), ...retained]
2622
+ } };
2623
+ }
2624
+ function hashGlobalScripts(c) {
2625
+ return createHash3("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
2626
+ }
2627
+ function resourceIds(c) {
2628
+ const libs = librariesOf(c);
2629
+ const revs = (items) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));
2630
+ return {
2631
+ channels: revs(channelsOf(c)),
2632
+ libraries: revs(libs),
2633
+ codeTemplates: revs(libs.flatMap(templatesOf2)),
2634
+ globalScripts: hashGlobalScripts(c)
2635
+ };
2636
+ }
2637
+ function adoptTarget(local, target) {
2638
+ const config = structuredClone(local);
2639
+ const mine = resourceIds(local);
2640
+ const theirs = resourceIds(target);
2641
+ const intersect = (key) => Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));
2642
+ const known = {
2643
+ channels: intersect("channels"),
2644
+ libraries: intersect("libraries"),
2645
+ codeTemplates: intersect("codeTemplates"),
2646
+ globalScripts: theirs.globalScripts
2647
+ };
2648
+ const rebase = (items, revisions) => {
2649
+ for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
2650
+ };
2651
+ rebase(channelsOf(config), theirs.channels);
2652
+ rebase(librariesOf(config), theirs.libraries);
2653
+ rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
2654
+ return { config, known };
2655
+ }
2656
+ function knownFrom(raw) {
2657
+ if (!isObj2(raw)) return void 0;
2658
+ const r = raw;
2659
+ const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
2660
+ return {
2661
+ channels: map(r["channels"]),
2662
+ libraries: map(r["libraries"]),
2663
+ codeTemplates: map(r["codeTemplates"]),
2664
+ globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
2665
+ };
2666
+ }
2667
+ function knownAfterPush(known, applied, touched, fresh) {
2668
+ const now = resourceIds(fresh);
2669
+ const next = {
2670
+ channels: { ...known.channels },
2671
+ libraries: { ...known.libraries },
2672
+ codeTemplates: { ...known.codeTemplates },
1926
2673
  globalScripts: known.globalScripts
1927
2674
  };
1928
2675
  const key = { channel: "channels", library: "libraries", codeTemplate: "codeTemplates" };
@@ -1967,7 +2714,7 @@ function librariesInSync(local, remote) {
1967
2714
  }).map(idOf);
1968
2715
  }
1969
2716
  function channelsUsing(lib, allChannelIds) {
1970
- const ids = (v) => isObj(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
2717
+ const ids = (v) => isObj2(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
1971
2718
  if (lib["includeNewChannels"] === true) {
1972
2719
  const disabled = new Set(ids(lib["disabledChannelIds"]));
1973
2720
  return allChannelIds.filter((id) => !disabled.has(id));
@@ -2112,11 +2859,11 @@ rename one of them, or delete or rename the other in a push of its own first`
2112
2859
  conflicts.push("global scripts changed on the server since the last pull");
2113
2860
  }
2114
2861
  }
2115
- 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() : [];
2862
+ 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() : [];
2116
2863
  const enabled = new Set(
2117
2864
  [...effective.values()].filter((c) => {
2118
- const md = isObj(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
2119
- return !(isObj(md) && md["enabled"] === false);
2865
+ const md = isObj2(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
2866
+ return !(isObj2(md) && md["enabled"] === false);
2120
2867
  }).map(idOf)
2121
2868
  );
2122
2869
  return {
@@ -2199,9 +2946,9 @@ function findChannel(c, id) {
2199
2946
  }
2200
2947
 
2201
2948
  // src/push/apply.ts
2202
- import { readdir as readdir2, writeFile as writeFile2 } from "fs/promises";
2203
- import { existsSync as existsSync2 } from "fs";
2204
- import * as path2 from "path";
2949
+ import { readdir as readdir4, writeFile as writeFile4 } from "fs/promises";
2950
+ import { existsSync as existsSync6 } from "fs";
2951
+ import * as path6 from "path";
2205
2952
  var ORDER = [
2206
2953
  ["codeTemplate", ["create", "update"]],
2207
2954
  ["library", ["create", "update", "delete"]],
@@ -2269,347 +3016,124 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
2269
3016
  }
2270
3017
  return { applied, touchedIds, sentLibraries };
2271
3018
  }
2272
- function checkResource(change, before, current, force) {
2273
- if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
2274
- throw new Error(`${change.label} changed on the server during the push (revision ${String(current?.["revision"] ?? "absent")}, planned against ${String(before?.["revision"] ?? "absent")}); pull and try again`);
2275
- }
2276
- }
2277
- async function checkTemplate(client, change, remote, force) {
2278
- checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
2279
- }
2280
- async function withServerAssociations(client, channel, change, planned, force) {
2281
- const server = await client.getChannel(String(channel["id"]));
2282
- checkResource(change, planned, server, force);
2283
- if (change.op !== "update") return channel;
2284
- const serverExport = server?.["exportData"];
2285
- if (!serverExport) return channel;
2286
- const exportData = { ...channel["exportData"] ?? {} };
2287
- for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
2288
- return { ...channel, exportData };
2289
- }
2290
- async function deployChannels(client, ids, nameOf2) {
2291
- const deployed = [];
2292
- const skipped = [];
2293
- const failures = [];
2294
- for (const id of ids) {
2295
- try {
2296
- if (!(await client.getDeployedChannelIds()).has(id)) {
2297
- skipped.push(nameOf2(id));
2298
- continue;
2299
- }
2300
- await client.deployChannel(id);
2301
- deployed.push(nameOf2(id));
2302
- } catch (err) {
2303
- failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
2304
- }
2305
- }
2306
- return { deployed, skipped, failures };
2307
- }
2308
- function copyVersionFields(target, source) {
2309
- if (!source) return false;
2310
- let changed = false;
2311
- for (const key of ["revision", "lastModified"]) {
2312
- if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
2313
- target[key] = source[key];
2314
- changed = true;
2315
- }
2316
- }
2317
- const tm = target["exportData"]?.["metadata"];
2318
- const sm = source["exportData"]?.["metadata"];
2319
- if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
2320
- tm["lastModified"] = sm["lastModified"];
2321
- changed = true;
2322
- }
2323
- return changed;
2324
- }
2325
- async function jsonFiles(dir, name) {
2326
- if (!existsSync2(dir)) return [];
2327
- const entries = await readdir2(dir, { withFileTypes: true });
2328
- return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
2329
- }
2330
- async function refreshRevisions(root, server, ids) {
2331
- for (const file of await jsonFiles(path2.join(root, "channels"), "channel.json")) {
2332
- const json = await readJson(file);
2333
- if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
2334
- await writeFile2(file, JSON.stringify(json, null, 2));
2335
- }
2336
- }
2337
- const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
2338
- for (const file of await jsonFiles(path2.join(root, "codeTemplates"), "library.json")) {
2339
- const json = await readJson(file);
2340
- let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
2341
- const container = json["codeTemplates"];
2342
- for (const t of list(container?.["codeTemplate"])) {
2343
- if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
2344
- }
2345
- if (changed) await writeFile2(file, JSON.stringify(json, null, 2));
2346
- }
2347
- }
2348
-
2349
- // src/secrets/envfile.ts
2350
- import { randomBytes } from "crypto";
2351
- import { existsSync as existsSync3 } from "fs";
2352
- import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as readdir3, realpath as realpath2, rename, rm, writeFile as writeFile3 } from "fs/promises";
2353
- import * as path3 from "path";
2354
- import { parse } from "dotenv";
2355
- var BASE64_PREFIX = "cv-base64:";
2356
- function parseEnv(text) {
2357
- const out = parse(text);
2358
- for (const [k, v] of Object.entries(out)) {
2359
- if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
2360
- }
2361
- return out;
2362
- }
2363
- async function readEnvFile(file) {
2364
- if (!existsSync3(file)) return {};
2365
- return parseEnv(await readFile3(file, "utf8"));
2366
- }
2367
- function formatValue(value) {
2368
- const candidates = [
2369
- /^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
2370
- value.includes("'") ? null : `'${value}'`,
2371
- value.includes("`") ? null : `\`${value}\``,
2372
- value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
2373
- ];
2374
- for (const c of candidates) {
2375
- if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
2376
- }
2377
- return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
2378
- }
2379
- async function updateEnvFile(file, updates) {
2380
- const names = Object.keys(updates);
2381
- if (names.length === 0) return;
2382
- const existing = existsSync3(file) ? await readFile3(file, "utf8") : "";
2383
- const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
2384
- const written = /* @__PURE__ */ new Set();
2385
- const out = [];
2386
- let inQuote = null;
2387
- let dropping = false;
2388
- for (const line of lines) {
2389
- if (inQuote !== null) {
2390
- if (!dropping) out.push(line);
2391
- if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
2392
- continue;
2393
- }
2394
- const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
2395
- const q = m?.[2][0];
2396
- const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
2397
- if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
2398
- if (!written.has(m[1])) {
2399
- out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
2400
- written.add(m[1]);
2401
- }
2402
- if (opens) [inQuote, dropping] = [opens, true];
2403
- continue;
2404
- }
2405
- out.push(line);
2406
- if (opens) inQuote = opens;
2407
- }
2408
- for (const name of names) {
2409
- if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
2410
- }
2411
- const text = `${out.join("\n")}
2412
- `;
2413
- const readBack = parseEnv(text);
2414
- const wrong = names.filter((n) => readBack[n] !== updates[n]);
2415
- if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
2416
- const target = existsSync3(file) ? await realpath2(file) : file;
2417
- const temp = `${target}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
2418
- try {
2419
- await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
2420
- await rename(temp, target);
2421
- } catch (err) {
2422
- await rm(temp, { force: true });
2423
- throw err;
2424
- }
2425
- }
2426
- var ENV_BACKUPS_KEPT = 5;
2427
- async function backupEnvFile(file, updates, dir) {
2428
- if (!existsSync3(file)) return null;
2429
- const current = parseEnv(await readFile3(file, "utf8"));
2430
- if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
2431
- await mkdir2(dir, { recursive: true });
2432
- const prefix = `${path3.basename(file)}-`;
2433
- const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
2434
- let target = path3.join(dir, `${prefix}${stamp2}`);
2435
- for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
2436
- await copyFile(file, target);
2437
- await chmod(target, 384);
2438
- const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
2439
- for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
2440
- await rm(path3.join(dir, old));
2441
- }
2442
- return target;
2443
- }
2444
- var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
2445
- async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
2446
- const file = path3.join(dir, ".gitignore");
2447
- const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
2448
- const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
2449
- const wanted = [...IGNORE_LINES];
2450
- if (envFile) {
2451
- const rel = path3.relative(treeRoot, envFile).split(path3.sep).join("/");
2452
- const base = path3.basename(envFile);
2453
- const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
2454
- if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
2455
- }
2456
- const missing = wanted.filter((l) => !present2.has(l));
2457
- if (missing.length === 0) return false;
2458
- const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
2459
- await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
2460
- ${missing.join("\n")}
2461
- `);
2462
- return true;
2463
- }
2464
-
2465
- // src/backup/index.ts
2466
- import { randomBytes as randomBytes2 } from "crypto";
2467
- import { existsSync as existsSync4, realpathSync } from "fs";
2468
- import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
2469
- import * as path5 from "path";
2470
-
2471
- // src/profiles.ts
2472
- import { homedir } from "os";
2473
- import * as path4 from "path";
2474
- function configDir() {
2475
- const override = process.env.CHANNELVAULT_CONFIG_DIR;
2476
- return override ? path4.resolve(override) : path4.join(homedir(), ".channelvault");
2477
- }
2478
-
2479
- // src/backup/index.ts
2480
- function defaultBackupDir() {
2481
- return path5.join(configDir(), "backups");
2482
- }
2483
- var LEGACY_BACKUP_DIR = ".backup";
2484
- var DEFAULT_KEEP = 10;
2485
- var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
2486
- function serverSlug(name) {
2487
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
2488
- }
2489
- function backupName(config, fallback) {
2490
- return configuredName(config) || serverSlug(fallback) || "mirth";
2491
- }
2492
- function configuredName(config) {
2493
- const settings = config["serverSettings"];
2494
- const field = (key) => {
2495
- const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
2496
- return typeof v === "string" ? serverSlug(v) : "";
2497
- };
2498
- return field("serverName") || field("environmentName");
2499
- }
2500
- function stamp(date) {
2501
- return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
2502
- }
2503
- async function listBackups(dir) {
2504
- if (!existsSync4(dir)) return [];
2505
- const out = [];
2506
- for (const name of await readdir4(dir)) {
2507
- const m = FILE_NAME.exec(name);
2508
- if (m) out.push({ file: path5.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2509
- }
2510
- return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
2511
- }
2512
- var MANIFEST = "channelvault-backups.json";
2513
- async function readManifest(dir) {
2514
- const file = path5.join(dir, MANIFEST);
2515
- if (!existsSync4(file)) return {};
2516
- try {
2517
- const parsed = JSON.parse(await readFile4(file, "utf8"));
2518
- return parsed.files ?? {};
2519
- } catch (err) {
2520
- throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
2521
- }
2522
- }
2523
- async function writeManifest(dir, files) {
2524
- const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path5.join(dir, name))));
2525
- await writePrivate(path5.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
2526
- `);
2527
- }
2528
- async function backupsOf(dir, serverId) {
2529
- const manifest = await readManifest(dir);
2530
- return (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === serverId);
2531
- }
2532
- async function originOf(dir, file) {
2533
- if (!existsSync4(dir) || !sameFile(path5.dirname(file), dir)) return null;
2534
- return (await readManifest(dir))[path5.basename(file)] ?? null;
2535
- }
2536
- async function originsIn(dir) {
2537
- if (!existsSync4(dir)) return [];
2538
- const seen = /* @__PURE__ */ new Map();
2539
- for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);
2540
- return [...seen.values()];
2541
- }
2542
- async function saveBackup(dir, name, xml2, opts) {
2543
- await ensureBackupDir(dir);
2544
- const manifest = await readManifest(dir);
2545
- const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
2546
- let file = path5.join(dir, `${base}.xml`);
2547
- for (let n = 2; existsSync4(file); n += 1) file = path5.join(dir, `${base}-${n}.xml`);
2548
- await writePrivate(file, xml2);
2549
- manifest[path5.basename(file)] = opts.origin;
2550
- await writeManifest(dir, manifest);
2551
- const mine = (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === opts.origin.serverId);
2552
- for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
2553
- if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
2554
- await rm2(old.file);
3019
+ function checkResource(change, before, current, force) {
3020
+ if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
3021
+ throw new Error(`${change.label} changed on the server during the push (revision ${String(current?.["revision"] ?? "absent")}, planned against ${String(before?.["revision"] ?? "absent")}); pull and try again`);
2555
3022
  }
2556
- await writeManifest(dir, manifest);
2557
- return file;
2558
3023
  }
2559
- function sameFile(a, b) {
2560
- const real = (p) => {
2561
- const resolved = existsSync4(p) ? realpathSync.native(p) : path5.resolve(p);
2562
- return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
2563
- };
2564
- return real(a) === real(b);
3024
+ async function checkTemplate(client, change, remote, force) {
3025
+ checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
2565
3026
  }
2566
- async function ensureBackupDir(dir) {
2567
- if (existsSync4(dir)) return;
2568
- await mkdir3(dir, { recursive: true, mode: 448 });
2569
- await writeFile4(path5.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
3027
+ async function withServerAssociations(client, channel, change, planned, force) {
3028
+ const server = await client.getChannel(String(channel["id"]));
3029
+ checkResource(change, planned, server, force);
3030
+ if (change.op !== "update") return channel;
3031
+ const serverExport = server?.["exportData"];
3032
+ if (!serverExport) return channel;
3033
+ const exportData = { ...channel["exportData"] ?? {} };
3034
+ for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
3035
+ return { ...channel, exportData };
2570
3036
  }
2571
- async function writePrivate(file, text) {
2572
- const temp = `${file}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
2573
- try {
2574
- await writeFile4(temp, text, { encoding: "utf8", mode: 384 });
2575
- await rename2(temp, file);
2576
- } catch (err) {
2577
- await rm2(temp, { force: true });
2578
- throw err;
3037
+ async function deployChannels(client, ids, nameOf2) {
3038
+ const deployed = [];
3039
+ const skipped = [];
3040
+ const failures = [];
3041
+ for (const id of ids) {
3042
+ try {
3043
+ if (!(await client.getDeployedChannelIds()).has(id)) {
3044
+ skipped.push(nameOf2(id));
3045
+ continue;
3046
+ }
3047
+ await client.deployChannel(id);
3048
+ deployed.push(nameOf2(id));
3049
+ } catch (err) {
3050
+ failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
3051
+ }
2579
3052
  }
3053
+ return { deployed, skipped, failures };
2580
3054
  }
2581
- function numericVersion(v) {
2582
- const m = /^\d+(?:\.\d+)*/.exec(v.trim());
2583
- return m ? m[0].split(".").map(Number) : null;
3055
+ function copyVersionFields(target, source) {
3056
+ if (!source) return false;
3057
+ let changed = false;
3058
+ for (const key of ["revision", "lastModified"]) {
3059
+ if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
3060
+ target[key] = source[key];
3061
+ changed = true;
3062
+ }
3063
+ }
3064
+ const tm = target["exportData"]?.["metadata"];
3065
+ const sm = source["exportData"]?.["metadata"];
3066
+ if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
3067
+ tm["lastModified"] = sm["lastModified"];
3068
+ changed = true;
3069
+ }
3070
+ return changed;
2584
3071
  }
2585
- function compareVersions(a, b) {
2586
- const pa = numericVersion(a);
2587
- const pb = numericVersion(b);
2588
- for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
2589
- const d = (pa[i] ?? 0) - (pb[i] ?? 0);
2590
- if (d !== 0) return d;
3072
+ async function jsonFiles(dir, name) {
3073
+ if (!existsSync6(dir)) return [];
3074
+ const entries = await readdir4(dir, { withFileTypes: true });
3075
+ return entries.filter((e) => e.isDirectory()).map((e) => path6.join(dir, e.name, name)).filter((f) => existsSync6(f));
3076
+ }
3077
+ async function refreshRevisions(root, server, ids) {
3078
+ for (const file of await jsonFiles(path6.join(root, "channels"), "channel.json")) {
3079
+ const json = await readJson(file);
3080
+ if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
3081
+ await writeFile4(file, JSON.stringify(json, null, 2));
3082
+ }
2591
3083
  }
2592
- return 0;
3084
+ const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
3085
+ for (const file of await jsonFiles(path6.join(root, "codeTemplates"), "library.json")) {
3086
+ const json = await readJson(file);
3087
+ let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
3088
+ const container = json["codeTemplates"];
3089
+ for (const t of list(container?.["codeTemplate"])) {
3090
+ if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
3091
+ }
3092
+ if (changed) await writeFile4(file, JSON.stringify(json, null, 2));
3093
+ }
3094
+ }
3095
+
3096
+ // src/configMapBaselines.ts
3097
+ import { createHash as createHash4 } from "crypto";
3098
+ import { existsSync as existsSync7 } from "fs";
3099
+ import { mkdir as mkdir5 } from "fs/promises";
3100
+ import * as path7 from "path";
3101
+ var BASELINES_DIR = "config-map-baselines";
3102
+ function fileFor(serverId) {
3103
+ return path7.join(configDir(), BASELINES_DIR, `${createHash4("sha256").update(serverId).digest("hex").slice(0, 32)}.json`);
3104
+ }
3105
+ async function readConfigMapBaseline(serverId) {
3106
+ const file = fileFor(serverId);
3107
+ if (!existsSync7(file)) return void 0;
3108
+ const stored = await readJson(file);
3109
+ if (stored.serverId !== serverId || typeof stored.entries !== "object" || stored.entries === null) return void 0;
3110
+ return stored.entries;
3111
+ }
3112
+ async function writeConfigMapBaseline(serverId, entries) {
3113
+ const file = fileFor(serverId);
3114
+ await mkdir5(path7.dirname(file), { recursive: true, mode: 448 });
3115
+ await writePrivate(file, `${JSON.stringify({ serverId, entries }, null, 2)}
3116
+ `);
2593
3117
  }
2594
3118
 
2595
3119
  // src/xml/chars.ts
2596
3120
  import { readFile as readFile5 } from "fs/promises";
2597
- import * as path7 from "path";
3121
+ import * as path9 from "path";
2598
3122
 
2599
3123
  // src/tree/transaction.ts
2600
3124
  import { randomUUID } from "crypto";
2601
- import { constants, existsSync as existsSync5 } from "fs";
2602
- import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir4, readdir as readdir5, readlink, realpath as realpath3, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
3125
+ import { constants, existsSync as existsSync8 } from "fs";
3126
+ 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";
2603
3127
  import { hostname } from "os";
2604
- import * as path6 from "path";
3128
+ import * as path8 from "path";
2605
3129
  import { setTimeout as delay } from "timers/promises";
2606
3130
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2607
3131
  async function treeFiles(base) {
2608
3132
  const out = [];
2609
3133
  for (const d of MANAGED_DIRS) {
2610
- if (!existsSync5(path6.join(base, d))) continue;
2611
- for (const entry of await readdir5(path6.join(base, d), { recursive: true, withFileTypes: true })) {
2612
- if (entry.isFile()) out.push(path6.relative(base, path6.join(entry.parentPath, entry.name)).split(path6.sep).join("/"));
3134
+ if (!existsSync8(path8.join(base, d))) continue;
3135
+ for (const entry of await readdir5(path8.join(base, d), { recursive: true, withFileTypes: true })) {
3136
+ if (entry.isFile()) out.push(path8.relative(base, path8.join(entry.parentPath, entry.name)).split(path8.sep).join("/"));
2613
3137
  }
2614
3138
  }
2615
3139
  return out;
@@ -2618,21 +3142,6 @@ var STAGING_DIR = ".channelvault-staging";
2618
3142
  var JOURNAL = ".channelvault-transaction.json";
2619
3143
  var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
2620
3144
  var RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
2621
- async function present(file) {
2622
- return lstat2(file).then(() => true, (err) => {
2623
- if (err.code === "ENOENT") return false;
2624
- throw err;
2625
- });
2626
- }
2627
- async function canonical(file, depth = 0) {
2628
- if (depth > 64) throw new Error(`too many links in path: ${file}`);
2629
- let existing = path6.resolve(file);
2630
- while (!await present(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
2631
- const info = await lstat2(existing);
2632
- const base = info.isSymbolicLink() ? await canonical(path6.resolve(path6.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2633
- return path6.join(base, path6.relative(existing, path6.resolve(file)));
2634
- }
2635
- var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
2636
3145
  async function move(from, to) {
2637
3146
  for (let attempt = 0; ; attempt++) {
2638
3147
  try {
@@ -2645,15 +3154,15 @@ async function move(from, to) {
2645
3154
  }
2646
3155
  }
2647
3156
  async function lockTree(root) {
2648
- await mkdir4(path6.dirname(root), { recursive: true });
3157
+ await mkdir6(path8.dirname(root), { recursive: true });
2649
3158
  const lock = `${await canonical(root)}.channelvault-lock`;
2650
- const ownerFile = path6.join(lock, "owner.json");
3159
+ const ownerFile = path8.join(lock, "owner.json");
2651
3160
  const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
2652
3161
  try {
2653
- await mkdir4(lock);
3162
+ await mkdir6(lock);
2654
3163
  } catch (err) {
2655
3164
  if (err.code !== "EEXIST") throw err;
2656
- if ((await lstat2(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
3165
+ if ((await lstat3(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
2657
3166
  let previous;
2658
3167
  try {
2659
3168
  previous = await readJson(ownerFile);
@@ -2670,9 +3179,9 @@ async function lockTree(root) {
2670
3179
  }
2671
3180
  };
2672
3181
  if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
2673
- const reaping = path6.join(lock, "reaping");
3182
+ const reaping = path8.join(lock, "reaping");
2674
3183
  try {
2675
- await mkdir4(reaping);
3184
+ await mkdir6(reaping);
2676
3185
  } catch {
2677
3186
  throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
2678
3187
  }
@@ -2684,7 +3193,7 @@ async function lockTree(root) {
2684
3193
  await rmdir(reaping);
2685
3194
  }
2686
3195
  await rmdir(lock);
2687
- await mkdir4(lock);
3196
+ await mkdir6(lock);
2688
3197
  }
2689
3198
  try {
2690
3199
  await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
@@ -2701,8 +3210,8 @@ async function lockTree(root) {
2701
3210
  }
2702
3211
  async function assertStage(root) {
2703
3212
  for (const suffix of ["", "next", "previous"]) {
2704
- const stage = path6.join(root, STAGING_DIR, suffix);
2705
- const info = await lstat2(stage).catch((err) => {
3213
+ const stage = path8.join(root, STAGING_DIR, suffix);
3214
+ const info = await lstat3(stage).catch((err) => {
2706
3215
  if (err.code !== "ENOENT") throw err;
2707
3216
  return void 0;
2708
3217
  });
@@ -2710,10 +3219,10 @@ async function assertStage(root) {
2710
3219
  }
2711
3220
  }
2712
3221
  function targetOf(root, journal, name) {
2713
- return name === "env" ? journal.envFile : path6.join(root, name);
3222
+ return name === "env" ? journal.envFile : path8.join(root, name);
2714
3223
  }
2715
3224
  function copies(root, journal, name) {
2716
- return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path6.join(root, STAGING_DIR, "previous", name), next: path6.join(root, STAGING_DIR, "next", name) };
3225
+ 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) };
2717
3226
  }
2718
3227
  async function cleanup(root, journal) {
2719
3228
  if (journal.entries.some((e) => e.name === "env")) {
@@ -2721,7 +3230,7 @@ async function cleanup(root, journal) {
2721
3230
  await rm3(old, { force: true });
2722
3231
  await rm3(next, { force: true });
2723
3232
  }
2724
- await rm3(path6.join(root, STAGING_DIR), RM);
3233
+ await rm3(path8.join(root, STAGING_DIR), RM);
2725
3234
  }
2726
3235
  async function rollback(root, journal) {
2727
3236
  for (const entry of [...journal.entries].reverse()) {
@@ -2735,12 +3244,19 @@ async function rollback(root, journal) {
2735
3244
  }
2736
3245
  }
2737
3246
  }
2738
- async function recoverTree(root, envFile) {
2739
- const file = path6.join(root, JOURNAL);
2740
- if (!existsSync5(file)) return;
3247
+ async function pendingEnvFile(root) {
3248
+ const file = path8.join(root, JOURNAL);
3249
+ if (!existsSync8(file)) return null;
3250
+ const journal = await readJson(file).catch(() => null);
3251
+ return typeof journal?.envFile === "string" ? journal.envFile : null;
3252
+ }
3253
+ async function recoverTree(root, envFiles) {
3254
+ const file = path8.join(root, JOURNAL);
3255
+ if (!existsSync8(file)) return;
2741
3256
  await assertStage(root);
2742
3257
  const journal = await readJson(file);
2743
- if (journal.version !== 1 || !/^[a-f0-9-]{36}$/.test(journal.id) || !["prepared", "committed"].includes(journal.state) || !Array.isArray(journal.entries) || journal.entries.some((e) => !ITEMS.includes(e.name) || typeof e.hadOld !== "boolean") || new Set(journal.entries.map((e) => e.name)).size !== journal.entries.length || typeof journal.envFile !== "string" || !samePath(journal.envFile, await canonical(envFile))) {
3258
+ const allowed = await Promise.all((Array.isArray(envFiles) ? envFiles : [envFiles]).map((f) => canonical(f)));
3259
+ if (journal.version !== 1 || !/^[a-f0-9-]{36}$/.test(journal.id) || !["prepared", "committed"].includes(journal.state) || !Array.isArray(journal.entries) || journal.entries.some((e) => !ITEMS.includes(e.name) || typeof e.hadOld !== "boolean") || new Set(journal.entries.map((e) => e.name)).size !== journal.entries.length || typeof journal.envFile !== "string" || !allowed.some((f) => samePath(journal.envFile, f))) {
2744
3260
  throw new Error(`invalid transaction journal or different env file: ${file}; use the original --dotenv selection to recover`);
2745
3261
  }
2746
3262
  if (journal.state === "prepared") await rollback(root, journal);
@@ -2750,56 +3266,56 @@ async function recoverTree(root, envFile) {
2750
3266
  async function replaceTree(root, envFile, prepare) {
2751
3267
  await recoverTree(root, envFile);
2752
3268
  await assertStage(root);
2753
- const stage = path6.join(root, STAGING_DIR);
3269
+ const stage = path8.join(root, STAGING_DIR);
2754
3270
  await rm3(stage, RM);
2755
- const next = path6.join(stage, "next");
2756
- await mkdir4(next, { recursive: true });
3271
+ const next = path8.join(stage, "next");
3272
+ await mkdir6(next, { recursive: true });
2757
3273
  let journal;
2758
3274
  try {
2759
3275
  await prepare(next);
2760
3276
  const targetEnv = await canonical(envFile);
2761
3277
  journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
2762
3278
  for (const name of ITEMS) {
2763
- if (!MANAGED_DIRS.includes(name) && !existsSync5(path6.join(next, name === "env" ? ".env" : name))) continue;
3279
+ if (!MANAGED_DIRS.includes(name) && !existsSync8(path8.join(next, name === "env" ? ".env" : name))) continue;
2764
3280
  const target = targetOf(root, journal, name);
2765
- const info = await lstat2(target).catch((err) => {
3281
+ const info = await lstat3(target).catch((err) => {
2766
3282
  if (err.code !== "ENOENT") throw err;
2767
3283
  return void 0;
2768
3284
  });
2769
3285
  journal.entries.push({ name, hadOld: info !== void 0 });
2770
3286
  }
2771
- await mkdir4(path6.join(stage, "previous"));
2772
- await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
3287
+ await mkdir6(path8.join(stage, "previous"));
3288
+ await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
2773
3289
  if (journal.entries.some((e) => e.name === "env")) {
2774
- await mkdir4(path6.dirname(targetEnv), { recursive: true });
2775
- await copyFile2(path6.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
3290
+ await mkdir6(path8.dirname(targetEnv), { recursive: true });
3291
+ await copyFile2(path8.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2776
3292
  }
2777
3293
  for (const entry of journal.entries) {
2778
3294
  const target = targetOf(root, journal, entry.name);
2779
3295
  const files = copies(root, journal, entry.name);
2780
3296
  if (entry.hadOld) await move(target, files.old);
2781
- if (existsSync5(files.next)) {
2782
- await mkdir4(path6.dirname(target), { recursive: true });
3297
+ if (existsSync8(files.next)) {
3298
+ await mkdir6(path8.dirname(target), { recursive: true });
2783
3299
  await move(files.next, target);
2784
3300
  }
2785
3301
  }
2786
3302
  journal.state = "committed";
2787
- await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
3303
+ await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
2788
3304
  } catch (err) {
2789
- if (journal && existsSync5(path6.join(root, JOURNAL))) {
3305
+ if (journal && existsSync8(path8.join(root, JOURNAL))) {
2790
3306
  try {
2791
3307
  await rollback(root, journal);
2792
3308
  } catch (recoveryError) {
2793
- throw new Error(`replacement failed and recovery is pending in ${path6.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
3309
+ throw new Error(`replacement failed and recovery is pending in ${path8.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2794
3310
  }
2795
3311
  await cleanup(root, journal);
2796
- await unlink(path6.join(root, JOURNAL));
3312
+ await unlink(path8.join(root, JOURNAL));
2797
3313
  }
2798
3314
  await rm3(stage, RM);
2799
3315
  throw err;
2800
3316
  }
2801
3317
  await cleanup(root, journal);
2802
- await unlink(path6.join(root, JOURNAL));
3318
+ await unlink(path8.join(root, JOURNAL));
2803
3319
  }
2804
3320
 
2805
3321
  // src/xml/chars.ts
@@ -2826,7 +3342,7 @@ function forbiddenXmlChars(config) {
2826
3342
  async function forbiddenInFiles(root) {
2827
3343
  const out = [];
2828
3344
  for (const file of await treeFiles(root)) {
2829
- for (const p of positions(await readFile5(path7.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
3345
+ for (const p of positions(await readFile5(path9.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
2830
3346
  }
2831
3347
  return out;
2832
3348
  }
@@ -2846,43 +3362,64 @@ async function xmlSafetyProblem(config, treeRoot) {
2846
3362
  var engine = createExplodeEngine();
2847
3363
  var xml = new XmlConfigAdapter();
2848
3364
  var VERSION = createRequire(import.meta.url)("../package.json").version;
2849
- var CliError = class extends Error {
3365
+ var CliError = class extends ReasonError {
2850
3366
  };
2851
- function fail(message) {
2852
- throw new CliError(message);
3367
+ function fail(message, reason) {
3368
+ throw new CliError(message, reason);
2853
3369
  }
2854
3370
  var errorExitCode = 1;
2855
3371
  var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
2856
- function resolveClientConfig(flags) {
2857
- const host = flags.host ?? process.env.MIRTH_HOST;
2858
- const portStr = flags.port ?? process.env.MIRTH_PORT;
2859
- const username = flags.user ?? process.env.MIRTH_USER;
2860
- const password = flags.pass ?? process.env.MIRTH_PASS;
2861
- if (!host) fail("no server host (pass --host or set MIRTH_HOST)");
2862
- if (!portStr) fail("no server port (pass --port or set MIRTH_PORT)");
2863
- if (!username) fail("no username (pass --user or set MIRTH_USER)");
2864
- if (password == null) fail("no password (pass --pass or set MIRTH_PASS)");
2865
- const port = Number(portStr);
2866
- if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);
3372
+ function addConnectionFlags(cmd) {
3373
+ return cmd.option("--profile <name>", "saved connection profile (env MIRTH_PROFILE); see `channelvault profile list`").option("--host <host>", "Mirth server host (env MIRTH_HOST)").option("--port <port>", "Mirth server port (env MIRTH_PORT)").option("--user <user>", "username (env MIRTH_USER)").option("--pass <pass>", "password (env MIRTH_PASS)").option("--tls-fingerprint <sha256>", "accept only the server certificate with this SHA-256 fingerprint (env MIRTH_TLS_FINGERPRINT)").option("--insecure", "turn TLS certificate verification off (prefer --tls-fingerprint)", false).option("--no-https", "use http instead of https");
3374
+ }
3375
+ function clientConfigOf(conn) {
2867
3376
  return {
2868
- host,
2869
- port,
2870
- username,
2871
- password,
2872
- https: flags.https !== false,
2873
- disableTlsCheck: flags.insecure === true,
3377
+ host: conn.host,
3378
+ port: conn.port,
3379
+ username: conn.user,
3380
+ password: conn.password,
3381
+ https: conn.https,
3382
+ disableTlsCheck: conn.insecure,
3383
+ ...conn.tlsFingerprint ? { tlsFingerprint: conn.tlsFingerprint } : {},
2874
3384
  // Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).
2875
3385
  includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG)
2876
3386
  };
2877
3387
  }
2878
- function addConnectionFlags(cmd) {
2879
- return cmd.option("--host <host>", "Mirth server host (env MIRTH_HOST)").option("--port <port>", "Mirth server port (env MIRTH_PORT)").option("--user <user>", "username (env MIRTH_USER)").option("--pass <pass>", "password (env MIRTH_PASS)").option("--insecure", "allow self-signed TLS certificates", false).option("--no-https", "use http instead of https");
3388
+ var activeConnection;
3389
+ var loadedProfiles = {};
3390
+ async function selectConnection(root, flags, opts = {}) {
3391
+ loadedProfiles = await loadProfiles();
3392
+ const meta = root ? await readMeta(root) : null;
3393
+ const conn = resolveConnection({
3394
+ flags,
3395
+ env: process.env,
3396
+ profiles: loadedProfiles,
3397
+ credentials: await readCredentials(),
3398
+ ...meta?.serverId ? { treeServerId: meta.serverId } : {},
3399
+ write: opts.write === true,
3400
+ yes: flags.yes === true,
3401
+ explicit: opts.explicit === true
3402
+ });
3403
+ rememberSecret(conn.password, { stdout: true });
3404
+ activeConnection = conn;
3405
+ return conn;
2880
3406
  }
2881
- async function withClient(flags, fn) {
2882
- const client = createMirthClient(resolveClientConfig(flags));
3407
+ function targetOf2(conn) {
3408
+ return conn.profile ? `${urlOf(conn)} (profile ${conn.profile})` : urlOf(conn);
3409
+ }
3410
+ async function withClient(conn, fn, opts = {}) {
3411
+ const client = createMirthClient(clientConfigOf(conn));
2883
3412
  try {
2884
3413
  await client.login();
2885
- return await fn(client);
3414
+ const serverId = await client.getServerId();
3415
+ if (conn.serverId && serverId !== conn.serverId) {
3416
+ fail(`profile ${conn.profile} is installation ${conn.serverId}, but ${urlOf(conn)} answered as installation ${serverId}; nothing was done. If the server was reinstalled, check it with the administrator and update the profile`, "server-mismatch");
3417
+ }
3418
+ const owner = conn.source === "env" ? profileOwning(loadedProfiles, serverId) : void 0;
3419
+ if (owner) fail(`MIRTH_HOST reaches installation ${serverId}, which is profile ${owner}; use --profile ${owner}, or unset MIRTH_HOST`, "env-shadowed");
3420
+ if (!opts.quiet) process.stderr.write(`${describeConnection(conn, serverId, opts.envFile)}
3421
+ `);
3422
+ return await fn(client, serverId);
2886
3423
  } finally {
2887
3424
  await client.logout().catch(() => void 0);
2888
3425
  await client.close().catch(() => void 0);
@@ -2899,7 +3436,7 @@ function addBackupDirFlags(cmd) {
2899
3436
  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})`);
2900
3437
  }
2901
3438
  function backupDirOf(flags) {
2902
- return path8.resolve(flags.backupDir ?? defaultBackupDir());
3439
+ return path10.resolve(flags.backupDir ?? defaultBackupDir());
2903
3440
  }
2904
3441
  function keepOf(flags) {
2905
3442
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -2907,9 +3444,8 @@ function keepOf(flags) {
2907
3444
  if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);
2908
3445
  return n;
2909
3446
  }
2910
- function serverNameOf(config, flags) {
2911
- const cfg = resolveClientConfig(flags);
2912
- return backupName(config, `${cfg.host}-${cfg.port}`);
3447
+ function serverNameOf(config, conn) {
3448
+ return backupName(config, `${conn.host}-${conn.port}`);
2913
3449
  }
2914
3450
  function parseBackup(text, where) {
2915
3451
  try {
@@ -2918,61 +3454,61 @@ function parseBackup(text, where) {
2918
3454
  fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);
2919
3455
  }
2920
3456
  }
2921
- async function saveServerBackup(client, text, flags, protect) {
3457
+ async function saveServerBackup(client, text, conn, flags, protect) {
2922
3458
  const config = parseBackup(text, "the server configuration");
2923
- const origin = { serverId: await client.getServerId(), host: hostOf(flags) };
2924
- const file = await saveBackup(backupDirOf(flags), serverNameOf(config, flags), text, { keep: keepOf(flags), origin, protect });
3459
+ const origin = { serverId: await client.getServerId(), host: hostOf(conn) };
3460
+ const file = await saveBackup(backupDirOf(flags), serverNameOf(config, conn), text, { keep: keepOf(flags), origin, protect });
2925
3461
  if (gitWouldCommit(file)) {
2926
3462
  process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore
2927
3463
  `);
2928
3464
  }
2929
3465
  return file;
2930
3466
  }
2931
- async function backupBeforePush(client, flags) {
3467
+ async function backupBeforePush(client, conn, flags) {
2932
3468
  if (flags.backup === false) return;
2933
- const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
2934
- process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, flags)})
3469
+ const file = await saveServerBackup(client, await client.getServerConfigurationXml(), conn, flags);
3470
+ process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, conn, flags)})
2935
3471
  `);
2936
- printUndoLimits(flags);
3472
+ printUndoLimits(conn, flags);
2937
3473
  }
2938
3474
  function shellArgument(value) {
2939
3475
  return process.platform === "win32" ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, "'\\''")}'`;
2940
3476
  }
2941
- function undoCommand(file, flags) {
2942
- const cfg = resolveClientConfig(flags);
2943
- const args = [
2944
- "channelvault",
2945
- "restore",
2946
- shellArgument(file),
2947
- "--host",
2948
- shellArgument(cfg.host),
2949
- "--port",
2950
- String(cfg.port),
2951
- "--user",
2952
- shellArgument(cfg.username),
2953
- "--backup-dir",
2954
- shellArgument(backupDirOf(flags))
2955
- ];
2956
- if (cfg.https === false) args.push("--no-https");
2957
- if (cfg.disableTlsCheck) args.push("--insecure");
3477
+ function undoCommand(file, conn, flags) {
3478
+ const args = ["channelvault", "restore", shellArgument(file)];
3479
+ if (conn.profile) {
3480
+ args.push("--profile", shellArgument(conn.profile));
3481
+ } else {
3482
+ args.push("--host", shellArgument(conn.host), "--port", String(conn.port), "--user", shellArgument(conn.user));
3483
+ if (!conn.https) args.push("--no-https");
3484
+ if (conn.tlsFingerprint) args.push("--tls-fingerprint", conn.tlsFingerprint);
3485
+ else if (conn.insecure) args.push("--insecure");
3486
+ }
3487
+ args.push("--backup-dir", shellArgument(backupDirOf(flags)));
2958
3488
  if (flags.overwriteConfigMap) args.push("--overwrite-config-map");
2959
3489
  return args.join(" ");
2960
3490
  }
2961
- function printUndoLimits(flags) {
2962
- if (flags.pass !== void 0) process.stdout.write("undo authentication: supply this server's password through MIRTH_PASS; it is omitted from the command\n");
3491
+ function printUndoLimits(conn, flags) {
3492
+ if (conn.passwordSource === "--pass") process.stdout.write("undo authentication: supply this server's password through MIRTH_PASS; it is omitted from the command\n");
2963
3493
  if (flags.deploy) process.stdout.write("the undo restores saved configuration; runtime deployment state is not in the backup. Review targeted redeployment separately\n");
2964
3494
  }
2965
- function hostOf(flags) {
2966
- const cfg = resolveClientConfig(flags);
2967
- return `${cfg.host}:${cfg.port}`;
3495
+ function hostOf(conn) {
3496
+ return `${conn.host}:${conn.port}`;
2968
3497
  }
2969
- async function ask(question) {
2970
- const rl = createInterface({ input: process.stdin, output: process.stdout });
3498
+ async function ask(question, opts = {}) {
3499
+ let output = process.stdout;
3500
+ if (opts.secret) {
3501
+ process.stdout.write(question);
3502
+ output = new Writable({ write: (_chunk, _enc, done) => done() });
3503
+ }
3504
+ const rl = createInterface({ input: process.stdin, output, terminal: opts.secret ? Boolean(process.stdin.isTTY) : void 0 });
2971
3505
  const controller = new AbortController();
2972
3506
  rl.once("close", () => controller.abort());
2973
3507
  rl.once("SIGINT", () => controller.abort());
2974
3508
  try {
2975
- return (await rl.question(question, { signal: controller.signal })).trim();
3509
+ const answer = await rl.question(opts.secret ? "" : question, { signal: controller.signal });
3510
+ if (opts.secret) process.stdout.write("\n");
3511
+ return opts.secret ? answer : answer.trim();
2976
3512
  } catch (err) {
2977
3513
  if (controller.signal.aborted) fail("confirmation interrupted; nothing was changed");
2978
3514
  throw err;
@@ -3005,6 +3541,31 @@ function summarize(config) {
3005
3541
  codeTemplates
3006
3542
  };
3007
3543
  }
3544
+ async function recordConfigMapBaseline(serverId, baseline) {
3545
+ if (!serverId) return;
3546
+ try {
3547
+ await writeConfigMapBaseline(serverId, baseline);
3548
+ } catch (err) {
3549
+ 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
3550
+ `);
3551
+ }
3552
+ }
3553
+ async function readMeta(root) {
3554
+ const metaPath = path10.join(root, "channelvault.json");
3555
+ if (!existsSync9(metaPath)) return null;
3556
+ let meta;
3557
+ try {
3558
+ meta = await readJson(metaPath);
3559
+ } catch (err) {
3560
+ meta = err;
3561
+ }
3562
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
3563
+ fail(
3564
+ `${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ""}; nothing was written. Restore it (for example \`git checkout -- channelvault.json\`) and retry.`
3565
+ );
3566
+ }
3567
+ return meta;
3568
+ }
3008
3569
  async function writeMeta(root, source, config, previous, serverId, resources = resourceIds(config)) {
3009
3570
  const meta = {
3010
3571
  tool: "channelvault",
@@ -3016,12 +3577,33 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
3016
3577
  resources,
3017
3578
  serverId
3018
3579
  };
3019
- const file = path8.join(root, "channelvault.json");
3580
+ const file = path10.join(root, "channelvault.json");
3020
3581
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
3021
3582
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
3022
3583
  }
3023
- function envFilePath(root, flags) {
3024
- return flags.dotenv ? path8.resolve(flags.dotenv) : path8.join(root, ".env");
3584
+ async function envFileFor(root, flags, conn) {
3585
+ if (flags.dotenv) return path10.resolve(flags.dotenv);
3586
+ const local = path10.join(root, ".env");
3587
+ if (!conn?.dotenv) return local;
3588
+ if (!existsSync9(local) || samePath(await canonical(local), await canonical(conn.dotenv))) {
3589
+ await assertNoSwapPending(conn.dotenv);
3590
+ return conn.dotenv;
3591
+ }
3592
+ 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");
3593
+ }
3594
+ async function assertNoSwapPending(file) {
3595
+ const dir = path10.dirname(file);
3596
+ if (!existsSync9(dir)) return;
3597
+ const prefix = `${path10.basename(file)}.channelvault-`;
3598
+ const pending = (await readdir6(dir)).filter((n) => n.startsWith(prefix) && /\.(next|previous)$/.test(n));
3599
+ if (pending.length > 0) {
3600
+ 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");
3601
+ }
3602
+ }
3603
+ async function recoveryCandidates(root, flags) {
3604
+ if (flags.dotenv) return [path10.resolve(flags.dotenv)];
3605
+ const dotenvs = Object.values(await loadProfiles()).flatMap((p) => p.dotenv ? [p.dotenv] : []);
3606
+ return [path10.join(root, ".env"), ...dotenvs];
3025
3607
  }
3026
3608
  async function loadEnv(file) {
3027
3609
  return { ...await readEnvFile(file), ...process.env };
@@ -3033,26 +3615,47 @@ function addExtractFlag(cmd) {
3033
3615
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
3034
3616
  }
3035
3617
  async function existingTree(root) {
3036
- return existsSync6(path8.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3618
+ return existsSync9(path10.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3037
3619
  }
3038
- async function renderedTree(root, flags) {
3620
+ async function renderedTree(root, envFile) {
3039
3621
  const tree = await engine.implode({ root });
3040
- const env = await loadEnv(envFilePath(root, flags));
3622
+ const env = await loadEnv(envFile);
3041
3623
  rememberSecrets(tree, env);
3042
3624
  return render(tree, env);
3043
3625
  }
3044
3626
  var knownSecrets = /* @__PURE__ */ new Set();
3627
+ var everywhereSecrets = /* @__PURE__ */ new Set();
3628
+ function rememberSecret(value, opts = {}) {
3629
+ if (value === void 0 || value.length < 4) return;
3630
+ knownSecrets.add(value);
3631
+ if (opts.stdout && value.length >= 8) everywhereSecrets.add(value);
3632
+ }
3045
3633
  function rememberSecrets(tree, env) {
3046
- mapLeaves(tree, (value) => {
3047
- for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) {
3048
- const secret = env[m[1]];
3049
- if (secret !== void 0 && secret.length >= 4) knownSecrets.add(secret);
3050
- }
3051
- return value;
3634
+ for (const name of placeholderNames(tree)) rememberSecret(env[name]);
3635
+ }
3636
+ function assertEnvComplete(tree, server, env, envFile, conn) {
3637
+ const { compared, treeOnly } = placeholderUse(tree, server);
3638
+ const unset = (names) => [...names].filter((name) => env[name] === void 0).sort();
3639
+ const missing = unset(compared);
3640
+ if (missing.length > 0) {
3641
+ const fix = conn.dotenv && samePath(envFile, conn.dotenv) ? `set them in profile ${conn.profile}'s env file, or pass --dotenv <file>` : `pass --dotenv <file>, or ${conn.profile ? `set profile ${conn.profile}'s dotenv` : "use a connection profile with a dotenv"}`;
3642
+ const what = `no value for ${missing.join(", ")}, so those secrets can't be compared`;
3643
+ if (!existsSync9(envFile)) fail(`there is no env file at ${envFile}: ${what}; ${fix}`, "env-missing");
3644
+ fail(`${envFile} has ${what}; add them, or ${fix}`, "env-incomplete");
3645
+ }
3646
+ return unset(treeOnly);
3647
+ }
3648
+ for (const stream of [process.stdout, process.stderr]) {
3649
+ const write = stream.write.bind(stream);
3650
+ stream.write = ((chunk, ...rest) => {
3651
+ if (everywhereSecrets.size === 0) return write(chunk, ...rest);
3652
+ if (typeof chunk === "string") return write(scrub(chunk, everywhereSecrets), ...rest);
3653
+ if (Buffer.isBuffer(chunk)) return write(Buffer.from(scrub(chunk.toString("utf8"), everywhereSecrets), "utf8"), ...rest);
3654
+ return write(chunk, ...rest);
3052
3655
  });
3053
3656
  }
3054
- function scrub(text) {
3055
- const forms = [...knownSecrets].flatMap((s) => [
3657
+ function scrub(text, secrets = knownSecrets) {
3658
+ const forms = [...secrets].flatMap((s) => [
3056
3659
  s,
3057
3660
  JSON.stringify(s).slice(1, -1),
3058
3661
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;"),
@@ -3062,13 +3665,12 @@ function scrub(text) {
3062
3665
  }
3063
3666
  var ALLOW_FILE = "channelvault.allow.json";
3064
3667
  async function readAllow(root) {
3065
- const file = path8.join(root, ALLOW_FILE);
3066
- if (!existsSync6(file)) return [];
3668
+ const file = path10.join(root, ALLOW_FILE);
3669
+ if (!existsSync9(file)) return [];
3067
3670
  const parsed = await readJson(file);
3068
3671
  return parsed.ignore ?? [];
3069
3672
  }
3070
- async function writeTree(root, fetched, source, flags, serverId) {
3071
- const envFile = envFilePath(root, flags);
3673
+ async function writeTree(root, fetched, source, flags, envFile, serverId) {
3072
3674
  const previousMeta = await preflightTree(root, envFile);
3073
3675
  const env = await loadEnv(envFile);
3074
3676
  const templated = templatize(fetched, await existingTree(root), env);
@@ -3088,30 +3690,31 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3088
3690
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
3089
3691
  rememberSecrets(config, { ...env, ...envUpdates });
3090
3692
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3091
- const rel = path8.relative(root, envFile);
3092
- const envInTree = !rel.startsWith("..") && !path8.isAbsolute(rel);
3693
+ const rel = path10.relative(root, envFile);
3694
+ const envInTree = !rel.startsWith("..") && !path10.isAbsolute(rel);
3093
3695
  let backup = null;
3094
3696
  await replaceTree(root, envFile, async (next) => {
3095
3697
  await engine.explode(config, { root: next });
3096
3698
  await writeMeta(next, source, fetched, previousMeta, serverId);
3097
3699
  if (Object.keys(envUpdates).length > 0) {
3098
- const history = path8.join(root, ".secrets");
3099
- if (existsSync6(history)) {
3100
- if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3101
- await cp(history, path8.join(next, ".secrets"), { recursive: true });
3700
+ const history = path10.join(root, ".secrets");
3701
+ if (existsSync9(history)) {
3702
+ if ((await lstat4(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3703
+ await cp(history, path10.join(next, ".secrets"), { recursive: true });
3102
3704
  }
3103
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path8.join(next, ".secrets"));
3104
- if (stagedBackup) backup = path8.join(root, ".secrets", path8.basename(stagedBackup));
3705
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path10.join(next, ".secrets"));
3706
+ if (stagedBackup) backup = path10.join(root, ".secrets", path10.basename(stagedBackup));
3105
3707
  if (backup || envInTree) {
3106
- const ignore = path8.join(root, ".gitignore");
3107
- if (existsSync6(ignore)) await writeFile6(path8.join(next, ".gitignore"), await readFile6(ignore));
3708
+ const ignore = path10.join(root, ".gitignore");
3709
+ if (existsSync9(ignore)) await writeFile6(path10.join(next, ".gitignore"), await readFile6(ignore));
3108
3710
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3109
3711
  }
3110
- const stagedEnv = path8.join(next, ".env");
3111
- if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3712
+ const stagedEnv = path10.join(next, ".env");
3713
+ if (existsSync9(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3112
3714
  await updateEnvFile(stagedEnv, envUpdates);
3113
3715
  }
3114
3716
  });
3717
+ await recordConfigMapBaseline(serverId, configMapBaseline(fetched));
3115
3718
  if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
3116
3719
  `);
3117
3720
  const updated = Object.keys(envUpdates).length;
@@ -3125,48 +3728,24 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3125
3728
  process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
3126
3729
  `);
3127
3730
  }
3128
- if (existsSync6(envFile) && gitWouldCommit(envFile)) {
3731
+ if (existsSync9(envFile) && gitWouldCommit(envFile)) {
3129
3732
  process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
3130
3733
  `);
3131
3734
  }
3132
3735
  }
3133
3736
  function gitWouldCommit(file) {
3134
- const r = spawnSync("git", ["check-ignore", "-q", path8.basename(file)], { cwd: path8.dirname(file) });
3737
+ const r = spawnSync2("git", ["check-ignore", "-q", path10.basename(file)], { cwd: path10.dirname(file) });
3135
3738
  return r.status === 1;
3136
3739
  }
3137
- async function resolvedPath(p) {
3138
- const abs = path8.resolve(p);
3139
- let existing = abs;
3140
- while (!existsSync6(existing) && path8.dirname(existing) !== existing) existing = path8.dirname(existing);
3141
- return path8.join(await realpath4(existing), path8.relative(existing, abs));
3142
- }
3143
- function isWithin(child, parent) {
3144
- const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
3145
- const rel = path8.relative(norm(parent), norm(child));
3146
- return rel === "" || rel !== ".." && !rel.startsWith(`..${path8.sep}`) && !path8.isAbsolute(rel);
3147
- }
3148
3740
  async function preflightTree(root, envFile) {
3149
3741
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3150
3742
  const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
3151
- (d) => isWithin(path8.resolve(envFile), path8.resolve(root, d)) || isWithin(realEnv, path8.join(realRoot, d))
3743
+ (d) => isWithin(path10.resolve(envFile), path10.resolve(root, d)) || isWithin(realEnv, path10.join(realRoot, d))
3152
3744
  );
3153
3745
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3154
- const metaPath = path8.join(root, "channelvault.json");
3155
- if (existsSync6(metaPath)) {
3156
- let meta;
3157
- try {
3158
- meta = await readJson(metaPath);
3159
- } catch (err) {
3160
- meta = err;
3161
- }
3162
- if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
3163
- fail(
3164
- `${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ""}; nothing was written. Restore it (for example \`git checkout -- channelvault.json\`) and retry.`
3165
- );
3166
- }
3167
- return meta;
3168
- }
3169
- const foreign = MANAGED_DIRS.filter((d) => existsSync6(path8.join(root, d)));
3746
+ const meta = await readMeta(root);
3747
+ if (meta) return meta;
3748
+ const foreign = MANAGED_DIRS.filter((d) => existsSync9(path10.join(root, d)));
3170
3749
  if (foreign.length > 0) {
3171
3750
  fail(
3172
3751
  `${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).`
@@ -3175,16 +3754,14 @@ async function preflightTree(root, envFile) {
3175
3754
  return null;
3176
3755
  }
3177
3756
  function assertTree(root) {
3178
- if (!existsSync6(path8.join(root, "server", "configuration.json"))) {
3757
+ if (!existsSync9(path10.join(root, "server", "configuration.json"))) {
3179
3758
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3180
3759
  }
3181
3760
  }
3182
3761
  async function readTreeOrigin(root) {
3183
- const metaPath = path8.join(root, "channelvault.json");
3184
- if (!existsSync6(metaPath)) return "unknown";
3185
3762
  try {
3186
- const meta = await readJson(metaPath);
3187
- if (typeof meta.source === "string") {
3763
+ const meta = await readMeta(root);
3764
+ if (typeof meta?.source === "string") {
3188
3765
  if (meta.source.startsWith("file:")) return "xml";
3189
3766
  if (/^https?:\/\//i.test(meta.source)) return "live";
3190
3767
  }
@@ -3209,39 +3786,44 @@ function collect(value, previous) {
3209
3786
  return [...previous ?? [], value];
3210
3787
  }
3211
3788
  async function bindingProblems(root, serverId) {
3212
- const file = path8.join(root, "channelvault.json");
3213
- const meta = existsSync6(file) ? await readJson(file) : null;
3789
+ const meta = await readMeta(root);
3214
3790
  if (meta?.serverId === serverId) return [];
3215
3791
  return [`this tree's baseline belongs to ${meta?.serverId ? `installation ${meta.serverId}` : "an unknown installation"}, not the target (${serverId}); pull the target and merge your edits, or review with 'adopt <dir> --plan-only' and run 'adopt <dir>' to establish its baseline; --force does not bypass installation binding`];
3216
3792
  }
3217
3793
  async function xmlProblems(root, config) {
3218
- const problem = await xmlSafetyProblem(config, root);
3219
- return problem ? [problem] : [];
3794
+ const problem2 = await xmlSafetyProblem(config, root);
3795
+ return problem2 ? [problem2] : [];
3220
3796
  }
3221
3797
  async function assertBinding(client, root) {
3222
3798
  const problems = await bindingProblems(root, await client.getServerId());
3223
3799
  if (problems.length) fail(problems.join("\n"));
3224
3800
  }
3225
3801
  async function readKnown(root) {
3226
- const metaPath = path8.join(root, "channelvault.json");
3227
- if (!existsSync6(metaPath)) return void 0;
3228
- return knownFrom((await readJson(metaPath)).resources);
3802
+ const meta = await readMeta(root);
3803
+ return meta ? knownFrom(meta.resources) : void 0;
3229
3804
  }
3230
3805
  async function writeKnown(root, known) {
3231
- const metaPath = path8.join(root, "channelvault.json");
3232
- if (!existsSync6(metaPath)) return;
3233
- const meta = await readJson(metaPath);
3234
- if (!meta.resources) return;
3806
+ const meta = await readMeta(root);
3807
+ if (!meta?.resources) return;
3235
3808
  meta.resources = known;
3236
- await writeFile6(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf8");
3809
+ await writeFile6(path10.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
3237
3810
  }
3238
3811
  function printNameChange(incoming, current) {
3239
3812
  const [to, from] = [configuredName(incoming), configuredName(current)];
3240
3813
  if (to !== from) process.stdout.write(`server name changes: ${from || "(none)"} -> ${to || "(none)"}
3241
3814
  `);
3242
3815
  }
3816
+ function withConfigMap(plan, map) {
3817
+ return { ...plan, changes: [...map.changes, ...plan.changes], conflicts: [...map.conflicts, ...plan.conflicts] };
3818
+ }
3243
3819
  function printChanges(plan) {
3244
- const kindLabel = { channel: "channel", library: "library", codeTemplate: "code template", globalScripts: "" };
3820
+ const kindLabel = {
3821
+ channel: "channel",
3822
+ library: "library",
3823
+ codeTemplate: "code template",
3824
+ globalScripts: "",
3825
+ configMapKey: "configuration-map key"
3826
+ };
3245
3827
  for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}
3246
3828
  `);
3247
3829
  }
@@ -3256,7 +3838,7 @@ pull (and merge) first, or pass --force to overwrite the server's version`
3256
3838
  }
3257
3839
  const deletes = plan.changes.filter((c) => c.op === "delete").length;
3258
3840
  if (deletes > 0 && !flags.allowDeletes) {
3259
- problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow with --channel/--library`);
3841
+ problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow the push`);
3260
3842
  }
3261
3843
  return problems;
3262
3844
  }
@@ -3270,12 +3852,13 @@ function wholeServerProblems(plan, flags) {
3270
3852
  if (plan.conflicts.length > 0 && !flags.force) problems.push(...planProblems({ ...plan, changes: [] }, flags));
3271
3853
  return problems;
3272
3854
  }
3273
- function reportPlanOnly(flags, plan, problems, extra) {
3855
+ function reportPlanOnly(flags, plan, problems, live, extra) {
3274
3856
  if (flags.json) {
3275
3857
  writeJson2({
3276
3858
  target: extra.target,
3277
3859
  mode: extra.mode,
3278
- ...extra.serverId ? { serverId: extra.serverId } : {},
3860
+ serverId: live.serverId,
3861
+ connection: connectionJson(live.conn, live.serverId, live.envFile),
3279
3862
  changes: plan.changes,
3280
3863
  conflicts: plan.conflicts,
3281
3864
  serverOnly: plan.serverOnly,
@@ -3289,11 +3872,55 @@ function reportPlanOnly(flags, plan, problems, extra) {
3289
3872
  `);
3290
3873
  process.stdout.write("plan only: nothing was changed\n");
3291
3874
  }
3292
- async function scopedPush(client, root, local, scope, target, flags) {
3875
+ var mapKeyLabel = (key) => `configuration-map key "${key}"`;
3876
+ async function pushConfigMapKeys(client, local, planned, named, changed, baseline, serverId, flags) {
3877
+ const current = await client.getServerConfiguration();
3878
+ const moved = configMapMoved(named, planned, current);
3879
+ if (moved.length > 0 && !flags.force) {
3880
+ 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`);
3881
+ }
3882
+ try {
3883
+ await client.putConfigurationMap(mergeConfigMap(current, local, changed));
3884
+ } catch (err) {
3885
+ fail(`saving the configuration map failed; nothing else was pushed: ${err instanceof Error ? err.message : String(err)}`);
3886
+ }
3887
+ let after;
3888
+ try {
3889
+ after = await client.getServerConfiguration();
3890
+ } catch (err) {
3891
+ 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)}`);
3892
+ }
3893
+ const tree = new Map(configMapOf(local).map((e) => [configMapKeyOf(e), e]));
3894
+ const saved = new Map(configMapOf(after).map((e) => [configMapKeyOf(e), e]));
3895
+ const wrong = changed.filter((k) => !sameEntry(tree.get(k), saved.get(k)));
3896
+ if (wrong.length > 0) {
3897
+ 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`);
3898
+ }
3899
+ const others = otherDifferingKeys(current, after, changed);
3900
+ if (others.length > 0) {
3901
+ 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`);
3902
+ }
3903
+ const next = baselineAfterPush(baseline, after, changed);
3904
+ if (next) await recordConfigMapBaseline(serverId, next);
3905
+ process.stdout.write(`saved ${changed.length} configuration-map key(s): ${changed.join(", ")}
3906
+ `);
3907
+ }
3908
+ async function scopedPush(client, root, local, scope, target, flags, live) {
3293
3909
  const remote = await client.getServerConfiguration();
3294
3910
  const known = await readKnown(root);
3295
3911
  const plan = planPush(local, remote, scope, known);
3296
- const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3912
+ const mapKeys = flags.configMapKey ?? [];
3913
+ const mapBaseline = mapKeys.length > 0 ? await readConfigMapBaseline(live.serverId) : void 0;
3914
+ let mapPlan = { changes: [], conflicts: [], unchanged: [] };
3915
+ try {
3916
+ if (mapKeys.length > 0) mapPlan = planConfigMap(local, remote, mapKeys, mapBaseline);
3917
+ } catch (err) {
3918
+ if (err instanceof UnknownConfigMapKey) fail(err.message, "config-map-key-unknown");
3919
+ throw err;
3920
+ }
3921
+ const mapChanged = mapPlan.changes.map((c) => c.id);
3922
+ const shown = withConfigMap(plan, mapPlan);
3923
+ const problems = [...await bindingProblems(root, live.serverId), ...planProblems(shown, flags), ...await xmlProblems(root, local)];
3297
3924
  const names = new Map(
3298
3925
  [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
3299
3926
  );
@@ -3303,16 +3930,16 @@ async function scopedPush(client, root, local, scope, target, flags) {
3303
3930
  const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
3304
3931
  if (flags.planOnly && flags.json) {
3305
3932
  const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
3306
- reportPlanOnly(flags, plan, problems, { target, mode: "scoped", ...redeploy });
3933
+ reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped", ...redeploy });
3307
3934
  return;
3308
3935
  }
3309
- if (plan.changes.length === 0) {
3936
+ if (shown.changes.length === 0) {
3310
3937
  process.stdout.write(`nothing to push: ${target} already matches the tree
3311
3938
  `);
3312
3939
  } else {
3313
3940
  process.stdout.write(`Push to ${target}:
3314
3941
  `);
3315
- printChanges(plan);
3942
+ printChanges(shown);
3316
3943
  if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf2).join(", ")}
3317
3944
  `);
3318
3945
  if (notDeployed.length > 0) {
@@ -3321,7 +3948,15 @@ async function scopedPush(client, root, local, scope, target, flags) {
3321
3948
  }
3322
3949
  }
3323
3950
  if (plan.notPushed.length > 0) {
3324
- process.stdout.write(`not pushed (differs; use --whole-server): ${plan.notPushed.join(", ")}
3951
+ const mapHint = plan.notPushed.includes("configurationMap") ? ", or --config-map-key for named configuration-map keys" : "";
3952
+ process.stdout.write(`not pushed (differs; use --whole-server${mapHint}): ${plan.notPushed.join(", ")}
3953
+ `);
3954
+ }
3955
+ if (mapPlan.unchanged.length > 0) process.stdout.write(`configuration-map keys already as in the tree: ${mapPlan.unchanged.join(", ")}
3956
+ `);
3957
+ if (mapKeys.length > 0) {
3958
+ const others = otherDifferingKeys(local, remote, mapKeys);
3959
+ if (others.length > 0) process.stdout.write(`other configuration-map keys differ (not pushed): ${others.join(", ")}
3325
3960
  `);
3326
3961
  }
3327
3962
  if (plan.serverOnly.length > 0) {
@@ -3329,29 +3964,30 @@ async function scopedPush(client, root, local, scope, target, flags) {
3329
3964
  `);
3330
3965
  }
3331
3966
  if (flags.planOnly) {
3332
- reportPlanOnly(flags, plan, problems, { target, mode: "scoped" });
3967
+ reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped" });
3333
3968
  return;
3334
3969
  }
3335
3970
  if (problems.length > 0) fail(problems.join("\n"));
3336
- if (plan.changes.length === 0) return;
3971
+ if (shown.changes.length === 0) return;
3337
3972
  if (!flags.yes && !await confirm("Continue?")) {
3338
3973
  process.stdout.write("aborted.\n");
3339
3974
  return;
3340
3975
  }
3341
3976
  const fresh = await client.getServerConfiguration();
3342
- const moved = changedSince(plan, remote, fresh);
3977
+ const moved = [...configMapMoved(mapKeys, remote, fresh).map(mapKeyLabel), ...changedSince(plan, remote, fresh)];
3343
3978
  if (moved.length > 0 && !flags.force) {
3344
3979
  fail(`changed on the server while this push was being confirmed:
3345
3980
  ${moved.join("\n ")}
3346
3981
  pull and try again, or pass --force`);
3347
3982
  }
3348
- await backupBeforePush(client, flags);
3983
+ await backupBeforePush(client, live.conn, { ...flags, overwriteConfigMap: mapChanged.length > 0 });
3349
3984
  const afterBackup = await client.getServerConfiguration();
3350
- const changedDuringBackup = changedSince(plan, fresh, afterBackup);
3985
+ const changedDuringBackup = [...configMapMoved(mapKeys, fresh, afterBackup).map(mapKeyLabel), ...changedSince(plan, fresh, afterBackup)];
3351
3986
  if (!flags.force && changedDuringBackup.length) {
3352
3987
  fail(`changed on the server during backup: ${changedDuringBackup.join(", ")}; pull and try again`);
3353
3988
  }
3354
3989
  await assertBinding(client, root);
3990
+ if (mapChanged.length > 0) await pushConfigMapKeys(client, local, afterBackup, mapKeys, mapChanged, mapBaseline, live.serverId, flags);
3355
3991
  const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
3356
3992
  let baselineError;
3357
3993
  let changedAgain = [];
@@ -3385,13 +4021,13 @@ changed again after saving (pull and review before retrying): ${changedAgain.joi
3385
4021
  if (baselineError) process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(baselineError)}
3386
4022
  `);
3387
4023
  const { change, error } = result.failed;
3388
- fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
4024
+ fail(`applied ${result.applied.length + mapChanged.length} of ${shown.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
3389
4025
  }
3390
4026
  if (changedAgain.length > 0) {
3391
- fail(`applied ${result.applied.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
4027
+ fail(`applied ${result.applied.length + mapChanged.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
3392
4028
  ${baselineError}` : ""}`);
3393
4029
  }
3394
- process.stdout.write(`pushed ${result.applied.length} change(s)
4030
+ process.stdout.write(`pushed ${result.applied.length + mapChanged.length} change(s)
3395
4031
  `);
3396
4032
  if (toDeploy.length > 0) {
3397
4033
  const { deployed: deployed2, skipped, failures } = await deployChannels(client, toDeploy, nameOf2);
@@ -3406,12 +4042,12 @@ ${baselineError}` : ""}`);
3406
4042
  if (baselineError) {
3407
4043
  const note = unverified.length > 0 ? `
3408
4044
  not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3409
- fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
4045
+ fail(`pushed ${result.applied.length + mapChanged.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3410
4046
  }
3411
4047
  printCommitHint(root);
3412
4048
  }
3413
4049
  function printCommitHint(root) {
3414
- const r = spawnSync("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
4050
+ const r = spawnSync2("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
3415
4051
  if (r.status !== 0 || !r.stdout) return;
3416
4052
  const entries = r.stdout.split("\0");
3417
4053
  const files = [];
@@ -3449,13 +4085,13 @@ async function changedAgainSingly(client, applied, local) {
3449
4085
  }
3450
4086
  return { changed, unverified };
3451
4087
  }
3452
- async function wholeServerPush(client, root, local, target, flags) {
4088
+ async function wholeServerPush(client, root, local, target, flags, live) {
3453
4089
  const remote = await client.getServerConfiguration();
3454
4090
  const known = await readKnown(root);
3455
4091
  const plan = planPush(local, remote, {}, known, { wholeReplace: true });
3456
- const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
4092
+ const problems = [...await bindingProblems(root, live.serverId), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
3457
4093
  if (flags.planOnly && flags.json) {
3458
- reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
4094
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
3459
4095
  return;
3460
4096
  }
3461
4097
  const s = summarize(local);
@@ -3476,7 +4112,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3476
4112
  `);
3477
4113
  if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
3478
4114
  if (flags.planOnly) {
3479
- reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
4115
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
3480
4116
  return;
3481
4117
  }
3482
4118
  if (problems.length > 0) fail(problems.join("\n"));
@@ -3492,7 +4128,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3492
4128
  if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some((c) => c.op === "delete"))) {
3493
4129
  fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
3494
4130
  }
3495
- await backupBeforePush(client, flags);
4131
+ await backupBeforePush(client, live.conn, flags);
3496
4132
  const afterBackup = await client.getServerConfiguration();
3497
4133
  if (!sameServerConfig(fresh, afterBackup) && !flags.force) fail("the server changed during backup; pull and try again");
3498
4134
  const finalPlan = planPush(local, afterBackup, {}, known, { wholeReplace: true });
@@ -3516,6 +4152,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3516
4152
  const ids = resourceIds(local);
3517
4153
  await refreshRevisions(root, after, /* @__PURE__ */ new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));
3518
4154
  if (known) await writeKnown(root, resourceIds(after));
4155
+ if (flags.overwriteConfigMap) await recordConfigMapBaseline(live.serverId, configMapBaseline(after));
3519
4156
  process.stdout.write(`pushed ${root} -> ${target}
3520
4157
  `);
3521
4158
  printCommitHint(root);
@@ -3526,8 +4163,8 @@ addExtractFlag(addEnvFlag(
3526
4163
  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")
3527
4164
  )).action(async (backupPath, dir, flags) => {
3528
4165
  const config = xml.parse(await readFile6(backupPath, "utf8"));
3529
- const root = path8.resolve(dir);
3530
- await writeTree(root, config, `file:${path8.resolve(backupPath)}`, flags);
4166
+ const root = path10.resolve(dir);
4167
+ await writeTree(root, config, `file:${path10.resolve(backupPath)}`, flags, await envFileFor(root, flags));
3531
4168
  const s = summarize(config);
3532
4169
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3533
4170
  `);
@@ -3535,28 +4172,32 @@ addExtractFlag(addEnvFlag(
3535
4172
  addEnvFlag(
3536
4173
  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)
3537
4174
  ).action(async (dir, outPath, flags) => {
3538
- const root = path8.resolve(dir);
4175
+ const root = path10.resolve(dir);
3539
4176
  assertTree(root);
3540
- const config = await renderedTree(root, flags);
4177
+ const config = await renderedTree(root, await envFileFor(root, flags));
3541
4178
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3542
4179
  const xmlStr = xml.build(config);
3543
4180
  await writeFile6(outPath, xmlStr, "utf8");
3544
- process.stdout.write(`imploded ${root} -> ${path8.resolve(outPath)}
4181
+ process.stdout.write(`imploded ${root} -> ${path10.resolve(outPath)}
3545
4182
  `);
3546
4183
  });
3547
4184
  addExtractFlag(addEnvFlag(addConnectionFlags(
3548
4185
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3549
4186
  ))).action(async (dir, flags) => {
3550
- const root = path8.resolve(dir);
3551
- await preflightTree(root, envFilePath(root, flags));
3552
- const { config, serverId } = await withClient(flags, async (client) => {
3553
- const serverId2 = await client.getServerId();
4187
+ const root = path10.resolve(dir);
4188
+ const conn = await selectConnection(root, flags);
4189
+ const envFile = await envFileFor(root, flags, conn);
4190
+ if (!isWithin(path10.resolve(envFile), root)) await lockAlso(envFile);
4191
+ const previous = await preflightTree(root, envFile);
4192
+ const { config, serverId } = await withClient(conn, async (client, serverId2) => {
4193
+ if (previous?.serverId && previous.serverId !== serverId2) {
4194
+ fail(`this tree belongs to installation ${previous.serverId}, but ${urlOf(conn)} is installation ${serverId2}; nothing was written. Pull into another directory, or rebind this tree deliberately with 'adopt <dir> --plan-only' and 'adopt <dir>'`, "installation-mismatch");
4195
+ }
3554
4196
  const config2 = await client.getServerConfiguration();
3555
4197
  if (await client.getServerId() !== serverId2) fail("the installation changed while pulling; nothing was written");
3556
4198
  return { config: config2, serverId: serverId2 };
3557
- });
3558
- const cfg = resolveClientConfig(flags);
3559
- await writeTree(root, config, `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`, flags, serverId);
4199
+ }, { envFile });
4200
+ await writeTree(root, config, urlOf(conn), flags, envFile, serverId);
3560
4201
  const s = summarize(config);
3561
4202
  process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3562
4203
  `);
@@ -3564,23 +4205,23 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3564
4205
  addJsonFlag(addEnvFlag(addConnectionFlags(
3565
4206
  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)
3566
4207
  ))).action(async (dir, flags) => {
3567
- const root = path8.resolve(dir);
4208
+ const root = path10.resolve(dir);
3568
4209
  assertTree(root);
3569
- const previous = await preflightTree(root, envFilePath(root, flags));
3570
- const stored = await engine.implode({ root });
3571
- const local = await renderedTree(root, flags);
3572
- await assertCompatibleOrigin(root, local, "live", false);
3573
4210
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
3574
4211
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
3575
- const cfg = resolveClientConfig(flags);
3576
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3577
- await withClient(flags, async (client) => {
3578
- const serverId = await client.getServerId();
4212
+ const conn = await selectConnection(void 0, flags, { write: !flags.planOnly, explicit: true });
4213
+ const envFile = await envFileFor(root, flags, conn);
4214
+ const previous = await preflightTree(root, envFile);
4215
+ const stored = await engine.implode({ root });
4216
+ const local = await renderedTree(root, envFile);
4217
+ await assertCompatibleOrigin(root, local, "live", false);
4218
+ const target = urlOf(conn);
4219
+ await withClient(conn, async (client, serverId) => {
3579
4220
  const remote = await client.getServerConfiguration();
3580
4221
  const adopted = adoptTarget(local, remote);
3581
4222
  const plan = planPush(adopted.config, remote, {}, adopted.known);
3582
4223
  if (!flags.json) {
3583
- process.stdout.write(`Adopt ${target} (installation ${serverId}) as this tree's baseline.
4224
+ process.stdout.write(`Adopt ${targetOf2(conn)} (installation ${serverId}) as this tree's baseline.
3584
4225
  Local content is preserved; the following differences become reviewed edits for a subsequent push:
3585
4226
  `);
3586
4227
  printChanges(plan);
@@ -3590,7 +4231,7 @@ Local content is preserved; the following differences become reviewed edits for
3590
4231
  `);
3591
4232
  }
3592
4233
  if (flags.planOnly) {
3593
- reportPlanOnly(flags, plan, planProblems(plan, {}), { target, mode: "adopt", serverId });
4234
+ reportPlanOnly(flags, plan, planProblems(plan, {}), { conn, serverId, envFile }, { target, mode: "adopt" });
3594
4235
  return;
3595
4236
  }
3596
4237
  if (!flags.yes && !await confirm("Accept this baseline?")) {
@@ -3601,53 +4242,57 @@ Local content is preserved; the following differences become reviewed edits for
3601
4242
  fail("the target changed while adopting; nothing was written. Review the new baseline and try again");
3602
4243
  }
3603
4244
  if (!sameServerConfig(stored, await engine.implode({ root }))) fail("the local tree changed while adopting; nothing was written");
3604
- await replaceTree(root, envFilePath(root, flags), async (next) => {
4245
+ await replaceTree(root, envFile, async (next) => {
3605
4246
  const rebased = adoptTarget(stored, remote);
3606
4247
  await engine.explode(rebased.config, { root: next });
3607
4248
  await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
3608
4249
  });
4250
+ await recordConfigMapBaseline(serverId, configMapBaseline(remote));
3609
4251
  process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
3610
4252
  `);
3611
- });
4253
+ }, { envFile, quiet: flags.json });
3612
4254
  });
3613
4255
  addBackupDirFlags(addEnvFlag(addConnectionFlags(
3614
- 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)
4256
+ 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)
3615
4257
  ))).action(
3616
4258
  async (dir, flags) => {
3617
- if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
3618
- fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
4259
+ if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts || flags.configMapKey)) {
4260
+ fail("--whole-server replaces everything; it cannot be combined with --channel, --library, --global-scripts or --config-map-key");
3619
4261
  }
3620
4262
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
3621
- const root = path8.resolve(dir);
4263
+ const root = path10.resolve(dir);
3622
4264
  assertTree(root);
3623
- const config = await renderedTree(root, flags);
3624
- await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
3625
- const cfg = resolveClientConfig(flags);
3626
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3627
4265
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
3628
4266
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {
3629
4267
  fail("no terminal to confirm on; review with `push --plan-only` or `diff`, and pass --yes");
3630
4268
  }
4269
+ const conn = await selectConnection(root, flags, { write: !flags.planOnly });
4270
+ const envFile = await envFileFor(root, flags, conn);
4271
+ const config = await renderedTree(root, envFile);
4272
+ await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
4273
+ const target = targetOf2(conn);
4274
+ const quiet = flags.json === true;
3631
4275
  if (flags.wholeServer) {
3632
- await withClient(flags, (client) => wholeServerPush(client, root, config, target, flags));
4276
+ await withClient(conn, (client, serverId) => wholeServerPush(client, root, config, target, flags, { conn, serverId, envFile }), { envFile, quiet });
3633
4277
  return;
3634
4278
  }
3635
- const scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
3636
- await withClient(flags, (client) => scopedPush(client, root, config, scope, target, flags));
4279
+ const keysOnly = flags.configMapKey !== void 0 && !flags.channel && !flags.library && !flags.globalScripts;
4280
+ const scope = keysOnly ? { channels: [], libraries: [] } : { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
4281
+ await withClient(conn, (client, serverId) => scopedPush(client, root, config, scope, target, flags, { conn, serverId, envFile }), { envFile, quiet });
3637
4282
  }
3638
4283
  );
3639
4284
  addBackupDirFlags(addConnectionFlags(
3640
4285
  program.command("backup").description("Save the server configuration as <server>-<UTC time>.xml in ~/.channelvault/backups (holds credentials in plain text)").option("--out <file>", "write to this file instead (no rotation)")
3641
4286
  )).action(async (flags) => {
3642
- const cfg = resolveClientConfig(flags);
3643
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3644
- const file = await withClient(flags, async (client) => {
4287
+ const conn = await selectConnection(void 0, flags);
4288
+ const target = targetOf2(conn);
4289
+ const file = await withClient(conn, async (client) => {
3645
4290
  const text = await client.getServerConfigurationXml();
3646
- if (!flags.out) return saveServerBackup(client, text, flags);
3647
- const out = path8.resolve(flags.out);
4291
+ if (!flags.out) return saveServerBackup(client, text, conn, flags);
4292
+ const out = path10.resolve(flags.out);
3648
4293
  parseBackup(text, "the server configuration");
3649
- if (existsSync6(out)) fail(`${out} already exists; choose another name`);
3650
- await mkdir5(path8.dirname(out), { recursive: true });
4294
+ if (existsSync9(out)) fail(`${out} already exists; choose another name`);
4295
+ await mkdir7(path10.dirname(out), { recursive: true });
3651
4296
  await writePrivate(out, text);
3652
4297
  if (gitWouldCommit(out)) {
3653
4298
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -3660,20 +4305,20 @@ addBackupDirFlags(addConnectionFlags(
3660
4305
  });
3661
4306
  async function chooseBackup(dir, file, serverId, target) {
3662
4307
  if (file) {
3663
- const chosen = path8.resolve(file);
3664
- if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
4308
+ const chosen = path10.resolve(file);
4309
+ if (!existsSync9(chosen)) fail(`${chosen} does not exist`);
3665
4310
  return chosen;
3666
4311
  }
3667
4312
  const mine = await backupsOf(dir, serverId);
3668
4313
  if (mine.length === 0) {
3669
4314
  const others = (await originsIn(dir)).map((o) => o.host);
3670
- const legacy = path8.resolve(LEGACY_BACKUP_DIR);
4315
+ const legacy = path10.resolve(LEGACY_BACKUP_DIR);
3671
4316
  const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
3672
4317
  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)}` : ""));
3673
4318
  }
3674
4319
  return mine[mine.length - 1].file;
3675
4320
  }
3676
- async function restoreWithBrokenExport(client, file, flags, target) {
4321
+ async function restoreWithBrokenExport(client, serverId, file, flags, target) {
3677
4322
  try {
3678
4323
  await client.getServerConfigurationXml();
3679
4324
  fail("the server can export its configuration; run restore without --export-broken, which shows a preview and saves an undo backup first");
@@ -3683,7 +4328,6 @@ async function restoreWithBrokenExport(client, file, flags, target) {
3683
4328
  fail(`cannot tell whether the export is broken: ${err instanceof Error ? err.message : String(err)}; --export-broken only proceeds when the server answers its export with HTTP 500`);
3684
4329
  }
3685
4330
  }
3686
- const serverId = await client.getServerId();
3687
4331
  const dir = backupDirOf(flags);
3688
4332
  const chosen = await chooseBackup(dir, file, serverId, target);
3689
4333
  const text = await readFile6(chosen, "utf8");
@@ -3692,7 +4336,7 @@ async function restoreWithBrokenExport(client, file, flags, target) {
3692
4336
  if (unsafe) fail(`${chosen} holds ${unsafe}`);
3693
4337
  const origin = await originOf(dir, chosen);
3694
4338
  if (!origin && !flags.force) {
3695
- fail(`${chosen} is not in ${path8.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
4339
+ 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`);
3696
4340
  }
3697
4341
  if (origin && origin.serverId !== serverId && !flags.force) {
3698
4342
  fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
@@ -3724,13 +4368,13 @@ The server cannot export its configuration, so there is no preview, no undo back
3724
4368
  addBackupDirFlags(addConnectionFlags(
3725
4369
  program.command("restore").description("Replace the entire server configuration with a backup (default: the newest backup of this server)").argument("[file]", "backup XML to restore").option("--deploy", "redeploy all channels afterwards", false).option("--overwrite-config-map", "also replace the configuration map", false).option("--force", "restore a backup taken from another server", false).option("--export-broken", "the server cannot export its configuration (HTTP 500): restore without a preview, undo backup or version check", false).option("-y, --yes", "skip the confirmation prompt", false)
3726
4370
  )).action(async (file, flags) => {
3727
- const cfg = resolveClientConfig(flags);
3728
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3729
4371
  if (!flags.yes && !process.stdin.isTTY) fail("no terminal to confirm on; pass --yes");
4372
+ const conn = await selectConnection(void 0, flags, { write: true });
4373
+ const target = targetOf2(conn);
3730
4374
  const dir = backupDirOf(flags);
3731
- await withClient(flags, async (client) => {
4375
+ await withClient(conn, async (client, serverId) => {
3732
4376
  if (flags.exportBroken) {
3733
- await restoreWithBrokenExport(client, file, flags, target);
4377
+ await restoreWithBrokenExport(client, serverId, file, flags, target);
3734
4378
  return;
3735
4379
  }
3736
4380
  let currentText;
@@ -3740,7 +4384,6 @@ addBackupDirFlags(addConnectionFlags(
3740
4384
  fail(`cannot read the server's current configuration: ${err instanceof Error ? err.message : String(err)}. If its export is broken (for example HTTP 500), restore with --export-broken, which skips the preview and the undo backup`);
3741
4385
  }
3742
4386
  const current = parseBackup(currentText, "the server configuration");
3743
- const serverId = await client.getServerId();
3744
4387
  const chosen = await chooseBackup(dir, file, serverId, target);
3745
4388
  const text = await readFile6(chosen, "utf8");
3746
4389
  const backup = parseBackup(text, chosen);
@@ -3756,7 +4399,7 @@ addBackupDirFlags(addConnectionFlags(
3756
4399
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
3757
4400
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
3758
4401
  }
3759
- process.stderr.write(`warning: ${chosen} is not in ${path8.join(dir, MANIFEST)}, so which server it came from cannot be checked
4402
+ process.stderr.write(`warning: ${chosen} is not in ${path10.join(dir, MANIFEST)}, so which server it came from cannot be checked
3760
4403
  `);
3761
4404
  }
3762
4405
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -3790,10 +4433,10 @@ to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeplo
3790
4433
  if (!sameServerConfig(parseBackup(freshText, "the server configuration"), current)) {
3791
4434
  fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
3792
4435
  }
3793
- const undo = await saveServerBackup(client, freshText, flags, chosen);
3794
- process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, flags)})
4436
+ const undo = await saveServerBackup(client, freshText, conn, flags, chosen);
4437
+ process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, conn, flags)})
3795
4438
  `);
3796
- printUndoLimits(flags);
4439
+ printUndoLimits(conn, flags);
3797
4440
  const afterBackup = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
3798
4441
  if (!sameServerConfig(parseBackup(freshText, "the server configuration"), afterBackup)) {
3799
4442
  fail("the server changed during the undo backup; nothing was restored. Run it again to review the new state");
@@ -3815,14 +4458,25 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3815
4458
  })
3816
4459
  ))).action(async (dir, flags) => {
3817
4460
  errorExitCode = 2;
3818
- const root = path8.resolve(dir);
4461
+ const root = path10.resolve(dir);
3819
4462
  assertTree(root);
3820
- const fetched = await withClient(flags, (client) => client.getServerConfiguration());
4463
+ const conn = await selectConnection(root, flags);
4464
+ const envFile = await envFileFor(root, flags, conn);
4465
+ const treeServerId = (await readMeta(root))?.serverId;
4466
+ const { fetched, serverId } = await withClient(conn, async (client, serverId2) => {
4467
+ if (treeServerId && treeServerId !== serverId2) {
4468
+ fail(`this tree belongs to installation ${treeServerId}, but ${urlOf(conn)} is installation ${serverId2}; choose the server this tree was pulled from`, "installation-mismatch");
4469
+ }
4470
+ return { fetched: await client.getServerConfiguration(), serverId: serverId2 };
4471
+ }, { envFile, quiet: flags.json });
3821
4472
  const tree = await engine.implode({ root });
3822
- const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));
4473
+ const env = await loadEnv(envFile);
4474
+ const unsetTreeOnly = assertEnvComplete(tree, fetched, env, envFile, conn);
4475
+ const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, env);
3823
4476
  const messages = [
3824
4477
  ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
3825
4478
  ...notes,
4479
+ ...unsetTreeOnly.length > 0 ? [`no value yet for ${unsetTreeOnly.join(", ")}, used only by resources the server doesn't have`] : [],
3826
4480
  ...await xmlProblems(root, tree)
3827
4481
  ];
3828
4482
  const allow = await readAllow(root);
@@ -3830,25 +4484,25 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3830
4484
  if (staleRevisions.length > 0) {
3831
4485
  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`);
3832
4486
  }
3833
- const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
3834
- const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
4487
+ const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(tree)))), { mode: "redact", allow });
4488
+ const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(templatedRemote)))), { mode: "redact", allow });
3835
4489
  if (treeView.findings.length > 0) {
3836
4490
  messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);
3837
4491
  }
3838
4492
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
3839
4493
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
3840
4494
  `);
3841
- const tmp = await mkdtemp(path8.join(tmpdir(), "channelvault-diff-"));
4495
+ const tmp = await mkdtemp(path10.join(tmpdir(), "channelvault-diff-"));
3842
4496
  try {
3843
- await engine.explode(treeView.config, { root: path8.join(tmp, "tree") });
3844
- await engine.explode(serverView.config, { root: path8.join(tmp, "server") });
3845
- await mkdir5(path8.join(tmp, ".empty"));
4497
+ await engine.explode(treeView.config, { root: path10.join(tmp, "tree") });
4498
+ await engine.explode(serverView.config, { root: path10.join(tmp, "server") });
4499
+ await mkdir7(path10.join(tmp, ".empty"));
3846
4500
  const chunks = [];
3847
4501
  for (const d of MANAGED_DIRS) {
3848
- const local = existsSync6(path8.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3849
- const server = existsSync6(path8.join(tmp, "server", d)) ? `server/${d}` : ".empty";
4502
+ const local = existsSync9(path10.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
4503
+ const server = existsSync9(path10.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3850
4504
  if (local === ".empty" && server === ".empty") continue;
3851
- const result = spawnSync(
4505
+ const result = spawnSync2(
3852
4506
  "git",
3853
4507
  ["-c", "core.autocrlf=false", "diff", "--no-index", "--no-color", "--ignore-cr-at-eol", local, server],
3854
4508
  { encoding: "utf8", cwd: tmp }
@@ -3868,8 +4522,8 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3868
4522
  const clean = out === "" && secretDrift.length === 0;
3869
4523
  if (!clean) process.exitCode = 1;
3870
4524
  if (flags.json) {
3871
- const files = await changedFiles(path8.join(tmp, "tree"), path8.join(tmp, "server"));
3872
- writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
4525
+ const files = await changedFiles(path10.join(tmp, "tree"), path10.join(tmp, "server"));
4526
+ writeJson2({ clean, serverId, connection: connectionJson(conn, serverId, envFile), files, secretDrift, staleRevisions, notes: messages, patch: out });
3873
4527
  } else if (clean) {
3874
4528
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
3875
4529
  } else {
@@ -3889,27 +4543,29 @@ async function changedFiles(treeDir, serverDir) {
3889
4543
  const files = [];
3890
4544
  for (const p of local) {
3891
4545
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
3892
- else if (await readFile6(path8.join(treeDir, p), "utf8") !== await readFile6(path8.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
4546
+ else if (await readFile6(path10.join(treeDir, p), "utf8") !== await readFile6(path10.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3893
4547
  }
3894
4548
  const localSet = new Set(local);
3895
4549
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
3896
4550
  return files.sort((a, b) => a.path.localeCompare(b.path));
3897
4551
  }
3898
4552
  addJsonFlag(addEnvFlag(
3899
- program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
4553
+ program.command("status").description("Summarize a working tree, and say which connection profile live commands would use").argument("<dir>", "working-tree directory")
3900
4554
  )).action(async (dir, flags) => {
3901
- const root = path8.resolve(dir);
4555
+ const root = path10.resolve(dir);
3902
4556
  assertTree(root);
3903
4557
  const config = await engine.implode({ root });
3904
4558
  const s = summarize(config);
3905
- const metaPath = path8.join(root, "channelvault.json");
3906
- const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
4559
+ const meta = await readMeta(root);
4560
+ const connection = await offlineConnection(meta?.serverId);
3907
4561
  if (flags.json) {
3908
4562
  writeJson2({
3909
4563
  root,
3910
4564
  source: meta?.source ?? null,
3911
4565
  pulledAt: meta?.pulledAt ?? null,
3912
4566
  engineVersion: meta?.engineVersion ?? null,
4567
+ serverId: meta?.serverId ?? null,
4568
+ connection,
3913
4569
  counts: s,
3914
4570
  xmlForbiddenChars: forbiddenXmlChars(config)
3915
4571
  });
@@ -3923,8 +4579,12 @@ addJsonFlag(addEnvFlag(
3923
4579
  process.stdout.write(`pulled: ${meta.pulledAt}
3924
4580
  `);
3925
4581
  process.stdout.write(`engine: ${meta.engineVersion ?? "unknown"}
4582
+ `);
4583
+ if (meta.serverId) process.stdout.write(`server: installation ${meta.serverId}
3926
4584
  `);
3927
4585
  }
4586
+ process.stdout.write(`connect: ${"problem" in connection ? connection.problem : `${connection.profile ? `profile ${connection.profile}` : "no profile"}, ${connection.url} as ${connection.user}, chosen by ${connection.source}${connection.passwordConfigured ? "" : " (no password configured)"}`}
4587
+ `);
3928
4588
  process.stdout.write(
3929
4589
  `channels: ${s.channels}
3930
4590
  channel groups: ${s.channelGroups}
@@ -3933,36 +4593,252 @@ code templates: ${s.codeTemplates}
3933
4593
  `
3934
4594
  );
3935
4595
  });
3936
- var unlock;
4596
+ async function offlineConnection(treeServerId) {
4597
+ try {
4598
+ const profiles = await loadProfiles();
4599
+ const credentials = await readCredentials();
4600
+ const conn = resolveConnection({
4601
+ flags: {},
4602
+ env: process.env,
4603
+ profiles,
4604
+ // Resolve as if every password were set, then report the real state.
4605
+ credentials: Object.fromEntries(Object.keys(profiles).map((n) => [n, ""])),
4606
+ ...treeServerId ? { treeServerId } : {}
4607
+ });
4608
+ const passwordConfigured = conn.profile ? Object.prototype.hasOwnProperty.call(credentials, conn.profile) : true;
4609
+ return { profile: conn.profile ?? null, url: urlOf(conn), user: conn.user, source: conn.source, passwordConfigured };
4610
+ } catch (err) {
4611
+ if (!(err instanceof ReasonError)) throw err;
4612
+ return { problem: `${err.reason ? `[${err.reason}] ` : ""}${err.message}` };
4613
+ }
4614
+ }
4615
+ function needTerminal(what) {
4616
+ if (!process.stdin.isTTY) fail(`${what} asks at a terminal; run it yourself in a terminal (agents cannot)`, "no-terminal");
4617
+ }
4618
+ async function askPassword(prompt) {
4619
+ const password = await ask(prompt, { secret: true });
4620
+ if (password.length < 8) fail("a profile password needs at least 8 characters; nothing was saved", "weak-password");
4621
+ return password;
4622
+ }
4623
+ function connectionOfProfile(name, profile, password) {
4624
+ return {
4625
+ host: profile.host,
4626
+ port: profile.port,
4627
+ user: profile.user,
4628
+ password,
4629
+ https: profile.https !== false,
4630
+ insecure: profile.insecure === true,
4631
+ ...profile.tlsFingerprint ? { tlsFingerprint: profile.tlsFingerprint } : {},
4632
+ source: "profile-flag",
4633
+ passwordSource: "credentials",
4634
+ profile: name,
4635
+ ...profile.serverId ? { serverId: profile.serverId } : {}
4636
+ };
4637
+ }
4638
+ async function loginCheck(conn) {
4639
+ rememberSecret(conn.password, { stdout: true });
4640
+ activeConnection = conn;
4641
+ return withClient(conn, async (_client, serverId) => serverId, { quiet: true });
4642
+ }
4643
+ function existingProfile(profiles, name) {
4644
+ const profile = profiles[name];
4645
+ if (!profile) fail(`no profile named ${name} (${Object.keys(profiles).join(", ") || "none saved"})`, "profile-unknown");
4646
+ return profile;
4647
+ }
4648
+ var profileCommand = program.command("profile").description(`Manage connection profiles (${path10.join("~", ".channelvault", "profiles.json")}; passwords in its credentials file)`);
4649
+ addJsonFlag(profileCommand.command("list").description("List the saved profiles (never their passwords)")).action(async (flags) => {
4650
+ const profiles = await loadProfiles();
4651
+ const credentials = await readCredentials();
4652
+ const rows = Object.entries(profiles).map(([name, p]) => ({
4653
+ name,
4654
+ url: urlOf({ https: p.https !== false, host: p.host, port: p.port }),
4655
+ user: p.user,
4656
+ serverId: p.serverId ?? null,
4657
+ tlsFingerprint: p.tlsFingerprint ?? null,
4658
+ insecure: p.insecure === true,
4659
+ dotenv: p.dotenv ?? null,
4660
+ passwordConfigured: Object.prototype.hasOwnProperty.call(credentials, name)
4661
+ }));
4662
+ if (flags.json) {
4663
+ writeJson2({ profilesFile: profilesFile(), profiles: rows });
4664
+ return;
4665
+ }
4666
+ if (rows.length === 0) {
4667
+ process.stdout.write(`no profiles in ${profilesFile()}; add one at a terminal with: channelvault profile add <name> --host <host> --port <port> --user <user>
4668
+ `);
4669
+ return;
4670
+ }
4671
+ for (const r of rows) {
4672
+ const tls = r.tlsFingerprint ? `pinned ${formatFingerprint(r.tlsFingerprint).slice(0, 11)}\u2026` : r.insecure ? "certificate not checked" : r.url.startsWith("https") ? "CA-verified" : "plain http";
4673
+ process.stdout.write(`${r.name} ${r.url} as ${r.user} installation ${r.serverId ?? "(not recorded)"} ${tls}${r.dotenv ? ` env file ${r.dotenv}` : ""}${r.passwordConfigured ? "" : " (no password: run profile set-password)"}
4674
+ `);
4675
+ }
4676
+ });
4677
+ profileCommand.command("add").description("Add a profile at a terminal: confirm the server and its certificate, enter the password, record its installation").argument("<name>", 'profile name (letters, digits, ".", "_", "-")').requiredOption("--host <host>", "Mirth server host").requiredOption("--port <port>", "Mirth server port").requiredOption("--user <user>", "username").option("--dotenv <path>", "env file for this server's trees, used when a tree has no .env of its own").option("--tls-fingerprint <sha256>", "the certificate's SHA-256 fingerprint, when you have it from the administrator").option("--insecure", "turn certificate verification off (loopback hosts only)", false).option("--no-https", "use http (loopback hosts only)").action(async (name, flags) => {
4678
+ needTerminal("profile add");
4679
+ if (!PROFILE_NAME.test(name)) fail(`profile names are letters, digits, '.', '_' and '-', starting with a letter or digit: ${name}`, "profile-invalid");
4680
+ const profiles = await loadProfiles();
4681
+ if (profiles[name]) fail(`profile ${name} already exists; change its password with \`channelvault profile set-password ${name}\`, or edit ${profilesFile()}`, "profile-exists");
4682
+ const port = Number(flags.port);
4683
+ const profile = { host: flags.host, port, user: flags.user };
4684
+ if (flags.https === false) profile.https = false;
4685
+ if (flags.insecure) profile.insecure = true;
4686
+ if (flags.dotenv) profile.dotenv = path10.resolve(flags.dotenv);
4687
+ if (flags.tlsFingerprint !== void 0) {
4688
+ const pin = normalizeFingerprint(flags.tlsFingerprint);
4689
+ if (!pin) fail("--tls-fingerprint must be a SHA-256 certificate fingerprint: 64 hex digits, colons allowed", "bad-fingerprint");
4690
+ profile.tlsFingerprint = pin;
4691
+ }
4692
+ const problems = profileProblems({ ...profiles, [name]: profile });
4693
+ if (problems.length > 0) fail(problems.join("\n"), "profile-invalid");
4694
+ const conn = connectionOfProfile(name, profile, "");
4695
+ process.stdout.write(`Add profile ${name}: ${urlOf(conn)} as ${profile.user}
4696
+ `);
4697
+ if (conn.https && !conn.insecure) {
4698
+ const presented = await presentedFingerprint(profile.host, port);
4699
+ if (profile.tlsFingerprint && presented !== profile.tlsFingerprint) {
4700
+ fail(`the server presents certificate SHA-256 ${formatFingerprint(presented)}, not the --tls-fingerprint given; nothing was saved`, "tls-pin-mismatch");
4701
+ }
4702
+ profile.tlsFingerprint = presented;
4703
+ process.stdout.write(`certificate SHA-256 ${formatFingerprint(presented)}
4704
+ channelvault will accept only this certificate from this server. Compare it with the one the server administrator gave you.
4705
+ `);
4706
+ }
4707
+ if (!await confirm("Is this the right server?")) {
4708
+ process.stdout.write("aborted.\n");
4709
+ return;
4710
+ }
4711
+ const password = await askPassword(`Password for ${profile.user}: `);
4712
+ profile.serverId = await loginCheck(connectionOfProfile(name, profile, password));
4713
+ const latest = await loadProfiles();
4714
+ if (latest[name]) fail(`profile ${name} was added meanwhile; nothing was saved`, "profile-exists");
4715
+ await saveProfiles({ ...latest, [name]: profile });
4716
+ await setCredential(name, password);
4717
+ process.stdout.write(`added profile ${name} (installation ${profile.serverId}); password stored in ${credentialsFile()}
4718
+ `);
4719
+ });
4720
+ profileCommand.command("set-password").description("Change a profile's stored password at a terminal; it is checked by logging in first").argument("<name>", "profile name").action(async (name) => {
4721
+ needTerminal("profile set-password");
4722
+ const profile = existingProfile(await loadProfiles(), name);
4723
+ process.stdout.write(`Profile ${name}: ${urlOf(connectionOfProfile(name, profile, ""))} as ${profile.user}
4724
+ `);
4725
+ const password = await askPassword(`New password for ${profile.user}: `);
4726
+ await loginCheck(connectionOfProfile(name, profile, password));
4727
+ await setCredential(name, password);
4728
+ process.stdout.write(`stored the password for profile ${name}
4729
+ `);
4730
+ });
4731
+ 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) => {
4732
+ const profiles = await loadProfiles();
4733
+ const credentials = await readCredentials();
4734
+ if (name) existingProfile(profiles, name);
4735
+ const names = name ? [name] : Object.keys(profiles);
4736
+ if (names.length === 0) fail(`no profiles in ${profilesFile()}`, "no-connection");
4737
+ const results = [];
4738
+ for (const n of names) {
4739
+ const password = credentials[n];
4740
+ if (password === void 0) {
4741
+ results.push({ name: n, ok: false, serverId: null, problem: `[no-password] run \`channelvault profile set-password ${n}\` at a terminal` });
4742
+ continue;
4743
+ }
4744
+ try {
4745
+ results.push({ name: n, ok: true, serverId: await loginCheck(connectionOfProfile(n, profiles[n], password)), problem: null });
4746
+ } catch (err) {
4747
+ results.push({ name: n, ok: false, serverId: null, problem: scrub(describeError(err)) });
4748
+ }
4749
+ }
4750
+ if (results.some((r) => !r.ok)) process.exitCode = 1;
4751
+ if (flags.json) {
4752
+ writeJson2({ profiles: results });
4753
+ return;
4754
+ }
4755
+ for (const r of results) process.stdout.write(r.ok ? `${r.name}: ok, installation ${r.serverId}
4756
+ ` : `${r.name}: FAILED ${r.problem}
4757
+ `);
4758
+ });
4759
+ profileCommand.command("repin").description("Pin a profile's server certificate again after it was replaced, at a terminal").argument("<name>", "profile name").action(async (name) => {
4760
+ needTerminal("profile repin");
4761
+ const profiles = await loadProfiles();
4762
+ const profile = existingProfile(profiles, name);
4763
+ if (profile.https === false || profile.insecure) fail(`profile ${name} does not check certificates, so there is nothing to pin`, "profile-invalid");
4764
+ const password = (await readCredentials())[name];
4765
+ if (password === void 0) fail(`profile ${name} has no password yet; run \`channelvault profile set-password ${name}\` first`, "no-password");
4766
+ const presented = await presentedFingerprint(profile.host, profile.port);
4767
+ if (presented === profile.tlsFingerprint) {
4768
+ process.stdout.write(`profile ${name} already pins the certificate ${profile.host}:${profile.port} presents
4769
+ `);
4770
+ return;
4771
+ }
4772
+ process.stdout.write(`Profile ${name}: ${profile.host}:${profile.port}
4773
+ pinned: ${profile.tlsFingerprint ? formatFingerprint(profile.tlsFingerprint) : "(none)"}
4774
+ presented: ${formatFingerprint(presented)}
4775
+ Accept the new certificate only if the administrator replaced it and gave you this fingerprint; otherwise someone may be impersonating the server.
4776
+ `);
4777
+ if (!await confirm("Pin the presented certificate?")) {
4778
+ process.stdout.write("aborted.\n");
4779
+ return;
4780
+ }
4781
+ const repinned = { ...profile, tlsFingerprint: presented };
4782
+ await loginCheck(connectionOfProfile(name, repinned, password));
4783
+ const latest = await loadProfiles();
4784
+ await saveProfiles({ ...latest, [name]: { ...existingProfile(latest, name), tlsFingerprint: presented } });
4785
+ process.stdout.write(`profile ${name} now pins ${formatFingerprint(presented)}
4786
+ `);
4787
+ });
4788
+ var unlocks = [];
4789
+ var locked = [];
4790
+ async function lockAlso(file) {
4791
+ const key = await canonical(file);
4792
+ if (locked.some((l) => samePath(l, key))) return;
4793
+ unlocks.push(await lockTree(path10.resolve(file)));
4794
+ locked.push(key);
4795
+ }
3937
4796
  program.hook("preAction", async (_program, command) => {
3938
4797
  const name = command.name();
3939
- if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
4798
+ if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name) || command.parent !== program) return;
3940
4799
  if (name === "diff") errorExitCode = 2;
3941
- const root = path8.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3942
- unlock = await lockTree(root);
3943
- await recoverTree(root, envFilePath(root, command.opts()));
4800
+ const root = path10.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
4801
+ unlocks.push(await lockTree(root));
4802
+ const pending = await pendingEnvFile(root);
4803
+ if (pending === null) return;
4804
+ if (!isWithin(pending, await resolvedPath(root))) await lockAlso(pending);
4805
+ await recoverTree(root, await recoveryCandidates(root, command.opts()));
3944
4806
  });
3945
- program.parseAsync().catch((err) => {
4807
+ function describeError(err) {
4808
+ const code = err?.code;
4809
+ const reason = err instanceof ReasonError ? err.reason : code === "TLS_PIN_MISMATCH" ? "tls-pin-mismatch" : void 0;
4810
+ return `${reason ? `[${reason}] ` : ""}${err instanceof Error ? err.message : String(err)}`;
4811
+ }
4812
+ async function certificateHint(code) {
4813
+ const conn = activeConnection;
4814
+ if (code === "TLS_PIN_MISMATCH") {
4815
+ return conn?.profile ? `if the administrator replaced the certificate, check its new fingerprint with them and run \`channelvault profile repin ${conn.profile}\` at a terminal` : "if the administrator replaced the certificate, check its new fingerprint with them and update --tls-fingerprint (or MIRTH_TLS_FINGERPRINT)";
4816
+ }
4817
+ if (!UNTRUSTED_CERT_CODES.has(code)) return void 0;
4818
+ const presented = conn ? await presentedFingerprint(conn.host, conn.port, 5e3).catch(() => void 0) : void 0;
4819
+ const pin = presented ? ` It presents SHA-256 ${formatFingerprint(presented)}.` : "";
4820
+ const loopback = conn ? isLoopback(conn.host) : false;
4821
+ return `the server's TLS certificate is not trusted (Mirth's default certificate is self-signed).${pin} Confirm that fingerprint with the server administrator, then save a profile at a terminal with \`channelvault profile add <name> --host <host> --port <port> --user <user>\`, which pins it${presented ? `, or pass --tls-fingerprint ${presented} (or set MIRTH_TLS_FINGERPRINT)` : ", or pass --tls-fingerprint"}${loopback ? ". For this loopback test server, --insecure turns verification off" : ""}.`;
4822
+ }
4823
+ program.parseAsync().catch(async (err) => {
3946
4824
  if (err instanceof CommanderError) return;
3947
- process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}
4825
+ process.stderr.write(`error: ${scrub(describeError(err))}
3948
4826
  `);
3949
4827
  const code = err?.code;
3950
- if (typeof code === "string" && UNTRUSTED_CERT_CODES.has(code)) {
3951
- process.stderr.write(
3952
- "hint: the server's TLS certificate is not trusted. For a self-signed certificate (Mirth's default), pass --insecure, which turns certificate verification off.\n"
3953
- );
3954
- }
3955
- if (!(err instanceof CliError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {
4828
+ const hint = typeof code === "string" ? await certificateHint(code) : void 0;
4829
+ if (hint) process.stderr.write(`hint: ${hint}
4830
+ `);
4831
+ if (!(err instanceof ReasonError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {
3956
4832
  process.stderr.write(`${scrub(err.stack ?? "")}
3957
4833
  `);
3958
4834
  }
3959
4835
  process.exitCode = errorExitCode;
3960
4836
  }).finally(async () => {
3961
- if (unlock) {
4837
+ for (const unlock of unlocks.reverse()) {
3962
4838
  try {
3963
4839
  await unlock();
3964
4840
  } catch (err) {
3965
- process.stderr.write(`error: could not release working-tree lock: ${scrub(err instanceof Error ? err.message : String(err))}
4841
+ process.stderr.write(`error: could not release a lock: ${scrub(err instanceof Error ? err.message : String(err))}
3966
4842
  `);
3967
4843
  process.exitCode = errorExitCode;
3968
4844
  }