@ubercode/channelvault 0.3.0-rc.2 → 0.3.0-rc.4

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 mkdir6, mkdtemp, readdir as readdir6, readFile as readFile6, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
+ import { existsSync as existsSync8 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path7 from "path";
9
+ import * as path9 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";
@@ -1000,12 +1003,12 @@ function configMapKeyOf(entry) {
1000
1003
  return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
1001
1004
  }
1002
1005
  function mapLeaves(config, visit) {
1003
- const walk = (node, key, path8, labels, section, cmKey) => {
1006
+ const walk = (node, key, path10, labels, section, cmKey) => {
1004
1007
  if (typeof node === "string") {
1005
- return visit(node, { location: path8.join("/"), key, labels, section, configMapKey: cmKey });
1008
+ return visit(node, { location: path10.join("/"), key, labels, section, configMapKey: cmKey });
1006
1009
  }
1007
1010
  if (Array.isArray(node)) {
1008
- return node.map((el, i) => walk(el, key, [...path8.slice(0, -1), `${path8[path8.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1011
+ return node.map((el, i) => walk(el, key, [...path10.slice(0, -1), `${path10[path10.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1009
1012
  }
1010
1013
  if (node && typeof node === "object") {
1011
1014
  const name = node["name"];
@@ -1013,7 +1016,7 @@ function mapLeaves(config, visit) {
1013
1016
  const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
1014
1017
  const out = {};
1015
1018
  for (const [k, v] of Object.entries(node)) {
1016
- out[k] = walk(v, k, [...path8, k], inner, section || k, mapKey);
1019
+ out[k] = walk(v, k, [...path10, k], inner, section || k, mapKey);
1017
1020
  }
1018
1021
  return out;
1019
1022
  }
@@ -1411,6 +1414,47 @@ function connectionError(url, err) {
1411
1414
  error.code = code;
1412
1415
  return error;
1413
1416
  }
1417
+ function fingerprintOf(socket) {
1418
+ return (socket.getPeerCertificate().fingerprint256 ?? "").replace(/:/g, "").toLowerCase();
1419
+ }
1420
+ function pinnedConnector(pin) {
1421
+ const base = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0 });
1422
+ return (options, callback) => {
1423
+ base(options, (err, socket) => {
1424
+ if (err) return callback(err, null);
1425
+ const presented = fingerprintOf(socket);
1426
+ if (presented === pin) return callback(null, socket);
1427
+ socket.destroy();
1428
+ const mismatch = new Error(
1429
+ `the server presented certificate SHA-256 ${presented || "(none)"}, but the pinned fingerprint is ${pin}; nothing was sent`
1430
+ );
1431
+ mismatch.code = "TLS_PIN_MISMATCH";
1432
+ mismatch.presented = presented;
1433
+ callback(mismatch, null);
1434
+ });
1435
+ };
1436
+ }
1437
+ function presentedFingerprint(host, port, timeoutMs = 1e4) {
1438
+ return new Promise((resolve6, reject) => {
1439
+ const socket = tlsConnect({ host, port, rejectUnauthorized: false, ...isIP(host) ? {} : { servername: host } });
1440
+ socket.setTimeout(timeoutMs, () => socket.destroy(new Error(`no TLS handshake from ${host}:${port} within ${timeoutMs / 1e3} s`)));
1441
+ socket.once("secureConnect", () => {
1442
+ const fp = fingerprintOf(socket);
1443
+ socket.end();
1444
+ resolve6(fp);
1445
+ });
1446
+ socket.once("error", reject);
1447
+ });
1448
+ }
1449
+ function redirectTarget(url, response) {
1450
+ const location = response.headers.get("location");
1451
+ if (!location) return "";
1452
+ try {
1453
+ return `, to ${new URL(location, url).origin}`;
1454
+ } catch {
1455
+ return "";
1456
+ }
1457
+ }
1414
1458
  var SERVER_CONFIG_KEY = "serverConfiguration";
1415
1459
  function unwrapSingleKey(value) {
1416
1460
  const keys = Object.keys(value);
@@ -1433,7 +1477,7 @@ var MirthClientImpl = class {
1433
1477
  const protocol = config.https !== false ? "https" : "http";
1434
1478
  this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;
1435
1479
  this.cookieJar = new CookieJar();
1436
- this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
1480
+ this.dispatcher = new Agent(config.tlsFingerprint ? { connect: pinnedConnector(config.tlsFingerprint) } : config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
1437
1481
  }
1438
1482
  isAuthenticated() {
1439
1483
  return this.authenticated;
@@ -1613,15 +1657,15 @@ var MirthClientImpl = class {
1613
1657
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1614
1658
  }
1615
1659
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1616
- async sendJson(method, path8, body, query) {
1617
- const response = await this.request(method, path8, {
1660
+ async sendJson(method, path10, body, query) {
1661
+ const response = await this.request(method, path10, {
1618
1662
  query,
1619
1663
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1620
1664
  body: JSON.stringify(body)
1621
1665
  });
1622
1666
  const text = await response.text();
1623
1667
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1624
- throw new Error(`${method} ${path8}: the server refused the update`);
1668
+ throw new Error(`${method} ${path10}: the server refused the update`);
1625
1669
  }
1626
1670
  }
1627
1671
  // --- internal transport ---------------------------------------------------
@@ -1630,11 +1674,11 @@ var MirthClientImpl = class {
1630
1674
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1631
1675
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1632
1676
  */
1633
- async request(method, path8, options = {}, isRetry = false) {
1677
+ async request(method, path10, options = {}, isRetry = false) {
1634
1678
  if (!this.authenticated) {
1635
1679
  await this.login();
1636
1680
  }
1637
- const url = this.buildUrl(path8, options.query);
1681
+ const url = this.buildUrl(path10, options.query);
1638
1682
  const headers = {
1639
1683
  "X-Requested-With": "XMLHttpRequest",
1640
1684
  ...options.headers
@@ -1648,28 +1692,39 @@ var MirthClientImpl = class {
1648
1692
  if (response.status === 401 && this.authenticated && !isRetry) {
1649
1693
  this.authenticated = false;
1650
1694
  await this.login();
1651
- return this.request(method, path8, options, true);
1695
+ return this.request(method, path10, options, true);
1652
1696
  }
1653
1697
  if (!response.ok) {
1654
1698
  throw await this.toApiError(response);
1655
1699
  }
1656
1700
  return response;
1657
1701
  }
1658
- /** fetch through this client's pool, with network failures explained. */
1702
+ /**
1703
+ * fetch through this client's pool, with network failures explained. Never
1704
+ * follows a redirect: fetch re-sends a 307/308 body, so a redirected login
1705
+ * would post the username and password to wherever the server points.
1706
+ */
1659
1707
  async send(url, init) {
1708
+ let response;
1660
1709
  try {
1661
- return await fetch(url, {
1710
+ response = await fetch(url, {
1662
1711
  ...init,
1712
+ redirect: "manual",
1663
1713
  // @ts-expect-error - dispatcher is a Node.js/undici specific option
1664
1714
  dispatcher: this.dispatcher
1665
1715
  });
1666
1716
  } catch (err) {
1667
1717
  throw connectionError(url, err);
1668
1718
  }
1719
+ if (response.status >= 300 && response.status < 400) {
1720
+ await response.body?.cancel();
1721
+ throw new Error(`the server answered ${new URL(url).pathname} with a redirect (HTTP ${response.status}${redirectTarget(url, response)}); channelvault does not follow redirects, so credentials and session cookies are never sent elsewhere. Connect to the address it redirects to: check https vs --no-https, --host and --port (or MIRTH_HOST/MIRTH_PORT)`);
1722
+ }
1723
+ return response;
1669
1724
  }
1670
1725
  /** Build an absolute URL with an optional query string. */
1671
- buildUrl(path8, query) {
1672
- const url = `${this.baseUrl}${path8}`;
1726
+ buildUrl(path10, query) {
1727
+ const url = `${this.baseUrl}${path10}`;
1673
1728
  if (!query || Object.keys(query).length === 0) {
1674
1729
  return url;
1675
1730
  }
@@ -1736,174 +1791,740 @@ function createMirthClient(config) {
1736
1791
  return new MirthClientImpl(config);
1737
1792
  }
1738
1793
 
1739
- // src/push/index.ts
1740
- import { createHash as createHash2 } from "crypto";
1741
- var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1742
- function list(v) {
1743
- if (v == null || v === "") return [];
1744
- return (Array.isArray(v) ? v : [v]).filter(isObj);
1794
+ // src/profiles.ts
1795
+ import { spawnSync } from "child_process";
1796
+ import { existsSync as existsSync5 } from "fs";
1797
+ import { mkdir as mkdir4 } from "fs/promises";
1798
+ import { homedir } from "os";
1799
+ import * as path5 from "path";
1800
+
1801
+ // src/backup/index.ts
1802
+ import { randomBytes } from "crypto";
1803
+ import { existsSync as existsSync2, realpathSync } from "fs";
1804
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rename, rm, writeFile as writeFile2 } from "fs/promises";
1805
+ import * as path2 from "path";
1806
+ function defaultBackupDir() {
1807
+ return path2.join(configDir(), "backups");
1745
1808
  }
1746
- function channelsOf(c) {
1747
- return isObj(c["channels"]) ? list(c["channels"]["channel"]) : [];
1809
+ var LEGACY_BACKUP_DIR = ".backup";
1810
+ var DEFAULT_KEEP = 10;
1811
+ var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
1812
+ function serverSlug(name) {
1813
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1748
1814
  }
1749
- function librariesOf(c) {
1750
- return isObj(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
1815
+ function backupName(config, fallback) {
1816
+ return configuredName(config) || serverSlug(fallback) || "mirth";
1751
1817
  }
1752
- function templatesOf2(library) {
1753
- return isObj(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
1818
+ function configuredName(config) {
1819
+ const settings = config["serverSettings"];
1820
+ const field = (key) => {
1821
+ const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
1822
+ return typeof v === "string" ? serverSlug(v) : "";
1823
+ };
1824
+ return field("serverName") || field("environmentName");
1754
1825
  }
1755
- var idOf = (o) => String(o["id"]);
1756
- var nameOf = (o) => String(o["name"] ?? o["id"]);
1757
- var revisionOf = (o) => Number(o["revision"] ?? 0);
1758
- function normalizeEol(s) {
1759
- return s.replace(/\r\n?/g, "\n");
1826
+ function stamp(date) {
1827
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
1760
1828
  }
1761
- function normalizeEolDeep(value) {
1762
- if (typeof value === "string") return normalizeEol(value);
1763
- if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
1764
- if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
1765
- return value;
1829
+ async function listBackups(dir) {
1830
+ if (!existsSync2(dir)) return [];
1831
+ const out = [];
1832
+ for (const name of await readdir2(dir)) {
1833
+ const m = FILE_NAME.exec(name);
1834
+ if (m) out.push({ file: path2.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
1835
+ }
1836
+ return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
1766
1837
  }
1767
- function same(a, b) {
1768
- if (a === b) return true;
1769
- if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
1770
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
1771
- if (isObj(a) && isObj(b)) {
1772
- const ka = Object.keys(a);
1773
- return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
1838
+ var MANIFEST = "channelvault-backups.json";
1839
+ async function readManifest(dir) {
1840
+ const file = path2.join(dir, MANIFEST);
1841
+ if (!existsSync2(file)) return {};
1842
+ try {
1843
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
1844
+ return parsed.files ?? {};
1845
+ } catch (err) {
1846
+ throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
1774
1847
  }
1775
- return false;
1776
1848
  }
1777
- var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
1778
- function withSortedContexts(o) {
1779
- const set = o["contextSet"];
1780
- const delegate = isObj(set) ? set["delegate"] : void 0;
1781
- const types = isObj(delegate) ? delegate["contextType"] : void 0;
1782
- if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
1783
- const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
1784
- return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
1849
+ async function writeManifest(dir, files) {
1850
+ const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync2(path2.join(dir, name))));
1851
+ await writePrivate(path2.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
1852
+ `);
1785
1853
  }
1786
- function stripVolatile(o) {
1787
- const out = withSortedContexts({ ...o });
1788
- delete out["revision"];
1789
- delete out["lastModified"];
1790
- const exportData = out["exportData"];
1791
- if (isObj(exportData)) {
1792
- const metadata = isObj(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
1793
- if (metadata) {
1794
- delete metadata["lastModified"];
1795
- delete metadata["userId"];
1796
- }
1797
- out["exportData"] = metadata ? { metadata } : {};
1854
+ async function backupsOf(dir, serverId) {
1855
+ const manifest = await readManifest(dir);
1856
+ return (await listBackups(dir)).filter((b) => manifest[path2.basename(b.file)]?.serverId === serverId);
1857
+ }
1858
+ async function originOf(dir, file) {
1859
+ if (!existsSync2(dir) || !sameFile(path2.dirname(file), dir)) return null;
1860
+ return (await readManifest(dir))[path2.basename(file)] ?? null;
1861
+ }
1862
+ async function originsIn(dir) {
1863
+ if (!existsSync2(dir)) return [];
1864
+ const seen = /* @__PURE__ */ new Map();
1865
+ for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);
1866
+ return [...seen.values()];
1867
+ }
1868
+ async function saveBackup(dir, name, xml2, opts) {
1869
+ await ensureBackupDir(dir);
1870
+ const manifest = await readManifest(dir);
1871
+ const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
1872
+ let file = path2.join(dir, `${base}.xml`);
1873
+ for (let n = 2; existsSync2(file); n += 1) file = path2.join(dir, `${base}-${n}.xml`);
1874
+ await writePrivate(file, xml2);
1875
+ manifest[path2.basename(file)] = opts.origin;
1876
+ await writeManifest(dir, manifest);
1877
+ const mine = (await listBackups(dir)).filter((b) => manifest[path2.basename(b.file)]?.serverId === opts.origin.serverId);
1878
+ for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
1879
+ if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
1880
+ await rm(old.file);
1798
1881
  }
1799
- return out;
1882
+ await writeManifest(dir, manifest);
1883
+ return file;
1800
1884
  }
1801
- var groupsOf = (c) => isObj(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
1802
- function withoutVolatile(c) {
1803
- const out = structuredClone(c);
1804
- const strip = (o) => {
1805
- delete o["revision"];
1806
- delete o["lastModified"];
1807
- const exportData = o["exportData"];
1808
- const md = isObj(exportData) ? exportData["metadata"] : void 0;
1809
- if (isObj(md)) {
1810
- delete md["lastModified"];
1811
- delete md["userId"];
1812
- }
1813
- if (isObj(exportData)) {
1814
- for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
1815
- }
1816
- if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
1885
+ function sameFile(a, b) {
1886
+ const real = (p) => {
1887
+ const resolved = existsSync2(p) ? realpathSync.native(p) : path2.resolve(p);
1888
+ return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
1817
1889
  };
1818
- for (const ch of channelsOf(out)) strip(ch);
1819
- for (const lib of librariesOf(out)) {
1820
- strip(lib);
1821
- for (const t of templatesOf2(lib)) strip(t);
1822
- }
1823
- for (const g of groupsOf(out)) {
1824
- strip(g);
1825
- for (const member of isObj(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
1890
+ return real(a) === real(b);
1891
+ }
1892
+ async function ensureBackupDir(dir) {
1893
+ if (existsSync2(dir)) return;
1894
+ await mkdir2(dir, { recursive: true, mode: 448 });
1895
+ await writeFile2(path2.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
1896
+ }
1897
+ async function writePrivate(file, text) {
1898
+ const temp = `${file}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
1899
+ try {
1900
+ await writeFile2(temp, text, { encoding: "utf8", mode: 384 });
1901
+ await rename(temp, file);
1902
+ } catch (err) {
1903
+ await rm(temp, { force: true });
1904
+ throw err;
1826
1905
  }
1827
- return out;
1828
1906
  }
1829
- function newerOnServer(tree, server) {
1830
- const out = [];
1831
- const compare = (kind, local, remote) => {
1832
- const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
1833
- for (const r of remote) {
1834
- const rev = mine.get(idOf(r));
1835
- if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
1836
- }
1837
- };
1838
- compare("channel", channelsOf(tree), channelsOf(server));
1839
- compare("library", librariesOf(tree), librariesOf(server));
1840
- compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
1841
- compare("channel group", groupsOf(tree), groupsOf(server));
1842
- return out;
1907
+ function numericVersion(v) {
1908
+ const m = /^\d+(?:\.\d+)*/.exec(v.trim());
1909
+ return m ? m[0].split(".").map(Number) : null;
1843
1910
  }
1844
- function libraryShape(lib) {
1845
- const out = stripVolatile(lib);
1846
- out["codeTemplates"] = templatesOf2(lib).map(idOf);
1847
- return out;
1911
+ function compareVersions(a, b) {
1912
+ const pa = numericVersion(a);
1913
+ const pb = numericVersion(b);
1914
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
1915
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1916
+ if (d !== 0) return d;
1917
+ }
1918
+ return 0;
1848
1919
  }
1849
- function withRetainedMembers(local, remote, localIds, deletedIds) {
1850
- const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
1851
- if (!retained.length) return local;
1852
- return { ...local, codeTemplates: {
1853
- ...isObj(local["codeTemplates"]) ? local["codeTemplates"] : {},
1854
- codeTemplate: [...templatesOf2(local), ...retained]
1855
- } };
1920
+
1921
+ // src/paths.ts
1922
+ import { existsSync as existsSync3, realpathSync as realpathSync2 } from "fs";
1923
+ import { lstat as lstat2, readlink, realpath as realpath2 } from "fs/promises";
1924
+ import * as path3 from "path";
1925
+ function samePath(a, b) {
1926
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
1856
1927
  }
1857
- function hashGlobalScripts(c) {
1858
- return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
1928
+ function isWithin(child, parent) {
1929
+ const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
1930
+ const rel = path3.relative(norm(parent), norm(child));
1931
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${path3.sep}`) && !path3.isAbsolute(rel);
1859
1932
  }
1860
- function resourceIds(c) {
1861
- const libs = librariesOf(c);
1862
- const revs = (items) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));
1863
- return {
1864
- channels: revs(channelsOf(c)),
1865
- libraries: revs(libs),
1866
- codeTemplates: revs(libs.flatMap(templatesOf2)),
1867
- globalScripts: hashGlobalScripts(c)
1868
- };
1933
+ async function resolvedPath(p) {
1934
+ const abs = path3.resolve(p);
1935
+ let existing = abs;
1936
+ while (!existsSync3(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1937
+ return path3.join(await realpath2(existing), path3.relative(existing, abs));
1869
1938
  }
1870
- function adoptTarget(local, target) {
1871
- const config = structuredClone(local);
1872
- const mine = resourceIds(local);
1873
- const theirs = resourceIds(target);
1874
- const intersect = (key) => Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));
1875
- const known = {
1876
- channels: intersect("channels"),
1877
- libraries: intersect("libraries"),
1878
- codeTemplates: intersect("codeTemplates"),
1879
- globalScripts: theirs.globalScripts
1880
- };
1881
- const rebase = (items, revisions) => {
1882
- for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
1883
- };
1884
- rebase(channelsOf(config), theirs.channels);
1885
- rebase(librariesOf(config), theirs.libraries);
1886
- rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
1887
- return { config, known };
1939
+ function resolvedPathSync(p) {
1940
+ const abs = path3.resolve(p);
1941
+ let existing = abs;
1942
+ while (!existsSync3(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1943
+ return path3.join(realpathSync2.native(existing), path3.relative(existing, abs));
1888
1944
  }
1889
- function knownFrom(raw) {
1890
- if (!isObj(raw)) return void 0;
1891
- const r = raw;
1892
- const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
1893
- return {
1894
- channels: map(r["channels"]),
1895
- libraries: map(r["libraries"]),
1896
- codeTemplates: map(r["codeTemplates"]),
1897
- globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
1898
- };
1945
+ async function present(file) {
1946
+ return lstat2(file).then(() => true, (err) => {
1947
+ if (err.code === "ENOENT") return false;
1948
+ throw err;
1949
+ });
1899
1950
  }
1900
- function knownAfterPush(known, applied, touched, fresh) {
1901
- const now = resourceIds(fresh);
1902
- const next = {
1903
- channels: { ...known.channels },
1904
- libraries: { ...known.libraries },
1905
- codeTemplates: { ...known.codeTemplates },
1906
- globalScripts: known.globalScripts
1951
+ async function canonical(file, depth = 0) {
1952
+ if (depth > 64) throw new Error(`too many links in path: ${file}`);
1953
+ let existing = path3.resolve(file);
1954
+ while (!await present(existing) && path3.dirname(existing) !== existing) existing = path3.dirname(existing);
1955
+ const info = await lstat2(existing);
1956
+ const base = info.isSymbolicLink() ? await canonical(path3.resolve(path3.dirname(existing), await readlink(existing)), depth + 1) : await realpath2(existing);
1957
+ return path3.join(base, path3.relative(existing, path3.resolve(file)));
1958
+ }
1959
+
1960
+ // src/secrets/envfile.ts
1961
+ import { randomBytes as randomBytes2 } from "crypto";
1962
+ import { existsSync as existsSync4 } from "fs";
1963
+ 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";
1964
+ import * as path4 from "path";
1965
+ import { parse } from "dotenv";
1966
+ var BASE64_PREFIX = "cv-base64:";
1967
+ function parseEnv(text) {
1968
+ const out = parse(text);
1969
+ for (const [k, v] of Object.entries(out)) {
1970
+ if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
1971
+ }
1972
+ return out;
1973
+ }
1974
+ async function readEnvFile(file) {
1975
+ if (!existsSync4(file)) return {};
1976
+ return parseEnv(await readFile4(file, "utf8"));
1977
+ }
1978
+ function formatValue(value) {
1979
+ const candidates = [
1980
+ /^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
1981
+ value.includes("'") ? null : `'${value}'`,
1982
+ value.includes("`") ? null : `\`${value}\``,
1983
+ value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
1984
+ ];
1985
+ for (const c of candidates) {
1986
+ if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
1987
+ }
1988
+ return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
1989
+ }
1990
+ async function updateEnvFile(file, updates) {
1991
+ const names = Object.keys(updates);
1992
+ if (names.length === 0) return;
1993
+ const existing = existsSync4(file) ? await readFile4(file, "utf8") : "";
1994
+ const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
1995
+ const written = /* @__PURE__ */ new Set();
1996
+ const out = [];
1997
+ let inQuote = null;
1998
+ let dropping = false;
1999
+ for (const line of lines) {
2000
+ if (inQuote !== null) {
2001
+ if (!dropping) out.push(line);
2002
+ if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
2003
+ continue;
2004
+ }
2005
+ const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
2006
+ const q = m?.[2][0];
2007
+ const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
2008
+ if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
2009
+ if (!written.has(m[1])) {
2010
+ out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
2011
+ written.add(m[1]);
2012
+ }
2013
+ if (opens) [inQuote, dropping] = [opens, true];
2014
+ continue;
2015
+ }
2016
+ out.push(line);
2017
+ if (opens) inQuote = opens;
2018
+ }
2019
+ for (const name of names) {
2020
+ if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
2021
+ }
2022
+ const text = `${out.join("\n")}
2023
+ `;
2024
+ const readBack = parseEnv(text);
2025
+ const wrong = names.filter((n) => readBack[n] !== updates[n]);
2026
+ if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
2027
+ const target = existsSync4(file) ? await realpath3(file) : file;
2028
+ const temp = `${target}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
2029
+ try {
2030
+ await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
2031
+ await rename2(temp, target);
2032
+ } catch (err) {
2033
+ await rm2(temp, { force: true });
2034
+ throw err;
2035
+ }
2036
+ }
2037
+ var ENV_BACKUPS_KEPT = 5;
2038
+ async function backupEnvFile(file, updates, dir) {
2039
+ if (!existsSync4(file)) return null;
2040
+ const current = parseEnv(await readFile4(file, "utf8"));
2041
+ if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
2042
+ await mkdir3(dir, { recursive: true });
2043
+ const prefix = `${path4.basename(file)}-`;
2044
+ const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
2045
+ let target = path4.join(dir, `${prefix}${stamp2}`);
2046
+ for (let n = 2; existsSync4(target); n += 1) target = path4.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
2047
+ await copyFile(file, target);
2048
+ await chmod(target, 384);
2049
+ const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path4.basename(target)).sort();
2050
+ for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
2051
+ await rm2(path4.join(dir, old));
2052
+ }
2053
+ return target;
2054
+ }
2055
+ var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
2056
+ async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
2057
+ const file = path4.join(dir, ".gitignore");
2058
+ const text = existsSync4(file) ? await readFile4(file, "utf8") : "";
2059
+ const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
2060
+ const wanted = [...IGNORE_LINES];
2061
+ if (envFile) {
2062
+ const rel = path4.relative(treeRoot, envFile).split(path4.sep).join("/");
2063
+ const base = path4.basename(envFile);
2064
+ const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
2065
+ if (!covered && !rel.startsWith("..") && !path4.isAbsolute(rel)) wanted.push(`/${rel}`);
2066
+ }
2067
+ const missing = wanted.filter((l) => !present2.has(l));
2068
+ if (missing.length === 0) return false;
2069
+ const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
2070
+ await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
2071
+ ${missing.join("\n")}
2072
+ `);
2073
+ return true;
2074
+ }
2075
+
2076
+ // src/profiles.ts
2077
+ var ReasonError = class extends Error {
2078
+ constructor(message, reason) {
2079
+ super(message);
2080
+ this.reason = reason;
2081
+ }
2082
+ reason;
2083
+ };
2084
+ function problem(message, reason) {
2085
+ throw new ReasonError(message, reason);
2086
+ }
2087
+ function configDir() {
2088
+ const override = process.env.CHANNELVAULT_CONFIG_DIR;
2089
+ if (!override) return path5.join(homedir(), ".channelvault");
2090
+ const dir = path5.resolve(override);
2091
+ let existing = dir;
2092
+ while (!existsSync5(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
2093
+ const git = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: existing, encoding: "utf8" });
2094
+ if (git.status === 0 && git.stdout.trim() === "true") {
2095
+ problem(`CHANNELVAULT_CONFIG_DIR (${dir}) is inside a git work tree; keep channelvault's folder outside every repository`, "config-in-repo");
2096
+ }
2097
+ return dir;
2098
+ }
2099
+ var PROFILES_FILE = "profiles.json";
2100
+ var CREDENTIALS_FILE = "credentials";
2101
+ var FIELDS = ["host", "port", "user", "https", "insecure", "tlsFingerprint", "serverId", "dotenv"];
2102
+ var PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
2103
+ function isLoopback(host) {
2104
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
2105
+ return h === "localhost" || h === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
2106
+ }
2107
+ function normalizeFingerprint(value) {
2108
+ const hex2 = value.replace(/:/g, "").toLowerCase();
2109
+ return /^[0-9a-f]{64}$/.test(hex2) ? hex2 : null;
2110
+ }
2111
+ function formatFingerprint(hex2) {
2112
+ return hex2.toUpperCase().match(/../g).join(":");
2113
+ }
2114
+ function profileProblems(profiles) {
2115
+ if (profiles === null || typeof profiles !== "object" || Array.isArray(profiles)) return ["profiles must be an object of named profiles"];
2116
+ const problems = [];
2117
+ const dotenvs = [];
2118
+ for (const [name, raw] of Object.entries(profiles)) {
2119
+ const at = `profile ${name}`;
2120
+ if (!PROFILE_NAME.test(name)) problems.push(`${at}: a name is letters, digits, '.', '_' and '-', starting with a letter or digit`);
2121
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
2122
+ problems.push(`${at}: must be an object`);
2123
+ continue;
2124
+ }
2125
+ const p = raw;
2126
+ for (const key of Object.keys(p)) {
2127
+ 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`);
2128
+ else if (!FIELDS.includes(key)) problems.push(`${at}: unknown field ${key} (fields: ${FIELDS.join(", ")})`);
2129
+ }
2130
+ if (typeof p.host !== "string" || p.host === "" || /[\s/]/.test(p.host)) problems.push(`${at}: host must be a host name or address`);
2131
+ if (!Number.isInteger(p.port) || p.port < 1 || p.port > 65535) problems.push(`${at}: port must be a whole number from 1 to 65535`);
2132
+ if (typeof p.user !== "string" || p.user === "") problems.push(`${at}: user must be a non-empty string`);
2133
+ for (const flag of ["https", "insecure"]) {
2134
+ if (p[flag] !== void 0 && typeof p[flag] !== "boolean") problems.push(`${at}: ${flag} must be true or false`);
2135
+ }
2136
+ if (p.serverId !== void 0 && (typeof p.serverId !== "string" || p.serverId === "")) problems.push(`${at}: serverId must be a non-empty string`);
2137
+ if (p.tlsFingerprint !== void 0 && (typeof p.tlsFingerprint !== "string" || normalizeFingerprint(p.tlsFingerprint) === null)) {
2138
+ problems.push(`${at}: tlsFingerprint must be a SHA-256 certificate fingerprint (64 hex digits, colons allowed)`);
2139
+ }
2140
+ if (p.dotenv !== void 0) {
2141
+ if (typeof p.dotenv !== "string" || !path5.isAbsolute(p.dotenv)) problems.push(`${at}: dotenv must be an absolute path`);
2142
+ else dotenvs.push([name, resolvedPathSync(p.dotenv)]);
2143
+ }
2144
+ if (typeof p.host === "string" && !isLoopback(p.host)) {
2145
+ 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)`);
2146
+ 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)`);
2147
+ }
2148
+ if (p.https === false && p.tlsFingerprint !== void 0) problems.push(`${at}: tlsFingerprint needs https`);
2149
+ if (p.insecure === true && p.tlsFingerprint !== void 0) problems.push(`${at}: insecure and tlsFingerprint cannot both be set`);
2150
+ }
2151
+ for (let i = 0; i < dotenvs.length; i++) {
2152
+ for (let j = i + 1; j < dotenvs.length; j++) {
2153
+ 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`);
2154
+ }
2155
+ }
2156
+ return problems;
2157
+ }
2158
+ function profilesFile() {
2159
+ return path5.join(configDir(), PROFILES_FILE);
2160
+ }
2161
+ function credentialsFile() {
2162
+ return path5.join(configDir(), CREDENTIALS_FILE);
2163
+ }
2164
+ async function loadProfiles() {
2165
+ const file = profilesFile();
2166
+ if (!existsSync5(file)) return {};
2167
+ let parsed;
2168
+ try {
2169
+ parsed = await readJson(file);
2170
+ } catch {
2171
+ problem(`${file} is not valid JSON; fix or remove it`, "profiles-invalid");
2172
+ }
2173
+ const profiles = parsed?.profiles;
2174
+ const keys = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? Object.keys(parsed) : [];
2175
+ const problems = keys.some((k) => k !== "profiles") || profiles === void 0 ? [`the file holds one object, { "profiles": { "<name>": { ... } } }`] : profileProblems(profiles);
2176
+ if (problems.length > 0) problem(`${file} cannot be used:
2177
+ ${problems.join("\n ")}`, "profiles-invalid");
2178
+ const out = {};
2179
+ for (const [name, p] of Object.entries(profiles)) {
2180
+ out[name] = { ...p, ...p.tlsFingerprint ? { tlsFingerprint: normalizeFingerprint(p.tlsFingerprint) } : {} };
2181
+ }
2182
+ return out;
2183
+ }
2184
+ async function ensureConfigDir() {
2185
+ const dir = configDir();
2186
+ await mkdir4(dir, { recursive: true, mode: 448 });
2187
+ return dir;
2188
+ }
2189
+ async function saveProfiles(profiles) {
2190
+ const problems = profileProblems(profiles);
2191
+ if (problems.length > 0) problem(`not saved:
2192
+ ${problems.join("\n ")}`, "profiles-invalid");
2193
+ await ensureConfigDir();
2194
+ await writePrivate(profilesFile(), `${JSON.stringify({ profiles }, null, 2)}
2195
+ `);
2196
+ }
2197
+ async function readCredentials() {
2198
+ return readEnvFile(credentialsFile());
2199
+ }
2200
+ async function setCredential(name, password) {
2201
+ await ensureConfigDir();
2202
+ await updateEnvFile(credentialsFile(), { [name]: password });
2203
+ }
2204
+
2205
+ // src/connection.ts
2206
+ var SOURCE_LABEL = {
2207
+ "profile-flag": "typed --profile",
2208
+ flags: "login flags",
2209
+ "env-profile": "MIRTH_PROFILE",
2210
+ env: "MIRTH_* environment",
2211
+ tree: "the tree's serverId"
2212
+ };
2213
+ function refuse(message, reason) {
2214
+ throw new ReasonError(message, reason);
2215
+ }
2216
+ function urlOf(conn) {
2217
+ return `${conn.https ? "https" : "http"}://${conn.host}:${conn.port}`;
2218
+ }
2219
+ function profileList(profiles) {
2220
+ const names = Object.keys(profiles);
2221
+ 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>`";
2222
+ }
2223
+ function sameHost(a, b) {
2224
+ return a.toLowerCase() === b.toLowerCase();
2225
+ }
2226
+ function fromProfile(name, input, source) {
2227
+ const profile = input.profiles[name];
2228
+ if (!profile) refuse(`no profile named ${name} (${profileList(input.profiles)})`, "profile-unknown");
2229
+ const typed = ["host", "port", "user", "pass", "tlsFingerprint"].filter((k) => input.flags[k] !== void 0).map((k) => `--${k === "tlsFingerprint" ? "tls-fingerprint" : k}`);
2230
+ if (input.flags.insecure) typed.push("--insecure");
2231
+ if (input.flags.https === false) typed.push("--no-https");
2232
+ if (typed.length > 0) refuse(`profile ${name} sets the whole connection; drop ${typed.join(", ")} (or use the login flags without a profile)`, "flag-conflict");
2233
+ const password = input.credentials[name];
2234
+ if (password === void 0) refuse(`profile ${name} has no password yet; run \`channelvault profile set-password ${name}\` at a terminal`, "no-password");
2235
+ if (input.treeServerId && profile.serverId && input.treeServerId !== profile.serverId) {
2236
+ refuse(`this tree belongs to installation ${input.treeServerId}, but profile ${name} is installation ${profile.serverId}; choose the profile for this tree`, "profile-mismatch");
2237
+ }
2238
+ return {
2239
+ host: profile.host,
2240
+ port: profile.port,
2241
+ user: profile.user,
2242
+ password,
2243
+ https: profile.https !== false,
2244
+ insecure: profile.insecure === true,
2245
+ ...profile.tlsFingerprint ? { tlsFingerprint: profile.tlsFingerprint } : {},
2246
+ source,
2247
+ passwordSource: "credentials",
2248
+ profile: name,
2249
+ ...profile.serverId ? { serverId: profile.serverId } : {},
2250
+ ...profile.dotenv ? { dotenv: profile.dotenv } : {}
2251
+ };
2252
+ }
2253
+ function fromFlagsAndEnv(input, source) {
2254
+ const { flags, env } = input;
2255
+ const foreign = flags.host !== void 0 && env.MIRTH_HOST && !sameHost(flags.host, env.MIRTH_HOST);
2256
+ const fallback = (name) => foreign ? void 0 : env[name];
2257
+ const host = flags.host ?? env.MIRTH_HOST;
2258
+ const portStr = flags.port ?? fallback("MIRTH_PORT");
2259
+ const user = flags.user ?? fallback("MIRTH_USER");
2260
+ const password = flags.pass ?? fallback("MIRTH_PASS");
2261
+ function missing(field, envName2) {
2262
+ if (foreign && env[envName2] !== void 0) {
2263
+ refuse(`${envName2} belongs to MIRTH_HOST=${env.MIRTH_HOST}, not --host ${flags.host}; type the matching --${field}, or use --profile`, "env-conflict");
2264
+ }
2265
+ refuse(`no ${field} for ${host ?? "the server"}: use --profile <name> (${profileList(input.profiles)})`, "no-connection");
2266
+ }
2267
+ if (!host) refuse(`no server: use --profile <name> (${profileList(input.profiles)})`, "no-connection");
2268
+ if (portStr === void 0) missing("port", "MIRTH_PORT");
2269
+ if (user === void 0) missing("user", "MIRTH_USER");
2270
+ if (password === void 0) missing("pass", "MIRTH_PASS");
2271
+ const port = Number(portStr);
2272
+ if (!Number.isInteger(port) || port < 1 || port > 65535) refuse(`invalid port: ${portStr}`, "bad-port");
2273
+ const rawPin = flags.tlsFingerprint ?? (foreign ? void 0 : env.MIRTH_TLS_FINGERPRINT);
2274
+ const tlsFingerprint = rawPin === void 0 ? void 0 : normalizeFingerprint(rawPin);
2275
+ 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");
2276
+ if (tlsFingerprint && flags.insecure) refuse("--insecure turns off the certificate check that --tls-fingerprint (or MIRTH_TLS_FINGERPRINT) pins; drop --insecure", "flag-conflict");
2277
+ if (tlsFingerprint && flags.https === false) refuse("--tls-fingerprint needs https; drop --no-https", "flag-conflict");
2278
+ return {
2279
+ host,
2280
+ port,
2281
+ user,
2282
+ password,
2283
+ https: flags.https !== false,
2284
+ insecure: flags.insecure === true,
2285
+ ...tlsFingerprint ? { tlsFingerprint } : {},
2286
+ source,
2287
+ passwordSource: flags.pass !== void 0 ? "--pass" : "MIRTH_PASS"
2288
+ };
2289
+ }
2290
+ function profilesFor(profiles, serverId) {
2291
+ return Object.entries(profiles).filter(([, p]) => p.serverId === serverId).map(([n]) => n);
2292
+ }
2293
+ function profileOwning(profiles, serverId) {
2294
+ return profilesFor(profiles, serverId)[0];
2295
+ }
2296
+ function resolveConnection(given) {
2297
+ const input = { ...given, env: Object.fromEntries(Object.entries(given.env).filter(([, v]) => v !== "")) };
2298
+ const { flags, env, profiles } = input;
2299
+ const loginTyped = flags.host !== void 0 || flags.port !== void 0 || flags.user !== void 0 || flags.pass !== void 0;
2300
+ let conn;
2301
+ if (flags.profile !== void 0) {
2302
+ conn = fromProfile(flags.profile, input, "profile-flag");
2303
+ } else if (flags.host !== void 0) {
2304
+ conn = fromFlagsAndEnv(input, "flags");
2305
+ } else if (env.MIRTH_PROFILE) {
2306
+ conn = fromProfile(env.MIRTH_PROFILE, input, "env-profile");
2307
+ } else if (env.MIRTH_HOST) {
2308
+ const owner = input.treeServerId ? profilesFor(profiles, input.treeServerId) : [];
2309
+ if (owner.length > 0) {
2310
+ refuse(`MIRTH_HOST is set, but this tree belongs to profile ${owner.join(" or ")}; use --profile ${owner[0]}, or unset MIRTH_HOST`, "env-shadowed");
2311
+ }
2312
+ conn = fromFlagsAndEnv(input, "env");
2313
+ } else if (loginTyped) {
2314
+ refuse(`--port, --user and --pass need --host (or use --profile <name>; ${profileList(profiles)})`, "no-connection");
2315
+ } else {
2316
+ const owner = input.treeServerId ? profilesFor(profiles, input.treeServerId) : [];
2317
+ if (owner.length > 1) refuse(`profiles ${owner.join(", ")} all name this tree's installation (${input.treeServerId}); pass --profile`, "profile-ambiguous");
2318
+ if (owner.length === 0) {
2319
+ refuse(`no connection: pass --profile <name> (${profileList(profiles)})`, "no-connection");
2320
+ }
2321
+ conn = fromProfile(owner[0], input, "tree");
2322
+ }
2323
+ if (input.write && conn.source === "tree") {
2324
+ 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");
2325
+ }
2326
+ if (input.write && conn.source === "env-profile" && input.yes) {
2327
+ 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");
2328
+ }
2329
+ if (input.write && input.explicit && conn.source !== "profile-flag" && conn.source !== "flags") {
2330
+ refuse("this command needs its server typed: pass --profile <name>, or --host with the login (environment variables can be stale)", "connection-not-typed");
2331
+ }
2332
+ return conn;
2333
+ }
2334
+ function describeConnection(conn, serverId, envFile) {
2335
+ const parts = [
2336
+ conn.profile ? `profile ${conn.profile}` : "no profile",
2337
+ `${urlOf(conn)} as ${conn.user}`,
2338
+ serverId ? `installation ${serverId}` : "installation not checked",
2339
+ `chosen by ${SOURCE_LABEL[conn.source]}`,
2340
+ `password from ${conn.passwordSource}`,
2341
+ conn.tlsFingerprint ? `certificate pinned ${formatFingerprint(conn.tlsFingerprint).slice(0, 23)}\u2026` : conn.insecure ? "certificate not checked" : conn.https ? "certificate verified" : "plain http"
2342
+ ];
2343
+ if (envFile) parts.push(`env file ${envFile}`);
2344
+ return `connection: ${parts.join(", ")}`;
2345
+ }
2346
+ function connectionJson(conn, serverId, envFile) {
2347
+ return {
2348
+ profile: conn.profile ?? null,
2349
+ url: urlOf(conn),
2350
+ user: conn.user,
2351
+ source: conn.source,
2352
+ passwordSource: conn.passwordSource,
2353
+ serverId: serverId ?? null,
2354
+ tlsFingerprint: conn.tlsFingerprint ?? null,
2355
+ insecure: conn.insecure,
2356
+ envFile: envFile ?? null
2357
+ };
2358
+ }
2359
+
2360
+ // src/push/index.ts
2361
+ import { createHash as createHash2 } from "crypto";
2362
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2363
+ function list(v) {
2364
+ if (v == null || v === "") return [];
2365
+ return (Array.isArray(v) ? v : [v]).filter(isObj);
2366
+ }
2367
+ function channelsOf(c) {
2368
+ return isObj(c["channels"]) ? list(c["channels"]["channel"]) : [];
2369
+ }
2370
+ function librariesOf(c) {
2371
+ return isObj(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
2372
+ }
2373
+ function templatesOf2(library) {
2374
+ return isObj(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
2375
+ }
2376
+ var idOf = (o) => String(o["id"]);
2377
+ var nameOf = (o) => String(o["name"] ?? o["id"]);
2378
+ var revisionOf = (o) => Number(o["revision"] ?? 0);
2379
+ function normalizeEol(s) {
2380
+ return s.replace(/\r\n?/g, "\n");
2381
+ }
2382
+ function normalizeEolDeep(value) {
2383
+ if (typeof value === "string") return normalizeEol(value);
2384
+ if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
2385
+ if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
2386
+ return value;
2387
+ }
2388
+ function same(a, b) {
2389
+ if (a === b) return true;
2390
+ if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
2391
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
2392
+ if (isObj(a) && isObj(b)) {
2393
+ const ka = Object.keys(a);
2394
+ return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
2395
+ }
2396
+ return false;
2397
+ }
2398
+ var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
2399
+ function withSortedContexts(o) {
2400
+ const set = o["contextSet"];
2401
+ const delegate = isObj(set) ? set["delegate"] : void 0;
2402
+ const types = isObj(delegate) ? delegate["contextType"] : void 0;
2403
+ if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
2404
+ const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
2405
+ return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
2406
+ }
2407
+ function stripVolatile(o) {
2408
+ const out = withSortedContexts({ ...o });
2409
+ delete out["revision"];
2410
+ delete out["lastModified"];
2411
+ const exportData = out["exportData"];
2412
+ if (isObj(exportData)) {
2413
+ const metadata = isObj(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
2414
+ if (metadata) {
2415
+ delete metadata["lastModified"];
2416
+ delete metadata["userId"];
2417
+ }
2418
+ out["exportData"] = metadata ? { metadata } : {};
2419
+ }
2420
+ return out;
2421
+ }
2422
+ var groupsOf = (c) => isObj(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
2423
+ function withoutVolatile(c) {
2424
+ const out = structuredClone(c);
2425
+ const strip = (o) => {
2426
+ delete o["revision"];
2427
+ delete o["lastModified"];
2428
+ const exportData = o["exportData"];
2429
+ const md = isObj(exportData) ? exportData["metadata"] : void 0;
2430
+ if (isObj(md)) {
2431
+ delete md["lastModified"];
2432
+ delete md["userId"];
2433
+ }
2434
+ if (isObj(exportData)) {
2435
+ for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
2436
+ }
2437
+ if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
2438
+ };
2439
+ for (const ch of channelsOf(out)) strip(ch);
2440
+ for (const lib of librariesOf(out)) {
2441
+ strip(lib);
2442
+ for (const t of templatesOf2(lib)) strip(t);
2443
+ }
2444
+ for (const g of groupsOf(out)) {
2445
+ strip(g);
2446
+ for (const member of isObj(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
2447
+ }
2448
+ return out;
2449
+ }
2450
+ function newerOnServer(tree, server) {
2451
+ const out = [];
2452
+ const compare = (kind, local, remote) => {
2453
+ const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
2454
+ for (const r of remote) {
2455
+ const rev = mine.get(idOf(r));
2456
+ if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
2457
+ }
2458
+ };
2459
+ compare("channel", channelsOf(tree), channelsOf(server));
2460
+ compare("library", librariesOf(tree), librariesOf(server));
2461
+ compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
2462
+ compare("channel group", groupsOf(tree), groupsOf(server));
2463
+ return out;
2464
+ }
2465
+ function libraryShape(lib) {
2466
+ const out = stripVolatile(lib);
2467
+ out["codeTemplates"] = templatesOf2(lib).map(idOf);
2468
+ return out;
2469
+ }
2470
+ function withRetainedMembers(local, remote, localIds, deletedIds) {
2471
+ const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
2472
+ if (!retained.length) return local;
2473
+ return { ...local, codeTemplates: {
2474
+ ...isObj(local["codeTemplates"]) ? local["codeTemplates"] : {},
2475
+ codeTemplate: [...templatesOf2(local), ...retained]
2476
+ } };
2477
+ }
2478
+ function hashGlobalScripts(c) {
2479
+ return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
2480
+ }
2481
+ function resourceIds(c) {
2482
+ const libs = librariesOf(c);
2483
+ const revs = (items) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));
2484
+ return {
2485
+ channels: revs(channelsOf(c)),
2486
+ libraries: revs(libs),
2487
+ codeTemplates: revs(libs.flatMap(templatesOf2)),
2488
+ globalScripts: hashGlobalScripts(c)
2489
+ };
2490
+ }
2491
+ function adoptTarget(local, target) {
2492
+ const config = structuredClone(local);
2493
+ const mine = resourceIds(local);
2494
+ const theirs = resourceIds(target);
2495
+ const intersect = (key) => Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));
2496
+ const known = {
2497
+ channels: intersect("channels"),
2498
+ libraries: intersect("libraries"),
2499
+ codeTemplates: intersect("codeTemplates"),
2500
+ globalScripts: theirs.globalScripts
2501
+ };
2502
+ const rebase = (items, revisions) => {
2503
+ for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
2504
+ };
2505
+ rebase(channelsOf(config), theirs.channels);
2506
+ rebase(librariesOf(config), theirs.libraries);
2507
+ rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
2508
+ return { config, known };
2509
+ }
2510
+ function knownFrom(raw) {
2511
+ if (!isObj(raw)) return void 0;
2512
+ const r = raw;
2513
+ const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
2514
+ return {
2515
+ channels: map(r["channels"]),
2516
+ libraries: map(r["libraries"]),
2517
+ codeTemplates: map(r["codeTemplates"]),
2518
+ globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
2519
+ };
2520
+ }
2521
+ function knownAfterPush(known, applied, touched, fresh) {
2522
+ const now = resourceIds(fresh);
2523
+ const next = {
2524
+ channels: { ...known.channels },
2525
+ libraries: { ...known.libraries },
2526
+ codeTemplates: { ...known.codeTemplates },
2527
+ globalScripts: known.globalScripts
1907
2528
  };
1908
2529
  const key = { channel: "channels", library: "libraries", codeTemplate: "codeTemplates" };
1909
2530
  for (const c of applied) {
@@ -2179,9 +2800,9 @@ function findChannel(c, id) {
2179
2800
  }
2180
2801
 
2181
2802
  // src/push/apply.ts
2182
- import { readdir as readdir2, writeFile as writeFile2 } from "fs/promises";
2183
- import { existsSync as existsSync2 } from "fs";
2184
- import * as path2 from "path";
2803
+ import { readdir as readdir4, writeFile as writeFile4 } from "fs/promises";
2804
+ import { existsSync as existsSync6 } from "fs";
2805
+ import * as path6 from "path";
2185
2806
  var ORDER = [
2186
2807
  ["codeTemplate", ["create", "update"]],
2187
2808
  ["library", ["create", "update", "delete"]],
@@ -2249,334 +2870,101 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
2249
2870
  }
2250
2871
  return { applied, touchedIds, sentLibraries };
2251
2872
  }
2252
- function checkResource(change, before, current, force) {
2253
- if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
2254
- 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`);
2255
- }
2256
- }
2257
- async function checkTemplate(client, change, remote, force) {
2258
- checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
2259
- }
2260
- async function withServerAssociations(client, channel, change, planned, force) {
2261
- const server = await client.getChannel(String(channel["id"]));
2262
- checkResource(change, planned, server, force);
2263
- if (change.op !== "update") return channel;
2264
- const serverExport = server?.["exportData"];
2265
- if (!serverExport) return channel;
2266
- const exportData = { ...channel["exportData"] ?? {} };
2267
- for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
2268
- return { ...channel, exportData };
2269
- }
2270
- async function deployChannels(client, ids, nameOf2) {
2271
- const deployed = [];
2272
- const skipped = [];
2273
- const failures = [];
2274
- for (const id of ids) {
2275
- try {
2276
- if (!(await client.getDeployedChannelIds()).has(id)) {
2277
- skipped.push(nameOf2(id));
2278
- continue;
2279
- }
2280
- await client.deployChannel(id);
2281
- deployed.push(nameOf2(id));
2282
- } catch (err) {
2283
- failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
2284
- }
2285
- }
2286
- return { deployed, skipped, failures };
2287
- }
2288
- function copyVersionFields(target, source) {
2289
- if (!source) return false;
2290
- let changed = false;
2291
- for (const key of ["revision", "lastModified"]) {
2292
- if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
2293
- target[key] = source[key];
2294
- changed = true;
2295
- }
2296
- }
2297
- const tm = target["exportData"]?.["metadata"];
2298
- const sm = source["exportData"]?.["metadata"];
2299
- if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
2300
- tm["lastModified"] = sm["lastModified"];
2301
- changed = true;
2302
- }
2303
- return changed;
2304
- }
2305
- async function jsonFiles(dir, name) {
2306
- if (!existsSync2(dir)) return [];
2307
- const entries = await readdir2(dir, { withFileTypes: true });
2308
- return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
2309
- }
2310
- async function refreshRevisions(root, server, ids) {
2311
- for (const file of await jsonFiles(path2.join(root, "channels"), "channel.json")) {
2312
- const json = await readJson(file);
2313
- if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
2314
- await writeFile2(file, JSON.stringify(json, null, 2));
2315
- }
2316
- }
2317
- const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
2318
- for (const file of await jsonFiles(path2.join(root, "codeTemplates"), "library.json")) {
2319
- const json = await readJson(file);
2320
- let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
2321
- const container = json["codeTemplates"];
2322
- for (const t of list(container?.["codeTemplate"])) {
2323
- if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
2324
- }
2325
- if (changed) await writeFile2(file, JSON.stringify(json, null, 2));
2326
- }
2327
- }
2328
-
2329
- // src/secrets/envfile.ts
2330
- import { randomBytes } from "crypto";
2331
- import { existsSync as existsSync3 } from "fs";
2332
- import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as readdir3, realpath as realpath2, rename, rm, writeFile as writeFile3 } from "fs/promises";
2333
- import * as path3 from "path";
2334
- import { parse } from "dotenv";
2335
- var BASE64_PREFIX = "cv-base64:";
2336
- function parseEnv(text) {
2337
- const out = parse(text);
2338
- for (const [k, v] of Object.entries(out)) {
2339
- if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
2340
- }
2341
- return out;
2342
- }
2343
- async function readEnvFile(file) {
2344
- if (!existsSync3(file)) return {};
2345
- return parseEnv(await readFile3(file, "utf8"));
2346
- }
2347
- function formatValue(value) {
2348
- const candidates = [
2349
- /^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
2350
- value.includes("'") ? null : `'${value}'`,
2351
- value.includes("`") ? null : `\`${value}\``,
2352
- value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
2353
- ];
2354
- for (const c of candidates) {
2355
- if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
2356
- }
2357
- return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
2358
- }
2359
- async function updateEnvFile(file, updates) {
2360
- const names = Object.keys(updates);
2361
- if (names.length === 0) return;
2362
- const existing = existsSync3(file) ? await readFile3(file, "utf8") : "";
2363
- const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
2364
- const written = /* @__PURE__ */ new Set();
2365
- const out = [];
2366
- let inQuote = null;
2367
- let dropping = false;
2368
- for (const line of lines) {
2369
- if (inQuote !== null) {
2370
- if (!dropping) out.push(line);
2371
- if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
2372
- continue;
2373
- }
2374
- const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
2375
- const q = m?.[2][0];
2376
- const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
2377
- if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
2378
- if (!written.has(m[1])) {
2379
- out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
2380
- written.add(m[1]);
2381
- }
2382
- if (opens) [inQuote, dropping] = [opens, true];
2383
- continue;
2384
- }
2385
- out.push(line);
2386
- if (opens) inQuote = opens;
2387
- }
2388
- for (const name of names) {
2389
- if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
2390
- }
2391
- const text = `${out.join("\n")}
2392
- `;
2393
- const readBack = parseEnv(text);
2394
- const wrong = names.filter((n) => readBack[n] !== updates[n]);
2395
- if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
2396
- const target = existsSync3(file) ? await realpath2(file) : file;
2397
- const temp = `${target}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
2398
- try {
2399
- await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
2400
- await rename(temp, target);
2401
- } catch (err) {
2402
- await rm(temp, { force: true });
2403
- throw err;
2404
- }
2405
- }
2406
- var ENV_BACKUPS_KEPT = 5;
2407
- async function backupEnvFile(file, updates, dir) {
2408
- if (!existsSync3(file)) return null;
2409
- const current = parseEnv(await readFile3(file, "utf8"));
2410
- if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
2411
- await mkdir2(dir, { recursive: true });
2412
- const prefix = `${path3.basename(file)}-`;
2413
- const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
2414
- let target = path3.join(dir, `${prefix}${stamp2}`);
2415
- for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
2416
- await copyFile(file, target);
2417
- await chmod(target, 384);
2418
- const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
2419
- for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
2420
- await rm(path3.join(dir, old));
2421
- }
2422
- return target;
2423
- }
2424
- var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
2425
- async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
2426
- const file = path3.join(dir, ".gitignore");
2427
- const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
2428
- const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
2429
- const wanted = [...IGNORE_LINES];
2430
- if (envFile) {
2431
- const rel = path3.relative(treeRoot, envFile).split(path3.sep).join("/");
2432
- const base = path3.basename(envFile);
2433
- const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
2434
- if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
2435
- }
2436
- const missing = wanted.filter((l) => !present2.has(l));
2437
- if (missing.length === 0) return false;
2438
- const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
2439
- await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
2440
- ${missing.join("\n")}
2441
- `);
2442
- return true;
2443
- }
2444
-
2445
- // src/backup/index.ts
2446
- import { randomBytes as randomBytes2 } from "crypto";
2447
- import { existsSync as existsSync4, realpathSync } from "fs";
2448
- import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
2449
- import * as path4 from "path";
2450
- var DEFAULT_BACKUP_DIR = ".backup";
2451
- var DEFAULT_KEEP = 10;
2452
- var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
2453
- function serverSlug(name) {
2454
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
2455
- }
2456
- function backupName(config, fallback) {
2457
- return configuredName(config) || serverSlug(fallback) || "mirth";
2458
- }
2459
- function configuredName(config) {
2460
- const settings = config["serverSettings"];
2461
- const field = (key) => {
2462
- const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
2463
- return typeof v === "string" ? serverSlug(v) : "";
2464
- };
2465
- return field("serverName") || field("environmentName");
2466
- }
2467
- function stamp(date) {
2468
- return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
2469
- }
2470
- async function listBackups(dir) {
2471
- if (!existsSync4(dir)) return [];
2472
- const out = [];
2473
- for (const name of await readdir4(dir)) {
2474
- const m = FILE_NAME.exec(name);
2475
- if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2476
- }
2477
- return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
2478
- }
2479
- var MANIFEST = "channelvault-backups.json";
2480
- async function readManifest(dir) {
2481
- const file = path4.join(dir, MANIFEST);
2482
- if (!existsSync4(file)) return {};
2483
- try {
2484
- const parsed = JSON.parse(await readFile4(file, "utf8"));
2485
- return parsed.files ?? {};
2486
- } catch (err) {
2487
- throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
2488
- }
2489
- }
2490
- async function writeManifest(dir, files) {
2491
- const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path4.join(dir, name))));
2492
- await writePrivate(path4.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
2493
- `);
2494
- }
2495
- async function backupsOf(dir, serverId) {
2496
- const manifest = await readManifest(dir);
2497
- return (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === serverId);
2498
- }
2499
- async function originOf(dir, file) {
2500
- if (!existsSync4(dir) || !sameFile(path4.dirname(file), dir)) return null;
2501
- return (await readManifest(dir))[path4.basename(file)] ?? null;
2502
- }
2503
- async function originsIn(dir) {
2504
- if (!existsSync4(dir)) return [];
2505
- const seen = /* @__PURE__ */ new Map();
2506
- for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);
2507
- return [...seen.values()];
2508
- }
2509
- async function saveBackup(dir, name, xml2, opts) {
2510
- await ensureBackupDir(dir);
2511
- const manifest = await readManifest(dir);
2512
- const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
2513
- let file = path4.join(dir, `${base}.xml`);
2514
- for (let n = 2; existsSync4(file); n += 1) file = path4.join(dir, `${base}-${n}.xml`);
2515
- await writePrivate(file, xml2);
2516
- manifest[path4.basename(file)] = opts.origin;
2517
- await writeManifest(dir, manifest);
2518
- const mine = (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === opts.origin.serverId);
2519
- for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
2520
- if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
2521
- await rm2(old.file);
2873
+ function checkResource(change, before, current, force) {
2874
+ if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
2875
+ 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`);
2522
2876
  }
2523
- await writeManifest(dir, manifest);
2524
- return file;
2525
2877
  }
2526
- function sameFile(a, b) {
2527
- const real = (p) => {
2528
- const resolved = existsSync4(p) ? realpathSync.native(p) : path4.resolve(p);
2529
- return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
2530
- };
2531
- return real(a) === real(b);
2878
+ async function checkTemplate(client, change, remote, force) {
2879
+ checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
2532
2880
  }
2533
- async function ensureBackupDir(dir) {
2534
- if (existsSync4(dir)) return;
2535
- await mkdir3(dir, { recursive: true });
2536
- await writeFile4(path4.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
2881
+ async function withServerAssociations(client, channel, change, planned, force) {
2882
+ const server = await client.getChannel(String(channel["id"]));
2883
+ checkResource(change, planned, server, force);
2884
+ if (change.op !== "update") return channel;
2885
+ const serverExport = server?.["exportData"];
2886
+ if (!serverExport) return channel;
2887
+ const exportData = { ...channel["exportData"] ?? {} };
2888
+ for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
2889
+ return { ...channel, exportData };
2537
2890
  }
2538
- async function writePrivate(file, text) {
2539
- const temp = `${file}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
2540
- try {
2541
- await writeFile4(temp, text, { encoding: "utf8", mode: 384 });
2542
- await rename2(temp, file);
2543
- } catch (err) {
2544
- await rm2(temp, { force: true });
2545
- throw err;
2891
+ async function deployChannels(client, ids, nameOf2) {
2892
+ const deployed = [];
2893
+ const skipped = [];
2894
+ const failures = [];
2895
+ for (const id of ids) {
2896
+ try {
2897
+ if (!(await client.getDeployedChannelIds()).has(id)) {
2898
+ skipped.push(nameOf2(id));
2899
+ continue;
2900
+ }
2901
+ await client.deployChannel(id);
2902
+ deployed.push(nameOf2(id));
2903
+ } catch (err) {
2904
+ failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
2905
+ }
2546
2906
  }
2907
+ return { deployed, skipped, failures };
2547
2908
  }
2548
- function numericVersion(v) {
2549
- const m = /^\d+(?:\.\d+)*/.exec(v.trim());
2550
- return m ? m[0].split(".").map(Number) : null;
2909
+ function copyVersionFields(target, source) {
2910
+ if (!source) return false;
2911
+ let changed = false;
2912
+ for (const key of ["revision", "lastModified"]) {
2913
+ if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
2914
+ target[key] = source[key];
2915
+ changed = true;
2916
+ }
2917
+ }
2918
+ const tm = target["exportData"]?.["metadata"];
2919
+ const sm = source["exportData"]?.["metadata"];
2920
+ if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
2921
+ tm["lastModified"] = sm["lastModified"];
2922
+ changed = true;
2923
+ }
2924
+ return changed;
2551
2925
  }
2552
- function compareVersions(a, b) {
2553
- const pa = numericVersion(a);
2554
- const pb = numericVersion(b);
2555
- for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
2556
- const d = (pa[i] ?? 0) - (pb[i] ?? 0);
2557
- if (d !== 0) return d;
2926
+ async function jsonFiles(dir, name) {
2927
+ if (!existsSync6(dir)) return [];
2928
+ const entries = await readdir4(dir, { withFileTypes: true });
2929
+ return entries.filter((e) => e.isDirectory()).map((e) => path6.join(dir, e.name, name)).filter((f) => existsSync6(f));
2930
+ }
2931
+ async function refreshRevisions(root, server, ids) {
2932
+ for (const file of await jsonFiles(path6.join(root, "channels"), "channel.json")) {
2933
+ const json = await readJson(file);
2934
+ if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
2935
+ await writeFile4(file, JSON.stringify(json, null, 2));
2936
+ }
2937
+ }
2938
+ const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
2939
+ for (const file of await jsonFiles(path6.join(root, "codeTemplates"), "library.json")) {
2940
+ const json = await readJson(file);
2941
+ let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
2942
+ const container = json["codeTemplates"];
2943
+ for (const t of list(container?.["codeTemplate"])) {
2944
+ if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
2945
+ }
2946
+ if (changed) await writeFile4(file, JSON.stringify(json, null, 2));
2558
2947
  }
2559
- return 0;
2560
2948
  }
2561
2949
 
2562
2950
  // src/xml/chars.ts
2563
2951
  import { readFile as readFile5 } from "fs/promises";
2564
- import * as path6 from "path";
2952
+ import * as path8 from "path";
2565
2953
 
2566
2954
  // src/tree/transaction.ts
2567
2955
  import { randomUUID } from "crypto";
2568
- import { constants, existsSync as existsSync5 } from "fs";
2569
- 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";
2956
+ import { constants, existsSync as existsSync7 } from "fs";
2957
+ import { copyFile as copyFile2, lstat as lstat3, mkdir as mkdir5, readdir as readdir5, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
2570
2958
  import { hostname } from "os";
2571
- import * as path5 from "path";
2959
+ import * as path7 from "path";
2572
2960
  import { setTimeout as delay } from "timers/promises";
2573
2961
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2574
2962
  async function treeFiles(base) {
2575
2963
  const out = [];
2576
2964
  for (const d of MANAGED_DIRS) {
2577
- if (!existsSync5(path5.join(base, d))) continue;
2578
- for (const entry of await readdir5(path5.join(base, d), { recursive: true, withFileTypes: true })) {
2579
- if (entry.isFile()) out.push(path5.relative(base, path5.join(entry.parentPath, entry.name)).split(path5.sep).join("/"));
2965
+ if (!existsSync7(path7.join(base, d))) continue;
2966
+ for (const entry of await readdir5(path7.join(base, d), { recursive: true, withFileTypes: true })) {
2967
+ if (entry.isFile()) out.push(path7.relative(base, path7.join(entry.parentPath, entry.name)).split(path7.sep).join("/"));
2580
2968
  }
2581
2969
  }
2582
2970
  return out;
@@ -2585,21 +2973,6 @@ var STAGING_DIR = ".channelvault-staging";
2585
2973
  var JOURNAL = ".channelvault-transaction.json";
2586
2974
  var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
2587
2975
  var RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
2588
- async function present(file) {
2589
- return lstat2(file).then(() => true, (err) => {
2590
- if (err.code === "ENOENT") return false;
2591
- throw err;
2592
- });
2593
- }
2594
- async function canonical(file, depth = 0) {
2595
- if (depth > 64) throw new Error(`too many links in path: ${file}`);
2596
- let existing = path5.resolve(file);
2597
- while (!await present(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
2598
- const info = await lstat2(existing);
2599
- const base = info.isSymbolicLink() ? await canonical(path5.resolve(path5.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2600
- return path5.join(base, path5.relative(existing, path5.resolve(file)));
2601
- }
2602
- var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
2603
2976
  async function move(from, to) {
2604
2977
  for (let attempt = 0; ; attempt++) {
2605
2978
  try {
@@ -2612,15 +2985,15 @@ async function move(from, to) {
2612
2985
  }
2613
2986
  }
2614
2987
  async function lockTree(root) {
2615
- await mkdir4(path5.dirname(root), { recursive: true });
2988
+ await mkdir5(path7.dirname(root), { recursive: true });
2616
2989
  const lock = `${await canonical(root)}.channelvault-lock`;
2617
- const ownerFile = path5.join(lock, "owner.json");
2990
+ const ownerFile = path7.join(lock, "owner.json");
2618
2991
  const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
2619
2992
  try {
2620
- await mkdir4(lock);
2993
+ await mkdir5(lock);
2621
2994
  } catch (err) {
2622
2995
  if (err.code !== "EEXIST") throw err;
2623
- if ((await lstat2(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
2996
+ if ((await lstat3(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
2624
2997
  let previous;
2625
2998
  try {
2626
2999
  previous = await readJson(ownerFile);
@@ -2637,9 +3010,9 @@ async function lockTree(root) {
2637
3010
  }
2638
3011
  };
2639
3012
  if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
2640
- const reaping = path5.join(lock, "reaping");
3013
+ const reaping = path7.join(lock, "reaping");
2641
3014
  try {
2642
- await mkdir4(reaping);
3015
+ await mkdir5(reaping);
2643
3016
  } catch {
2644
3017
  throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
2645
3018
  }
@@ -2651,7 +3024,7 @@ async function lockTree(root) {
2651
3024
  await rmdir(reaping);
2652
3025
  }
2653
3026
  await rmdir(lock);
2654
- await mkdir4(lock);
3027
+ await mkdir5(lock);
2655
3028
  }
2656
3029
  try {
2657
3030
  await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
@@ -2668,8 +3041,8 @@ async function lockTree(root) {
2668
3041
  }
2669
3042
  async function assertStage(root) {
2670
3043
  for (const suffix of ["", "next", "previous"]) {
2671
- const stage = path5.join(root, STAGING_DIR, suffix);
2672
- const info = await lstat2(stage).catch((err) => {
3044
+ const stage = path7.join(root, STAGING_DIR, suffix);
3045
+ const info = await lstat3(stage).catch((err) => {
2673
3046
  if (err.code !== "ENOENT") throw err;
2674
3047
  return void 0;
2675
3048
  });
@@ -2677,10 +3050,10 @@ async function assertStage(root) {
2677
3050
  }
2678
3051
  }
2679
3052
  function targetOf(root, journal, name) {
2680
- return name === "env" ? journal.envFile : path5.join(root, name);
3053
+ return name === "env" ? journal.envFile : path7.join(root, name);
2681
3054
  }
2682
3055
  function copies(root, journal, name) {
2683
- return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path5.join(root, STAGING_DIR, "previous", name), next: path5.join(root, STAGING_DIR, "next", name) };
3056
+ return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path7.join(root, STAGING_DIR, "previous", name), next: path7.join(root, STAGING_DIR, "next", name) };
2684
3057
  }
2685
3058
  async function cleanup(root, journal) {
2686
3059
  if (journal.entries.some((e) => e.name === "env")) {
@@ -2688,7 +3061,7 @@ async function cleanup(root, journal) {
2688
3061
  await rm3(old, { force: true });
2689
3062
  await rm3(next, { force: true });
2690
3063
  }
2691
- await rm3(path5.join(root, STAGING_DIR), RM);
3064
+ await rm3(path7.join(root, STAGING_DIR), RM);
2692
3065
  }
2693
3066
  async function rollback(root, journal) {
2694
3067
  for (const entry of [...journal.entries].reverse()) {
@@ -2702,12 +3075,19 @@ async function rollback(root, journal) {
2702
3075
  }
2703
3076
  }
2704
3077
  }
2705
- async function recoverTree(root, envFile) {
2706
- const file = path5.join(root, JOURNAL);
2707
- if (!existsSync5(file)) return;
3078
+ async function pendingEnvFile(root) {
3079
+ const file = path7.join(root, JOURNAL);
3080
+ if (!existsSync7(file)) return null;
3081
+ const journal = await readJson(file).catch(() => null);
3082
+ return typeof journal?.envFile === "string" ? journal.envFile : null;
3083
+ }
3084
+ async function recoverTree(root, envFiles) {
3085
+ const file = path7.join(root, JOURNAL);
3086
+ if (!existsSync7(file)) return;
2708
3087
  await assertStage(root);
2709
3088
  const journal = await readJson(file);
2710
- 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))) {
3089
+ const allowed = await Promise.all((Array.isArray(envFiles) ? envFiles : [envFiles]).map((f) => canonical(f)));
3090
+ 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))) {
2711
3091
  throw new Error(`invalid transaction journal or different env file: ${file}; use the original --dotenv selection to recover`);
2712
3092
  }
2713
3093
  if (journal.state === "prepared") await rollback(root, journal);
@@ -2717,56 +3097,56 @@ async function recoverTree(root, envFile) {
2717
3097
  async function replaceTree(root, envFile, prepare) {
2718
3098
  await recoverTree(root, envFile);
2719
3099
  await assertStage(root);
2720
- const stage = path5.join(root, STAGING_DIR);
3100
+ const stage = path7.join(root, STAGING_DIR);
2721
3101
  await rm3(stage, RM);
2722
- const next = path5.join(stage, "next");
2723
- await mkdir4(next, { recursive: true });
3102
+ const next = path7.join(stage, "next");
3103
+ await mkdir5(next, { recursive: true });
2724
3104
  let journal;
2725
3105
  try {
2726
3106
  await prepare(next);
2727
3107
  const targetEnv = await canonical(envFile);
2728
3108
  journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
2729
3109
  for (const name of ITEMS) {
2730
- if (!MANAGED_DIRS.includes(name) && !existsSync5(path5.join(next, name === "env" ? ".env" : name))) continue;
3110
+ if (!MANAGED_DIRS.includes(name) && !existsSync7(path7.join(next, name === "env" ? ".env" : name))) continue;
2731
3111
  const target = targetOf(root, journal, name);
2732
- const info = await lstat2(target).catch((err) => {
3112
+ const info = await lstat3(target).catch((err) => {
2733
3113
  if (err.code !== "ENOENT") throw err;
2734
3114
  return void 0;
2735
3115
  });
2736
3116
  journal.entries.push({ name, hadOld: info !== void 0 });
2737
3117
  }
2738
- await mkdir4(path5.join(stage, "previous"));
2739
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
3118
+ await mkdir5(path7.join(stage, "previous"));
3119
+ await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
2740
3120
  if (journal.entries.some((e) => e.name === "env")) {
2741
- await mkdir4(path5.dirname(targetEnv), { recursive: true });
2742
- await copyFile2(path5.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
3121
+ await mkdir5(path7.dirname(targetEnv), { recursive: true });
3122
+ await copyFile2(path7.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2743
3123
  }
2744
3124
  for (const entry of journal.entries) {
2745
3125
  const target = targetOf(root, journal, entry.name);
2746
3126
  const files = copies(root, journal, entry.name);
2747
3127
  if (entry.hadOld) await move(target, files.old);
2748
- if (existsSync5(files.next)) {
2749
- await mkdir4(path5.dirname(target), { recursive: true });
3128
+ if (existsSync7(files.next)) {
3129
+ await mkdir5(path7.dirname(target), { recursive: true });
2750
3130
  await move(files.next, target);
2751
3131
  }
2752
3132
  }
2753
3133
  journal.state = "committed";
2754
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
3134
+ await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
2755
3135
  } catch (err) {
2756
- if (journal && existsSync5(path5.join(root, JOURNAL))) {
3136
+ if (journal && existsSync7(path7.join(root, JOURNAL))) {
2757
3137
  try {
2758
3138
  await rollback(root, journal);
2759
3139
  } catch (recoveryError) {
2760
- throw new Error(`replacement failed and recovery is pending in ${path5.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
3140
+ throw new Error(`replacement failed and recovery is pending in ${path7.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2761
3141
  }
2762
3142
  await cleanup(root, journal);
2763
- await unlink(path5.join(root, JOURNAL));
3143
+ await unlink(path7.join(root, JOURNAL));
2764
3144
  }
2765
3145
  await rm3(stage, RM);
2766
3146
  throw err;
2767
3147
  }
2768
3148
  await cleanup(root, journal);
2769
- await unlink(path5.join(root, JOURNAL));
3149
+ await unlink(path7.join(root, JOURNAL));
2770
3150
  }
2771
3151
 
2772
3152
  // src/xml/chars.ts
@@ -2793,7 +3173,7 @@ function forbiddenXmlChars(config) {
2793
3173
  async function forbiddenInFiles(root) {
2794
3174
  const out = [];
2795
3175
  for (const file of await treeFiles(root)) {
2796
- for (const p of positions(await readFile5(path6.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
3176
+ for (const p of positions(await readFile5(path8.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
2797
3177
  }
2798
3178
  return out;
2799
3179
  }
@@ -2813,43 +3193,64 @@ async function xmlSafetyProblem(config, treeRoot) {
2813
3193
  var engine = createExplodeEngine();
2814
3194
  var xml = new XmlConfigAdapter();
2815
3195
  var VERSION = createRequire(import.meta.url)("../package.json").version;
2816
- var CliError = class extends Error {
3196
+ var CliError = class extends ReasonError {
2817
3197
  };
2818
- function fail(message) {
2819
- throw new CliError(message);
3198
+ function fail(message, reason) {
3199
+ throw new CliError(message, reason);
2820
3200
  }
2821
3201
  var errorExitCode = 1;
2822
3202
  var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
2823
- function resolveClientConfig(flags) {
2824
- const host = flags.host ?? process.env.MIRTH_HOST;
2825
- const portStr = flags.port ?? process.env.MIRTH_PORT;
2826
- const username = flags.user ?? process.env.MIRTH_USER;
2827
- const password = flags.pass ?? process.env.MIRTH_PASS;
2828
- if (!host) fail("no server host (pass --host or set MIRTH_HOST)");
2829
- if (!portStr) fail("no server port (pass --port or set MIRTH_PORT)");
2830
- if (!username) fail("no username (pass --user or set MIRTH_USER)");
2831
- if (password == null) fail("no password (pass --pass or set MIRTH_PASS)");
2832
- const port = Number(portStr);
2833
- if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);
3203
+ function addConnectionFlags(cmd) {
3204
+ 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");
3205
+ }
3206
+ function clientConfigOf(conn) {
2834
3207
  return {
2835
- host,
2836
- port,
2837
- username,
2838
- password,
2839
- https: flags.https !== false,
2840
- disableTlsCheck: flags.insecure === true,
3208
+ host: conn.host,
3209
+ port: conn.port,
3210
+ username: conn.user,
3211
+ password: conn.password,
3212
+ https: conn.https,
3213
+ disableTlsCheck: conn.insecure,
3214
+ ...conn.tlsFingerprint ? { tlsFingerprint: conn.tlsFingerprint } : {},
2841
3215
  // Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).
2842
3216
  includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG)
2843
3217
  };
2844
3218
  }
2845
- function addConnectionFlags(cmd) {
2846
- 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");
3219
+ var activeConnection;
3220
+ var loadedProfiles = {};
3221
+ async function selectConnection(root, flags, opts = {}) {
3222
+ loadedProfiles = await loadProfiles();
3223
+ const meta = root ? await readMeta(root) : null;
3224
+ const conn = resolveConnection({
3225
+ flags,
3226
+ env: process.env,
3227
+ profiles: loadedProfiles,
3228
+ credentials: await readCredentials(),
3229
+ ...meta?.serverId ? { treeServerId: meta.serverId } : {},
3230
+ write: opts.write === true,
3231
+ yes: flags.yes === true,
3232
+ explicit: opts.explicit === true
3233
+ });
3234
+ rememberSecret(conn.password, { stdout: true });
3235
+ activeConnection = conn;
3236
+ return conn;
3237
+ }
3238
+ function targetOf2(conn) {
3239
+ return conn.profile ? `${urlOf(conn)} (profile ${conn.profile})` : urlOf(conn);
2847
3240
  }
2848
- async function withClient(flags, fn) {
2849
- const client = createMirthClient(resolveClientConfig(flags));
3241
+ async function withClient(conn, fn, opts = {}) {
3242
+ const client = createMirthClient(clientConfigOf(conn));
2850
3243
  try {
2851
3244
  await client.login();
2852
- return await fn(client);
3245
+ const serverId = await client.getServerId();
3246
+ if (conn.serverId && serverId !== conn.serverId) {
3247
+ 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");
3248
+ }
3249
+ const owner = conn.source === "env" ? profileOwning(loadedProfiles, serverId) : void 0;
3250
+ if (owner) fail(`MIRTH_HOST reaches installation ${serverId}, which is profile ${owner}; use --profile ${owner}, or unset MIRTH_HOST`, "env-shadowed");
3251
+ if (!opts.quiet) process.stderr.write(`${describeConnection(conn, serverId, opts.envFile)}
3252
+ `);
3253
+ return await fn(client, serverId);
2853
3254
  } finally {
2854
3255
  await client.logout().catch(() => void 0);
2855
3256
  await client.close().catch(() => void 0);
@@ -2863,10 +3264,10 @@ function writeJson2(value) {
2863
3264
  `);
2864
3265
  }
2865
3266
  function addBackupDirFlags(cmd) {
2866
- return cmd.option("--backup-dir <dir>", `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`).option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
3267
+ 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})`);
2867
3268
  }
2868
3269
  function backupDirOf(flags) {
2869
- return path7.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
3270
+ return path9.resolve(flags.backupDir ?? defaultBackupDir());
2870
3271
  }
2871
3272
  function keepOf(flags) {
2872
3273
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -2874,9 +3275,8 @@ function keepOf(flags) {
2874
3275
  if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);
2875
3276
  return n;
2876
3277
  }
2877
- function serverNameOf(config, flags) {
2878
- const cfg = resolveClientConfig(flags);
2879
- return backupName(config, `${cfg.host}-${cfg.port}`);
3278
+ function serverNameOf(config, conn) {
3279
+ return backupName(config, `${conn.host}-${conn.port}`);
2880
3280
  }
2881
3281
  function parseBackup(text, where) {
2882
3282
  try {
@@ -2885,69 +3285,72 @@ function parseBackup(text, where) {
2885
3285
  fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);
2886
3286
  }
2887
3287
  }
2888
- async function saveServerBackup(client, text, flags, protect) {
3288
+ async function saveServerBackup(client, text, conn, flags, protect) {
2889
3289
  const config = parseBackup(text, "the server configuration");
2890
- const origin = { serverId: await client.getServerId(), host: hostOf(flags) };
2891
- const file = await saveBackup(backupDirOf(flags), serverNameOf(config, flags), text, { keep: keepOf(flags), origin, protect });
3290
+ const origin = { serverId: await client.getServerId(), host: hostOf(conn) };
3291
+ const file = await saveBackup(backupDirOf(flags), serverNameOf(config, conn), text, { keep: keepOf(flags), origin, protect });
2892
3292
  if (gitWouldCommit(file)) {
2893
3293
  process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore
2894
3294
  `);
2895
3295
  }
2896
3296
  return file;
2897
3297
  }
2898
- async function backupBeforePush(client, flags) {
3298
+ async function backupBeforePush(client, conn, flags) {
2899
3299
  if (flags.backup === false) return;
2900
- const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
2901
- process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, flags)})
3300
+ const file = await saveServerBackup(client, await client.getServerConfigurationXml(), conn, flags);
3301
+ process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, conn, flags)})
2902
3302
  `);
2903
- printUndoLimits(flags);
3303
+ printUndoLimits(conn, flags);
2904
3304
  }
2905
3305
  function shellArgument(value) {
2906
3306
  return process.platform === "win32" ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, "'\\''")}'`;
2907
3307
  }
2908
- function undoCommand(file, flags) {
2909
- const cfg = resolveClientConfig(flags);
2910
- const args = [
2911
- "channelvault",
2912
- "restore",
2913
- shellArgument(file),
2914
- "--host",
2915
- shellArgument(cfg.host),
2916
- "--port",
2917
- String(cfg.port),
2918
- "--user",
2919
- shellArgument(cfg.username),
2920
- "--backup-dir",
2921
- shellArgument(backupDirOf(flags))
2922
- ];
2923
- if (cfg.https === false) args.push("--no-https");
2924
- if (cfg.disableTlsCheck) args.push("--insecure");
3308
+ function undoCommand(file, conn, flags) {
3309
+ const args = ["channelvault", "restore", shellArgument(file)];
3310
+ if (conn.profile) {
3311
+ args.push("--profile", shellArgument(conn.profile));
3312
+ } else {
3313
+ args.push("--host", shellArgument(conn.host), "--port", String(conn.port), "--user", shellArgument(conn.user));
3314
+ if (!conn.https) args.push("--no-https");
3315
+ if (conn.tlsFingerprint) args.push("--tls-fingerprint", conn.tlsFingerprint);
3316
+ else if (conn.insecure) args.push("--insecure");
3317
+ }
3318
+ args.push("--backup-dir", shellArgument(backupDirOf(flags)));
2925
3319
  if (flags.overwriteConfigMap) args.push("--overwrite-config-map");
2926
3320
  return args.join(" ");
2927
3321
  }
2928
- function printUndoLimits(flags) {
2929
- 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");
3322
+ function printUndoLimits(conn, flags) {
3323
+ if (conn.passwordSource === "--pass") process.stdout.write("undo authentication: supply this server's password through MIRTH_PASS; it is omitted from the command\n");
2930
3324
  if (flags.deploy) process.stdout.write("the undo restores saved configuration; runtime deployment state is not in the backup. Review targeted redeployment separately\n");
2931
3325
  }
2932
- function hostOf(flags) {
2933
- const cfg = resolveClientConfig(flags);
2934
- return `${cfg.host}:${cfg.port}`;
3326
+ function hostOf(conn) {
3327
+ return `${conn.host}:${conn.port}`;
2935
3328
  }
2936
- async function confirm(question) {
2937
- const rl = createInterface({ input: process.stdin, output: process.stdout });
3329
+ async function ask(question, opts = {}) {
3330
+ let output = process.stdout;
3331
+ if (opts.secret) {
3332
+ process.stdout.write(question);
3333
+ output = new Writable({ write: (_chunk, _enc, done) => done() });
3334
+ }
3335
+ const rl = createInterface({ input: process.stdin, output, terminal: opts.secret ? Boolean(process.stdin.isTTY) : void 0 });
2938
3336
  const controller = new AbortController();
2939
3337
  rl.once("close", () => controller.abort());
2940
3338
  rl.once("SIGINT", () => controller.abort());
2941
3339
  try {
2942
- const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();
2943
- return answer === "y" || answer === "yes";
3340
+ const answer = await rl.question(opts.secret ? "" : question, { signal: controller.signal });
3341
+ if (opts.secret) process.stdout.write("\n");
3342
+ return opts.secret ? answer : answer.trim();
2944
3343
  } catch (err) {
2945
- if (controller.signal.aborted) fail("confirmation interrupted; nothing was pushed");
3344
+ if (controller.signal.aborted) fail("confirmation interrupted; nothing was changed");
2946
3345
  throw err;
2947
3346
  } finally {
2948
3347
  rl.close();
2949
3348
  }
2950
3349
  }
3350
+ async function confirm(question) {
3351
+ const answer = (await ask(`${question} [y/N] `)).toLowerCase();
3352
+ return answer === "y" || answer === "yes";
3353
+ }
2951
3354
  function summarize(config) {
2952
3355
  const asArray2 = (v) => Array.isArray(v) ? v : v == null ? [] : [v];
2953
3356
  const channels = asArray2(config.channels?.channel);
@@ -2969,6 +3372,22 @@ function summarize(config) {
2969
3372
  codeTemplates
2970
3373
  };
2971
3374
  }
3375
+ async function readMeta(root) {
3376
+ const metaPath = path9.join(root, "channelvault.json");
3377
+ if (!existsSync8(metaPath)) return null;
3378
+ let meta;
3379
+ try {
3380
+ meta = await readJson(metaPath);
3381
+ } catch (err) {
3382
+ meta = err;
3383
+ }
3384
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
3385
+ fail(
3386
+ `${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.`
3387
+ );
3388
+ }
3389
+ return meta;
3390
+ }
2972
3391
  async function writeMeta(root, source, config, previous, serverId, resources = resourceIds(config)) {
2973
3392
  const meta = {
2974
3393
  tool: "channelvault",
@@ -2980,43 +3399,76 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
2980
3399
  resources,
2981
3400
  serverId
2982
3401
  };
2983
- const file = path7.join(root, "channelvault.json");
3402
+ const file = path9.join(root, "channelvault.json");
2984
3403
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
2985
3404
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
2986
3405
  }
2987
- function envFilePath(root, flags) {
2988
- return flags.dotenv ? path7.resolve(flags.dotenv) : path7.join(root, ".env");
3406
+ async function envFileFor(root, flags, conn) {
3407
+ if (flags.dotenv) return path9.resolve(flags.dotenv);
3408
+ const local = path9.join(root, ".env");
3409
+ if (!conn?.dotenv) return local;
3410
+ if (!existsSync8(local) || samePath(await canonical(local), await canonical(conn.dotenv))) {
3411
+ await assertNoSwapPending(conn.dotenv);
3412
+ return conn.dotenv;
3413
+ }
3414
+ fail(`both ${local} and profile ${conn.profile}'s env file ${conn.dotenv} exist; pass --dotenv to choose one, or remove the one that is stale`, "env-ambiguous");
3415
+ }
3416
+ async function assertNoSwapPending(file) {
3417
+ const dir = path9.dirname(file);
3418
+ if (!existsSync8(dir)) return;
3419
+ const prefix = `${path9.basename(file)}.channelvault-`;
3420
+ const pending = (await readdir6(dir)).filter((n) => n.startsWith(prefix) && /\.(next|previous)$/.test(n));
3421
+ if (pending.length > 0) {
3422
+ fail(`${file} is being replaced by a pull in another checkout (${pending.join(", ")} beside it); retry when it finishes, or rerun that checkout's command to finish an interrupted one`, "env-busy");
3423
+ }
3424
+ }
3425
+ async function recoveryCandidates(root, flags) {
3426
+ if (flags.dotenv) return [path9.resolve(flags.dotenv)];
3427
+ const dotenvs = Object.values(await loadProfiles()).flatMap((p) => p.dotenv ? [p.dotenv] : []);
3428
+ return [path9.join(root, ".env"), ...dotenvs];
2989
3429
  }
2990
3430
  async function loadEnv(file) {
2991
3431
  return { ...await readEnvFile(file), ...process.env };
2992
3432
  }
2993
3433
  function addEnvFlag(cmd) {
2994
- return cmd.option("--dotenv <path>", "env file holding secrets and per-environment values (default <dir>/.env)");
3434
+ return cmd.option("--dotenv <path>", "env file holding the tree's placeholder values, not the login (default <dir>/.env)");
2995
3435
  }
2996
3436
  function addExtractFlag(cmd) {
2997
3437
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
2998
3438
  }
2999
3439
  async function existingTree(root) {
3000
- return existsSync6(path7.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3440
+ return existsSync8(path9.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3001
3441
  }
3002
- async function renderedTree(root, flags) {
3442
+ async function renderedTree(root, envFile) {
3003
3443
  const tree = await engine.implode({ root });
3004
- const env = await loadEnv(envFilePath(root, flags));
3444
+ const env = await loadEnv(envFile);
3005
3445
  rememberSecrets(tree, env);
3006
3446
  return render(tree, env);
3007
3447
  }
3008
3448
  var knownSecrets = /* @__PURE__ */ new Set();
3449
+ var everywhereSecrets = /* @__PURE__ */ new Set();
3450
+ function rememberSecret(value, opts = {}) {
3451
+ if (value === void 0 || value.length < 4) return;
3452
+ knownSecrets.add(value);
3453
+ if (opts.stdout && value.length >= 8) everywhereSecrets.add(value);
3454
+ }
3009
3455
  function rememberSecrets(tree, env) {
3010
3456
  mapLeaves(tree, (value) => {
3011
- for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) {
3012
- const secret = env[m[1]];
3013
- if (secret !== void 0 && secret.length >= 4) knownSecrets.add(secret);
3014
- }
3457
+ for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) rememberSecret(env[m[1]]);
3015
3458
  return value;
3016
3459
  });
3017
3460
  }
3018
- function scrub(text) {
3019
- const forms = [...knownSecrets].flatMap((s) => [
3461
+ for (const stream of [process.stdout, process.stderr]) {
3462
+ const write = stream.write.bind(stream);
3463
+ stream.write = ((chunk, ...rest) => {
3464
+ if (everywhereSecrets.size === 0) return write(chunk, ...rest);
3465
+ if (typeof chunk === "string") return write(scrub(chunk, everywhereSecrets), ...rest);
3466
+ if (Buffer.isBuffer(chunk)) return write(Buffer.from(scrub(chunk.toString("utf8"), everywhereSecrets), "utf8"), ...rest);
3467
+ return write(chunk, ...rest);
3468
+ });
3469
+ }
3470
+ function scrub(text, secrets = knownSecrets) {
3471
+ const forms = [...secrets].flatMap((s) => [
3020
3472
  s,
3021
3473
  JSON.stringify(s).slice(1, -1),
3022
3474
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;"),
@@ -3026,13 +3478,12 @@ function scrub(text) {
3026
3478
  }
3027
3479
  var ALLOW_FILE = "channelvault.allow.json";
3028
3480
  async function readAllow(root) {
3029
- const file = path7.join(root, ALLOW_FILE);
3030
- if (!existsSync6(file)) return [];
3481
+ const file = path9.join(root, ALLOW_FILE);
3482
+ if (!existsSync8(file)) return [];
3031
3483
  const parsed = await readJson(file);
3032
3484
  return parsed.ignore ?? [];
3033
3485
  }
3034
- async function writeTree(root, fetched, source, flags, serverId) {
3035
- const envFile = envFilePath(root, flags);
3486
+ async function writeTree(root, fetched, source, flags, envFile, serverId) {
3036
3487
  const previousMeta = await preflightTree(root, envFile);
3037
3488
  const env = await loadEnv(envFile);
3038
3489
  const templated = templatize(fetched, await existingTree(root), env);
@@ -3052,27 +3503,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3052
3503
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
3053
3504
  rememberSecrets(config, { ...env, ...envUpdates });
3054
3505
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3055
- const rel = path7.relative(root, envFile);
3056
- const envInTree = !rel.startsWith("..") && !path7.isAbsolute(rel);
3506
+ const rel = path9.relative(root, envFile);
3507
+ const envInTree = !rel.startsWith("..") && !path9.isAbsolute(rel);
3057
3508
  let backup = null;
3058
3509
  await replaceTree(root, envFile, async (next) => {
3059
3510
  await engine.explode(config, { root: next });
3060
3511
  await writeMeta(next, source, fetched, previousMeta, serverId);
3061
3512
  if (Object.keys(envUpdates).length > 0) {
3062
- const history = path7.join(root, ".secrets");
3063
- if (existsSync6(history)) {
3064
- if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3065
- await cp(history, path7.join(next, ".secrets"), { recursive: true });
3513
+ const history = path9.join(root, ".secrets");
3514
+ if (existsSync8(history)) {
3515
+ if ((await lstat4(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3516
+ await cp(history, path9.join(next, ".secrets"), { recursive: true });
3066
3517
  }
3067
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path7.join(next, ".secrets"));
3068
- if (stagedBackup) backup = path7.join(root, ".secrets", path7.basename(stagedBackup));
3518
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path9.join(next, ".secrets"));
3519
+ if (stagedBackup) backup = path9.join(root, ".secrets", path9.basename(stagedBackup));
3069
3520
  if (backup || envInTree) {
3070
- const ignore = path7.join(root, ".gitignore");
3071
- if (existsSync6(ignore)) await writeFile6(path7.join(next, ".gitignore"), await readFile6(ignore));
3521
+ const ignore = path9.join(root, ".gitignore");
3522
+ if (existsSync8(ignore)) await writeFile6(path9.join(next, ".gitignore"), await readFile6(ignore));
3072
3523
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3073
3524
  }
3074
- const stagedEnv = path7.join(next, ".env");
3075
- if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3525
+ const stagedEnv = path9.join(next, ".env");
3526
+ if (existsSync8(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3076
3527
  await updateEnvFile(stagedEnv, envUpdates);
3077
3528
  }
3078
3529
  });
@@ -3089,48 +3540,24 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3089
3540
  process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
3090
3541
  `);
3091
3542
  }
3092
- if (existsSync6(envFile) && gitWouldCommit(envFile)) {
3543
+ if (existsSync8(envFile) && gitWouldCommit(envFile)) {
3093
3544
  process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
3094
3545
  `);
3095
3546
  }
3096
3547
  }
3097
3548
  function gitWouldCommit(file) {
3098
- const r = spawnSync("git", ["check-ignore", "-q", path7.basename(file)], { cwd: path7.dirname(file) });
3549
+ const r = spawnSync2("git", ["check-ignore", "-q", path9.basename(file)], { cwd: path9.dirname(file) });
3099
3550
  return r.status === 1;
3100
3551
  }
3101
- async function resolvedPath(p) {
3102
- const abs = path7.resolve(p);
3103
- let existing = abs;
3104
- while (!existsSync6(existing) && path7.dirname(existing) !== existing) existing = path7.dirname(existing);
3105
- return path7.join(await realpath4(existing), path7.relative(existing, abs));
3106
- }
3107
- function isWithin(child, parent) {
3108
- const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
3109
- const rel = path7.relative(norm(parent), norm(child));
3110
- return rel === "" || rel !== ".." && !rel.startsWith(`..${path7.sep}`) && !path7.isAbsolute(rel);
3111
- }
3112
3552
  async function preflightTree(root, envFile) {
3113
3553
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3114
3554
  const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
3115
- (d) => isWithin(path7.resolve(envFile), path7.resolve(root, d)) || isWithin(realEnv, path7.join(realRoot, d))
3555
+ (d) => isWithin(path9.resolve(envFile), path9.resolve(root, d)) || isWithin(realEnv, path9.join(realRoot, d))
3116
3556
  );
3117
3557
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3118
- const metaPath = path7.join(root, "channelvault.json");
3119
- if (existsSync6(metaPath)) {
3120
- let meta;
3121
- try {
3122
- meta = await readJson(metaPath);
3123
- } catch (err) {
3124
- meta = err;
3125
- }
3126
- if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
3127
- fail(
3128
- `${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.`
3129
- );
3130
- }
3131
- return meta;
3132
- }
3133
- const foreign = MANAGED_DIRS.filter((d) => existsSync6(path7.join(root, d)));
3558
+ const meta = await readMeta(root);
3559
+ if (meta) return meta;
3560
+ const foreign = MANAGED_DIRS.filter((d) => existsSync8(path9.join(root, d)));
3134
3561
  if (foreign.length > 0) {
3135
3562
  fail(
3136
3563
  `${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).`
@@ -3139,16 +3566,14 @@ async function preflightTree(root, envFile) {
3139
3566
  return null;
3140
3567
  }
3141
3568
  function assertTree(root) {
3142
- if (!existsSync6(path7.join(root, "server", "configuration.json"))) {
3569
+ if (!existsSync8(path9.join(root, "server", "configuration.json"))) {
3143
3570
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3144
3571
  }
3145
3572
  }
3146
3573
  async function readTreeOrigin(root) {
3147
- const metaPath = path7.join(root, "channelvault.json");
3148
- if (!existsSync6(metaPath)) return "unknown";
3149
3574
  try {
3150
- const meta = await readJson(metaPath);
3151
- if (typeof meta.source === "string") {
3575
+ const meta = await readMeta(root);
3576
+ if (typeof meta?.source === "string") {
3152
3577
  if (meta.source.startsWith("file:")) return "xml";
3153
3578
  if (/^https?:\/\//i.test(meta.source)) return "live";
3154
3579
  }
@@ -3173,31 +3598,27 @@ function collect(value, previous) {
3173
3598
  return [...previous ?? [], value];
3174
3599
  }
3175
3600
  async function bindingProblems(root, serverId) {
3176
- const file = path7.join(root, "channelvault.json");
3177
- const meta = existsSync6(file) ? await readJson(file) : null;
3601
+ const meta = await readMeta(root);
3178
3602
  if (meta?.serverId === serverId) return [];
3179
3603
  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`];
3180
3604
  }
3181
3605
  async function xmlProblems(root, config) {
3182
- const problem = await xmlSafetyProblem(config, root);
3183
- return problem ? [problem] : [];
3606
+ const problem2 = await xmlSafetyProblem(config, root);
3607
+ return problem2 ? [problem2] : [];
3184
3608
  }
3185
3609
  async function assertBinding(client, root) {
3186
3610
  const problems = await bindingProblems(root, await client.getServerId());
3187
3611
  if (problems.length) fail(problems.join("\n"));
3188
3612
  }
3189
3613
  async function readKnown(root) {
3190
- const metaPath = path7.join(root, "channelvault.json");
3191
- if (!existsSync6(metaPath)) return void 0;
3192
- return knownFrom((await readJson(metaPath)).resources);
3614
+ const meta = await readMeta(root);
3615
+ return meta ? knownFrom(meta.resources) : void 0;
3193
3616
  }
3194
3617
  async function writeKnown(root, known) {
3195
- const metaPath = path7.join(root, "channelvault.json");
3196
- if (!existsSync6(metaPath)) return;
3197
- const meta = await readJson(metaPath);
3198
- if (!meta.resources) return;
3618
+ const meta = await readMeta(root);
3619
+ if (!meta?.resources) return;
3199
3620
  meta.resources = known;
3200
- await writeFile6(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf8");
3621
+ await writeFile6(path9.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
3201
3622
  }
3202
3623
  function printNameChange(incoming, current) {
3203
3624
  const [to, from] = [configuredName(incoming), configuredName(current)];
@@ -3234,12 +3655,13 @@ function wholeServerProblems(plan, flags) {
3234
3655
  if (plan.conflicts.length > 0 && !flags.force) problems.push(...planProblems({ ...plan, changes: [] }, flags));
3235
3656
  return problems;
3236
3657
  }
3237
- function reportPlanOnly(flags, plan, problems, extra) {
3658
+ function reportPlanOnly(flags, plan, problems, live, extra) {
3238
3659
  if (flags.json) {
3239
3660
  writeJson2({
3240
3661
  target: extra.target,
3241
3662
  mode: extra.mode,
3242
- ...extra.serverId ? { serverId: extra.serverId } : {},
3663
+ serverId: live.serverId,
3664
+ connection: connectionJson(live.conn, live.serverId, live.envFile),
3243
3665
  changes: plan.changes,
3244
3666
  conflicts: plan.conflicts,
3245
3667
  serverOnly: plan.serverOnly,
@@ -3253,11 +3675,11 @@ function reportPlanOnly(flags, plan, problems, extra) {
3253
3675
  `);
3254
3676
  process.stdout.write("plan only: nothing was changed\n");
3255
3677
  }
3256
- async function scopedPush(client, root, local, scope, target, flags) {
3678
+ async function scopedPush(client, root, local, scope, target, flags, live) {
3257
3679
  const remote = await client.getServerConfiguration();
3258
3680
  const known = await readKnown(root);
3259
3681
  const plan = planPush(local, remote, scope, known);
3260
- const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3682
+ const problems = [...await bindingProblems(root, live.serverId), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3261
3683
  const names = new Map(
3262
3684
  [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
3263
3685
  );
@@ -3267,7 +3689,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
3267
3689
  const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
3268
3690
  if (flags.planOnly && flags.json) {
3269
3691
  const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
3270
- reportPlanOnly(flags, plan, problems, { target, mode: "scoped", ...redeploy });
3692
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped", ...redeploy });
3271
3693
  return;
3272
3694
  }
3273
3695
  if (plan.changes.length === 0) {
@@ -3293,7 +3715,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
3293
3715
  `);
3294
3716
  }
3295
3717
  if (flags.planOnly) {
3296
- reportPlanOnly(flags, plan, problems, { target, mode: "scoped" });
3718
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped" });
3297
3719
  return;
3298
3720
  }
3299
3721
  if (problems.length > 0) fail(problems.join("\n"));
@@ -3309,7 +3731,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
3309
3731
  ${moved.join("\n ")}
3310
3732
  pull and try again, or pass --force`);
3311
3733
  }
3312
- await backupBeforePush(client, flags);
3734
+ await backupBeforePush(client, live.conn, flags);
3313
3735
  const afterBackup = await client.getServerConfiguration();
3314
3736
  const changedDuringBackup = changedSince(plan, fresh, afterBackup);
3315
3737
  if (!flags.force && changedDuringBackup.length) {
@@ -3372,9 +3794,26 @@ ${baselineError}` : ""}`);
3372
3794
  not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3373
3795
  fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3374
3796
  }
3797
+ printCommitHint(root);
3798
+ }
3799
+ function printCommitHint(root) {
3800
+ const r = spawnSync2("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
3801
+ if (r.status !== 0 || !r.stdout) return;
3802
+ const entries = r.stdout.split("\0");
3803
+ const files = [];
3804
+ for (let i = 0; i < entries.length; i++) {
3805
+ const entry = entries[i];
3806
+ if (entry.length < 4) continue;
3807
+ files.push(entry.slice(3));
3808
+ if (entry[0] === "R" || entry[0] === "C") i++;
3809
+ }
3810
+ if (files.length === 0) return;
3811
+ const shown = files.length > 10 ? [...files.slice(0, 10), `and ${files.length - 10} more`] : files;
3812
+ process.stdout.write(`commit the refreshed baseline with your change (paths from the repository root): ${shown.join(", ")}
3813
+ `);
3375
3814
  }
3376
3815
  function exportBrokenHint(flags) {
3377
- const undo = flags.backup === false ? "" : " (including the undo command above)";
3816
+ const undo = flags.backup === false ? "" : " (including the undo command above, unless you add --export-broken to it, which restores without a preview or an undo backup)";
3378
3817
  return `If the server cannot export its configuration, pull, diff, push and restore${undo} fail until the resource that broke it is fixed in the Administrator; then pull or adopt to refresh the baseline`;
3379
3818
  }
3380
3819
  async function changedAgainSingly(client, applied, local) {
@@ -3396,13 +3835,13 @@ async function changedAgainSingly(client, applied, local) {
3396
3835
  }
3397
3836
  return { changed, unverified };
3398
3837
  }
3399
- async function wholeServerPush(client, root, local, target, flags) {
3838
+ async function wholeServerPush(client, root, local, target, flags, live) {
3400
3839
  const remote = await client.getServerConfiguration();
3401
3840
  const known = await readKnown(root);
3402
3841
  const plan = planPush(local, remote, {}, known, { wholeReplace: true });
3403
- const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
3842
+ const problems = [...await bindingProblems(root, live.serverId), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
3404
3843
  if (flags.planOnly && flags.json) {
3405
- reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
3844
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
3406
3845
  return;
3407
3846
  }
3408
3847
  const s = summarize(local);
@@ -3423,7 +3862,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3423
3862
  `);
3424
3863
  if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
3425
3864
  if (flags.planOnly) {
3426
- reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
3865
+ reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
3427
3866
  return;
3428
3867
  }
3429
3868
  if (problems.length > 0) fail(problems.join("\n"));
@@ -3439,7 +3878,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3439
3878
  if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some((c) => c.op === "delete"))) {
3440
3879
  fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
3441
3880
  }
3442
- await backupBeforePush(client, flags);
3881
+ await backupBeforePush(client, live.conn, flags);
3443
3882
  const afterBackup = await client.getServerConfiguration();
3444
3883
  if (!sameServerConfig(fresh, afterBackup) && !flags.force) fail("the server changed during backup; pull and try again");
3445
3884
  const finalPlan = planPush(local, afterBackup, {}, known, { wholeReplace: true });
@@ -3465,6 +3904,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3465
3904
  if (known) await writeKnown(root, resourceIds(after));
3466
3905
  process.stdout.write(`pushed ${root} -> ${target}
3467
3906
  `);
3907
+ printCommitHint(root);
3468
3908
  }
3469
3909
  var program = new Command();
3470
3910
  program.name("channelvault").description("Git-style pull/push/diff for Mirth Connect").version(VERSION).allowExcessArguments(false);
@@ -3472,8 +3912,8 @@ addExtractFlag(addEnvFlag(
3472
3912
  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")
3473
3913
  )).action(async (backupPath, dir, flags) => {
3474
3914
  const config = xml.parse(await readFile6(backupPath, "utf8"));
3475
- const root = path7.resolve(dir);
3476
- await writeTree(root, config, `file:${path7.resolve(backupPath)}`, flags);
3915
+ const root = path9.resolve(dir);
3916
+ await writeTree(root, config, `file:${path9.resolve(backupPath)}`, flags, await envFileFor(root, flags));
3477
3917
  const s = summarize(config);
3478
3918
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3479
3919
  `);
@@ -3481,28 +3921,32 @@ addExtractFlag(addEnvFlag(
3481
3921
  addEnvFlag(
3482
3922
  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)
3483
3923
  ).action(async (dir, outPath, flags) => {
3484
- const root = path7.resolve(dir);
3924
+ const root = path9.resolve(dir);
3485
3925
  assertTree(root);
3486
- const config = await renderedTree(root, flags);
3926
+ const config = await renderedTree(root, await envFileFor(root, flags));
3487
3927
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3488
3928
  const xmlStr = xml.build(config);
3489
3929
  await writeFile6(outPath, xmlStr, "utf8");
3490
- process.stdout.write(`imploded ${root} -> ${path7.resolve(outPath)}
3930
+ process.stdout.write(`imploded ${root} -> ${path9.resolve(outPath)}
3491
3931
  `);
3492
3932
  });
3493
3933
  addExtractFlag(addEnvFlag(addConnectionFlags(
3494
3934
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3495
3935
  ))).action(async (dir, flags) => {
3496
- const root = path7.resolve(dir);
3497
- await preflightTree(root, envFilePath(root, flags));
3498
- const { config, serverId } = await withClient(flags, async (client) => {
3499
- const serverId2 = await client.getServerId();
3936
+ const root = path9.resolve(dir);
3937
+ const conn = await selectConnection(root, flags);
3938
+ const envFile = await envFileFor(root, flags, conn);
3939
+ if (!isWithin(path9.resolve(envFile), root)) await lockAlso(envFile);
3940
+ const previous = await preflightTree(root, envFile);
3941
+ const { config, serverId } = await withClient(conn, async (client, serverId2) => {
3942
+ if (previous?.serverId && previous.serverId !== serverId2) {
3943
+ 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");
3944
+ }
3500
3945
  const config2 = await client.getServerConfiguration();
3501
3946
  if (await client.getServerId() !== serverId2) fail("the installation changed while pulling; nothing was written");
3502
3947
  return { config: config2, serverId: serverId2 };
3503
- });
3504
- const cfg = resolveClientConfig(flags);
3505
- await writeTree(root, config, `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`, flags, serverId);
3948
+ }, { envFile });
3949
+ await writeTree(root, config, urlOf(conn), flags, envFile, serverId);
3506
3950
  const s = summarize(config);
3507
3951
  process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3508
3952
  `);
@@ -3510,23 +3954,23 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3510
3954
  addJsonFlag(addEnvFlag(addConnectionFlags(
3511
3955
  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)
3512
3956
  ))).action(async (dir, flags) => {
3513
- const root = path7.resolve(dir);
3957
+ const root = path9.resolve(dir);
3514
3958
  assertTree(root);
3515
- const previous = await preflightTree(root, envFilePath(root, flags));
3516
- const stored = await engine.implode({ root });
3517
- const local = await renderedTree(root, flags);
3518
- await assertCompatibleOrigin(root, local, "live", false);
3519
3959
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
3520
3960
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
3521
- const cfg = resolveClientConfig(flags);
3522
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3523
- await withClient(flags, async (client) => {
3524
- const serverId = await client.getServerId();
3961
+ const conn = await selectConnection(void 0, flags, { write: !flags.planOnly, explicit: true });
3962
+ const envFile = await envFileFor(root, flags, conn);
3963
+ const previous = await preflightTree(root, envFile);
3964
+ const stored = await engine.implode({ root });
3965
+ const local = await renderedTree(root, envFile);
3966
+ await assertCompatibleOrigin(root, local, "live", false);
3967
+ const target = urlOf(conn);
3968
+ await withClient(conn, async (client, serverId) => {
3525
3969
  const remote = await client.getServerConfiguration();
3526
3970
  const adopted = adoptTarget(local, remote);
3527
3971
  const plan = planPush(adopted.config, remote, {}, adopted.known);
3528
3972
  if (!flags.json) {
3529
- process.stdout.write(`Adopt ${target} (installation ${serverId}) as this tree's baseline.
3973
+ process.stdout.write(`Adopt ${targetOf2(conn)} (installation ${serverId}) as this tree's baseline.
3530
3974
  Local content is preserved; the following differences become reviewed edits for a subsequent push:
3531
3975
  `);
3532
3976
  printChanges(plan);
@@ -3536,7 +3980,7 @@ Local content is preserved; the following differences become reviewed edits for
3536
3980
  `);
3537
3981
  }
3538
3982
  if (flags.planOnly) {
3539
- reportPlanOnly(flags, plan, planProblems(plan, {}), { target, mode: "adopt", serverId });
3983
+ reportPlanOnly(flags, plan, planProblems(plan, {}), { conn, serverId, envFile }, { target, mode: "adopt" });
3540
3984
  return;
3541
3985
  }
3542
3986
  if (!flags.yes && !await confirm("Accept this baseline?")) {
@@ -3547,14 +3991,14 @@ Local content is preserved; the following differences become reviewed edits for
3547
3991
  fail("the target changed while adopting; nothing was written. Review the new baseline and try again");
3548
3992
  }
3549
3993
  if (!sameServerConfig(stored, await engine.implode({ root }))) fail("the local tree changed while adopting; nothing was written");
3550
- await replaceTree(root, envFilePath(root, flags), async (next) => {
3994
+ await replaceTree(root, envFile, async (next) => {
3551
3995
  const rebased = adoptTarget(stored, remote);
3552
3996
  await engine.explode(rebased.config, { root: next });
3553
3997
  await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
3554
3998
  });
3555
3999
  process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
3556
4000
  `);
3557
- });
4001
+ }, { envFile, quiet: flags.json });
3558
4002
  });
3559
4003
  addBackupDirFlags(addEnvFlag(addConnectionFlags(
3560
4004
  program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
@@ -3564,36 +4008,38 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3564
4008
  fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
3565
4009
  }
3566
4010
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
3567
- const root = path7.resolve(dir);
4011
+ const root = path9.resolve(dir);
3568
4012
  assertTree(root);
3569
- const config = await renderedTree(root, flags);
3570
- await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
3571
- const cfg = resolveClientConfig(flags);
3572
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3573
4013
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
3574
4014
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {
3575
4015
  fail("no terminal to confirm on; review with `push --plan-only` or `diff`, and pass --yes");
3576
4016
  }
4017
+ const conn = await selectConnection(root, flags, { write: !flags.planOnly });
4018
+ const envFile = await envFileFor(root, flags, conn);
4019
+ const config = await renderedTree(root, envFile);
4020
+ await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
4021
+ const target = targetOf2(conn);
4022
+ const quiet = flags.json === true;
3577
4023
  if (flags.wholeServer) {
3578
- await withClient(flags, (client) => wholeServerPush(client, root, config, target, flags));
4024
+ await withClient(conn, (client, serverId) => wholeServerPush(client, root, config, target, flags, { conn, serverId, envFile }), { envFile, quiet });
3579
4025
  return;
3580
4026
  }
3581
4027
  const scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
3582
- await withClient(flags, (client) => scopedPush(client, root, config, scope, target, flags));
4028
+ await withClient(conn, (client, serverId) => scopedPush(client, root, config, scope, target, flags, { conn, serverId, envFile }), { envFile, quiet });
3583
4029
  }
3584
4030
  );
3585
4031
  addBackupDirFlags(addConnectionFlags(
3586
- program.command("backup").description(`Save the server configuration as <server>-<UTC time>.xml in ./${DEFAULT_BACKUP_DIR} (holds credentials in plain text)`).option("--out <file>", "write to this file instead (no rotation)")
4032
+ 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)")
3587
4033
  )).action(async (flags) => {
3588
- const cfg = resolveClientConfig(flags);
3589
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3590
- const file = await withClient(flags, async (client) => {
4034
+ const conn = await selectConnection(void 0, flags);
4035
+ const target = targetOf2(conn);
4036
+ const file = await withClient(conn, async (client) => {
3591
4037
  const text = await client.getServerConfigurationXml();
3592
- if (!flags.out) return saveServerBackup(client, text, flags);
3593
- const out = path7.resolve(flags.out);
4038
+ if (!flags.out) return saveServerBackup(client, text, conn, flags);
4039
+ const out = path9.resolve(flags.out);
3594
4040
  parseBackup(text, "the server configuration");
3595
- if (existsSync6(out)) fail(`${out} already exists; choose another name`);
3596
- await mkdir5(path7.dirname(out), { recursive: true });
4041
+ if (existsSync8(out)) fail(`${out} already exists; choose another name`);
4042
+ await mkdir6(path9.dirname(out), { recursive: true });
3597
4043
  await writePrivate(out, text);
3598
4044
  if (gitWouldCommit(out)) {
3599
4045
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -3604,29 +4050,88 @@ addBackupDirFlags(addConnectionFlags(
3604
4050
  process.stdout.write(`backed up ${target} to ${file}
3605
4051
  `);
3606
4052
  });
4053
+ async function chooseBackup(dir, file, serverId, target) {
4054
+ if (file) {
4055
+ const chosen = path9.resolve(file);
4056
+ if (!existsSync8(chosen)) fail(`${chosen} does not exist`);
4057
+ return chosen;
4058
+ }
4059
+ const mine = await backupsOf(dir, serverId);
4060
+ if (mine.length === 0) {
4061
+ const others = (await originsIn(dir)).map((o) => o.host);
4062
+ const legacy = path9.resolve(LEGACY_BACKUP_DIR);
4063
+ const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
4064
+ fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}` + (inLegacy ? `; ${legacy} has backups of this server (the default before 0.3.0-rc.3): pass --backup-dir ${shellArgument(legacy)}` : ""));
4065
+ }
4066
+ return mine[mine.length - 1].file;
4067
+ }
4068
+ async function restoreWithBrokenExport(client, serverId, file, flags, target) {
4069
+ try {
4070
+ await client.getServerConfigurationXml();
4071
+ fail("the server can export its configuration; run restore without --export-broken, which shows a preview and saves an undo backup first");
4072
+ } catch (err) {
4073
+ if (err instanceof CliError) throw err;
4074
+ if (err.status !== 500) {
4075
+ 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`);
4076
+ }
4077
+ }
4078
+ const dir = backupDirOf(flags);
4079
+ const chosen = await chooseBackup(dir, file, serverId, target);
4080
+ const text = await readFile6(chosen, "utf8");
4081
+ const backup = parseBackup(text, chosen);
4082
+ const unsafe = await xmlSafetyProblem(backup);
4083
+ if (unsafe) fail(`${chosen} holds ${unsafe}`);
4084
+ const origin = await originOf(dir, chosen);
4085
+ if (!origin && !flags.force) {
4086
+ fail(`${chosen} is not in ${path9.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
4087
+ }
4088
+ if (origin && origin.serverId !== serverId && !flags.force) {
4089
+ fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
4090
+ }
4091
+ process.stdout.write(
4092
+ `Restore ${chosen}
4093
+ to ${target} (installation ${serverId}), replacing its ENTIRE configuration${flags.deploy ? ", then redeploy all channels" : ""}.
4094
+ The server cannot export its configuration, so there is no preview, no undo backup and no version check.
4095
+ `
4096
+ );
4097
+ if (!flags.yes && await ask(`Type the installation ID (${serverId}) to continue: `) !== serverId) {
4098
+ process.stdout.write("aborted.\n");
4099
+ return;
4100
+ }
4101
+ await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
4102
+ let afterText;
4103
+ try {
4104
+ afterText = await client.getServerConfigurationXml();
4105
+ } catch (err) {
4106
+ fail(`sent ${chosen} to ${target}, but the server still cannot export its configuration: ${err instanceof Error ? err.message : String(err)}; inspect it in the Administrator`);
4107
+ }
4108
+ const differ = planPush(backup, parseBackup(afterText, "the server configuration"), {}, void 0, { wholeReplace: true }).changes;
4109
+ if (differ.length > 0) {
4110
+ fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(", ")}; inspect the server`);
4111
+ }
4112
+ process.stdout.write(`restored ${chosen} to ${target}; the server exports its configuration again
4113
+ `);
4114
+ }
3607
4115
  addBackupDirFlags(addConnectionFlags(
3608
- 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("-y, --yes", "skip the confirmation prompt", false)
4116
+ 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)
3609
4117
  )).action(async (file, flags) => {
3610
- const cfg = resolveClientConfig(flags);
3611
- const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3612
4118
  if (!flags.yes && !process.stdin.isTTY) fail("no terminal to confirm on; pass --yes");
4119
+ const conn = await selectConnection(void 0, flags, { write: true });
4120
+ const target = targetOf2(conn);
3613
4121
  const dir = backupDirOf(flags);
3614
- await withClient(flags, async (client) => {
3615
- const currentText = await client.getServerConfigurationXml();
3616
- const current = parseBackup(currentText, "the server configuration");
3617
- const serverId = await client.getServerId();
3618
- let chosen;
3619
- if (file) {
3620
- chosen = path7.resolve(file);
3621
- if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3622
- } else {
3623
- const mine = await backupsOf(dir, serverId);
3624
- if (mine.length === 0) {
3625
- const others = (await originsIn(dir)).map((o) => o.host);
3626
- fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}`);
3627
- }
3628
- chosen = mine[mine.length - 1].file;
4122
+ await withClient(conn, async (client, serverId) => {
4123
+ if (flags.exportBroken) {
4124
+ await restoreWithBrokenExport(client, serverId, file, flags, target);
4125
+ return;
4126
+ }
4127
+ let currentText;
4128
+ try {
4129
+ currentText = await client.getServerConfigurationXml();
4130
+ } catch (err) {
4131
+ 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`);
3629
4132
  }
4133
+ const current = parseBackup(currentText, "the server configuration");
4134
+ const chosen = await chooseBackup(dir, file, serverId, target);
3630
4135
  const text = await readFile6(chosen, "utf8");
3631
4136
  const backup = parseBackup(text, chosen);
3632
4137
  const unsafe = await xmlSafetyProblem(backup);
@@ -3641,7 +4146,7 @@ addBackupDirFlags(addConnectionFlags(
3641
4146
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
3642
4147
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
3643
4148
  }
3644
- process.stderr.write(`warning: ${chosen} is not in ${path7.join(dir, MANIFEST)}, so which server it came from cannot be checked
4149
+ process.stderr.write(`warning: ${chosen} is not in ${path9.join(dir, MANIFEST)}, so which server it came from cannot be checked
3645
4150
  `);
3646
4151
  }
3647
4152
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -3675,10 +4180,10 @@ to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeplo
3675
4180
  if (!sameServerConfig(parseBackup(freshText, "the server configuration"), current)) {
3676
4181
  fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
3677
4182
  }
3678
- const undo = await saveServerBackup(client, freshText, flags, chosen);
3679
- process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, flags)})
4183
+ const undo = await saveServerBackup(client, freshText, conn, flags, chosen);
4184
+ process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, conn, flags)})
3680
4185
  `);
3681
- printUndoLimits(flags);
4186
+ printUndoLimits(conn, flags);
3682
4187
  const afterBackup = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
3683
4188
  if (!sameServerConfig(parseBackup(freshText, "the server configuration"), afterBackup)) {
3684
4189
  fail("the server changed during the undo backup; nothing was restored. Run it again to review the new state");
@@ -3700,11 +4205,19 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3700
4205
  })
3701
4206
  ))).action(async (dir, flags) => {
3702
4207
  errorExitCode = 2;
3703
- const root = path7.resolve(dir);
4208
+ const root = path9.resolve(dir);
3704
4209
  assertTree(root);
3705
- const fetched = await withClient(flags, (client) => client.getServerConfiguration());
4210
+ const conn = await selectConnection(root, flags);
4211
+ const envFile = await envFileFor(root, flags, conn);
4212
+ const treeServerId = (await readMeta(root))?.serverId;
4213
+ const { fetched, serverId } = await withClient(conn, async (client, serverId2) => {
4214
+ if (treeServerId && treeServerId !== serverId2) {
4215
+ fail(`this tree belongs to installation ${treeServerId}, but ${urlOf(conn)} is installation ${serverId2}; choose the server this tree was pulled from`, "installation-mismatch");
4216
+ }
4217
+ return { fetched: await client.getServerConfiguration(), serverId: serverId2 };
4218
+ }, { envFile, quiet: flags.json });
3706
4219
  const tree = await engine.implode({ root });
3707
- const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));
4220
+ const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFile));
3708
4221
  const messages = [
3709
4222
  ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
3710
4223
  ...notes,
@@ -3713,7 +4226,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3713
4226
  const allow = await readAllow(root);
3714
4227
  const staleRevisions = newerOnServer(tree, templatedRemote);
3715
4228
  if (staleRevisions.length > 0) {
3716
- messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);
4229
+ 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`);
3717
4230
  }
3718
4231
  const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
3719
4232
  const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
@@ -3723,17 +4236,17 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3723
4236
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
3724
4237
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
3725
4238
  `);
3726
- const tmp = await mkdtemp(path7.join(tmpdir(), "channelvault-diff-"));
4239
+ const tmp = await mkdtemp(path9.join(tmpdir(), "channelvault-diff-"));
3727
4240
  try {
3728
- await engine.explode(treeView.config, { root: path7.join(tmp, "tree") });
3729
- await engine.explode(serverView.config, { root: path7.join(tmp, "server") });
3730
- await mkdir5(path7.join(tmp, ".empty"));
4241
+ await engine.explode(treeView.config, { root: path9.join(tmp, "tree") });
4242
+ await engine.explode(serverView.config, { root: path9.join(tmp, "server") });
4243
+ await mkdir6(path9.join(tmp, ".empty"));
3731
4244
  const chunks = [];
3732
4245
  for (const d of MANAGED_DIRS) {
3733
- const local = existsSync6(path7.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3734
- const server = existsSync6(path7.join(tmp, "server", d)) ? `server/${d}` : ".empty";
4246
+ const local = existsSync8(path9.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
4247
+ const server = existsSync8(path9.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3735
4248
  if (local === ".empty" && server === ".empty") continue;
3736
- const result = spawnSync(
4249
+ const result = spawnSync2(
3737
4250
  "git",
3738
4251
  ["-c", "core.autocrlf=false", "diff", "--no-index", "--no-color", "--ignore-cr-at-eol", local, server],
3739
4252
  { encoding: "utf8", cwd: tmp }
@@ -3753,8 +4266,8 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3753
4266
  const clean = out === "" && secretDrift.length === 0;
3754
4267
  if (!clean) process.exitCode = 1;
3755
4268
  if (flags.json) {
3756
- const files = await changedFiles(path7.join(tmp, "tree"), path7.join(tmp, "server"));
3757
- writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
4269
+ const files = await changedFiles(path9.join(tmp, "tree"), path9.join(tmp, "server"));
4270
+ writeJson2({ clean, serverId, connection: connectionJson(conn, serverId, envFile), files, secretDrift, staleRevisions, notes: messages, patch: out });
3758
4271
  } else if (clean) {
3759
4272
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
3760
4273
  } else {
@@ -3774,27 +4287,29 @@ async function changedFiles(treeDir, serverDir) {
3774
4287
  const files = [];
3775
4288
  for (const p of local) {
3776
4289
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
3777
- else if (await readFile6(path7.join(treeDir, p), "utf8") !== await readFile6(path7.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
4290
+ else if (await readFile6(path9.join(treeDir, p), "utf8") !== await readFile6(path9.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3778
4291
  }
3779
4292
  const localSet = new Set(local);
3780
4293
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
3781
4294
  return files.sort((a, b) => a.path.localeCompare(b.path));
3782
4295
  }
3783
4296
  addJsonFlag(addEnvFlag(
3784
- program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
4297
+ program.command("status").description("Summarize a working tree, and say which connection profile live commands would use").argument("<dir>", "working-tree directory")
3785
4298
  )).action(async (dir, flags) => {
3786
- const root = path7.resolve(dir);
4299
+ const root = path9.resolve(dir);
3787
4300
  assertTree(root);
3788
4301
  const config = await engine.implode({ root });
3789
4302
  const s = summarize(config);
3790
- const metaPath = path7.join(root, "channelvault.json");
3791
- const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
4303
+ const meta = await readMeta(root);
4304
+ const connection = await offlineConnection(meta?.serverId);
3792
4305
  if (flags.json) {
3793
4306
  writeJson2({
3794
4307
  root,
3795
4308
  source: meta?.source ?? null,
3796
4309
  pulledAt: meta?.pulledAt ?? null,
3797
4310
  engineVersion: meta?.engineVersion ?? null,
4311
+ serverId: meta?.serverId ?? null,
4312
+ connection,
3798
4313
  counts: s,
3799
4314
  xmlForbiddenChars: forbiddenXmlChars(config)
3800
4315
  });
@@ -3808,8 +4323,12 @@ addJsonFlag(addEnvFlag(
3808
4323
  process.stdout.write(`pulled: ${meta.pulledAt}
3809
4324
  `);
3810
4325
  process.stdout.write(`engine: ${meta.engineVersion ?? "unknown"}
4326
+ `);
4327
+ if (meta.serverId) process.stdout.write(`server: installation ${meta.serverId}
3811
4328
  `);
3812
4329
  }
4330
+ 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)"}`}
4331
+ `);
3813
4332
  process.stdout.write(
3814
4333
  `channels: ${s.channels}
3815
4334
  channel groups: ${s.channelGroups}
@@ -3818,36 +4337,252 @@ code templates: ${s.codeTemplates}
3818
4337
  `
3819
4338
  );
3820
4339
  });
3821
- var unlock;
4340
+ async function offlineConnection(treeServerId) {
4341
+ try {
4342
+ const profiles = await loadProfiles();
4343
+ const credentials = await readCredentials();
4344
+ const conn = resolveConnection({
4345
+ flags: {},
4346
+ env: process.env,
4347
+ profiles,
4348
+ // Resolve as if every password were set, then report the real state.
4349
+ credentials: Object.fromEntries(Object.keys(profiles).map((n) => [n, ""])),
4350
+ ...treeServerId ? { treeServerId } : {}
4351
+ });
4352
+ const passwordConfigured = conn.profile ? Object.prototype.hasOwnProperty.call(credentials, conn.profile) : true;
4353
+ return { profile: conn.profile ?? null, url: urlOf(conn), user: conn.user, source: conn.source, passwordConfigured };
4354
+ } catch (err) {
4355
+ if (!(err instanceof ReasonError)) throw err;
4356
+ return { problem: `${err.reason ? `[${err.reason}] ` : ""}${err.message}` };
4357
+ }
4358
+ }
4359
+ function needTerminal(what) {
4360
+ if (!process.stdin.isTTY) fail(`${what} asks at a terminal; run it yourself in a terminal (agents cannot)`, "no-terminal");
4361
+ }
4362
+ async function askPassword(prompt) {
4363
+ const password = await ask(prompt, { secret: true });
4364
+ if (password.length < 8) fail("a profile password needs at least 8 characters; nothing was saved", "weak-password");
4365
+ return password;
4366
+ }
4367
+ function connectionOfProfile(name, profile, password) {
4368
+ return {
4369
+ host: profile.host,
4370
+ port: profile.port,
4371
+ user: profile.user,
4372
+ password,
4373
+ https: profile.https !== false,
4374
+ insecure: profile.insecure === true,
4375
+ ...profile.tlsFingerprint ? { tlsFingerprint: profile.tlsFingerprint } : {},
4376
+ source: "profile-flag",
4377
+ passwordSource: "credentials",
4378
+ profile: name,
4379
+ ...profile.serverId ? { serverId: profile.serverId } : {}
4380
+ };
4381
+ }
4382
+ async function loginCheck(conn) {
4383
+ rememberSecret(conn.password, { stdout: true });
4384
+ activeConnection = conn;
4385
+ return withClient(conn, async (_client, serverId) => serverId, { quiet: true });
4386
+ }
4387
+ function existingProfile(profiles, name) {
4388
+ const profile = profiles[name];
4389
+ if (!profile) fail(`no profile named ${name} (${Object.keys(profiles).join(", ") || "none saved"})`, "profile-unknown");
4390
+ return profile;
4391
+ }
4392
+ var profileCommand = program.command("profile").description(`Manage connection profiles (${path9.join("~", ".channelvault", "profiles.json")}; passwords in its credentials file)`);
4393
+ addJsonFlag(profileCommand.command("list").description("List the saved profiles (never their passwords)")).action(async (flags) => {
4394
+ const profiles = await loadProfiles();
4395
+ const credentials = await readCredentials();
4396
+ const rows = Object.entries(profiles).map(([name, p]) => ({
4397
+ name,
4398
+ url: urlOf({ https: p.https !== false, host: p.host, port: p.port }),
4399
+ user: p.user,
4400
+ serverId: p.serverId ?? null,
4401
+ tlsFingerprint: p.tlsFingerprint ?? null,
4402
+ insecure: p.insecure === true,
4403
+ dotenv: p.dotenv ?? null,
4404
+ passwordConfigured: Object.prototype.hasOwnProperty.call(credentials, name)
4405
+ }));
4406
+ if (flags.json) {
4407
+ writeJson2({ profilesFile: profilesFile(), profiles: rows });
4408
+ return;
4409
+ }
4410
+ if (rows.length === 0) {
4411
+ process.stdout.write(`no profiles in ${profilesFile()}; add one at a terminal with: channelvault profile add <name> --host <host> --port <port> --user <user>
4412
+ `);
4413
+ return;
4414
+ }
4415
+ for (const r of rows) {
4416
+ 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";
4417
+ 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)"}
4418
+ `);
4419
+ }
4420
+ });
4421
+ 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) => {
4422
+ needTerminal("profile add");
4423
+ if (!PROFILE_NAME.test(name)) fail(`profile names are letters, digits, '.', '_' and '-', starting with a letter or digit: ${name}`, "profile-invalid");
4424
+ const profiles = await loadProfiles();
4425
+ if (profiles[name]) fail(`profile ${name} already exists; change its password with \`channelvault profile set-password ${name}\`, or edit ${profilesFile()}`, "profile-exists");
4426
+ const port = Number(flags.port);
4427
+ const profile = { host: flags.host, port, user: flags.user };
4428
+ if (flags.https === false) profile.https = false;
4429
+ if (flags.insecure) profile.insecure = true;
4430
+ if (flags.dotenv) profile.dotenv = path9.resolve(flags.dotenv);
4431
+ if (flags.tlsFingerprint !== void 0) {
4432
+ const pin = normalizeFingerprint(flags.tlsFingerprint);
4433
+ if (!pin) fail("--tls-fingerprint must be a SHA-256 certificate fingerprint: 64 hex digits, colons allowed", "bad-fingerprint");
4434
+ profile.tlsFingerprint = pin;
4435
+ }
4436
+ const problems = profileProblems({ ...profiles, [name]: profile });
4437
+ if (problems.length > 0) fail(problems.join("\n"), "profile-invalid");
4438
+ const conn = connectionOfProfile(name, profile, "");
4439
+ process.stdout.write(`Add profile ${name}: ${urlOf(conn)} as ${profile.user}
4440
+ `);
4441
+ if (conn.https && !conn.insecure) {
4442
+ const presented = await presentedFingerprint(profile.host, port);
4443
+ if (profile.tlsFingerprint && presented !== profile.tlsFingerprint) {
4444
+ fail(`the server presents certificate SHA-256 ${formatFingerprint(presented)}, not the --tls-fingerprint given; nothing was saved`, "tls-pin-mismatch");
4445
+ }
4446
+ profile.tlsFingerprint = presented;
4447
+ process.stdout.write(`certificate SHA-256 ${formatFingerprint(presented)}
4448
+ channelvault will accept only this certificate from this server. Compare it with the one the server administrator gave you.
4449
+ `);
4450
+ }
4451
+ if (!await confirm("Is this the right server?")) {
4452
+ process.stdout.write("aborted.\n");
4453
+ return;
4454
+ }
4455
+ const password = await askPassword(`Password for ${profile.user}: `);
4456
+ profile.serverId = await loginCheck(connectionOfProfile(name, profile, password));
4457
+ const latest = await loadProfiles();
4458
+ if (latest[name]) fail(`profile ${name} was added meanwhile; nothing was saved`, "profile-exists");
4459
+ await saveProfiles({ ...latest, [name]: profile });
4460
+ await setCredential(name, password);
4461
+ process.stdout.write(`added profile ${name} (installation ${profile.serverId}); password stored in ${credentialsFile()}
4462
+ `);
4463
+ });
4464
+ 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) => {
4465
+ needTerminal("profile set-password");
4466
+ const profile = existingProfile(await loadProfiles(), name);
4467
+ process.stdout.write(`Profile ${name}: ${urlOf(connectionOfProfile(name, profile, ""))} as ${profile.user}
4468
+ `);
4469
+ const password = await askPassword(`New password for ${profile.user}: `);
4470
+ await loginCheck(connectionOfProfile(name, profile, password));
4471
+ await setCredential(name, password);
4472
+ process.stdout.write(`stored the password for profile ${name}
4473
+ `);
4474
+ });
4475
+ addJsonFlag(profileCommand.command("check").description("Log in with each profile (or the one named) and verify its certificate and installation").argument("[name]", "profile name")).action(async (name, flags) => {
4476
+ const profiles = await loadProfiles();
4477
+ const credentials = await readCredentials();
4478
+ if (name) existingProfile(profiles, name);
4479
+ const names = name ? [name] : Object.keys(profiles);
4480
+ if (names.length === 0) fail(`no profiles in ${profilesFile()}`, "no-connection");
4481
+ const results = [];
4482
+ for (const n of names) {
4483
+ const password = credentials[n];
4484
+ if (password === void 0) {
4485
+ results.push({ name: n, ok: false, serverId: null, problem: `[no-password] run \`channelvault profile set-password ${n}\` at a terminal` });
4486
+ continue;
4487
+ }
4488
+ try {
4489
+ results.push({ name: n, ok: true, serverId: await loginCheck(connectionOfProfile(n, profiles[n], password)), problem: null });
4490
+ } catch (err) {
4491
+ results.push({ name: n, ok: false, serverId: null, problem: scrub(describeError(err)) });
4492
+ }
4493
+ }
4494
+ if (results.some((r) => !r.ok)) process.exitCode = 1;
4495
+ if (flags.json) {
4496
+ writeJson2({ profiles: results });
4497
+ return;
4498
+ }
4499
+ for (const r of results) process.stdout.write(r.ok ? `${r.name}: ok, installation ${r.serverId}
4500
+ ` : `${r.name}: FAILED ${r.problem}
4501
+ `);
4502
+ });
4503
+ 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) => {
4504
+ needTerminal("profile repin");
4505
+ const profiles = await loadProfiles();
4506
+ const profile = existingProfile(profiles, name);
4507
+ if (profile.https === false || profile.insecure) fail(`profile ${name} does not check certificates, so there is nothing to pin`, "profile-invalid");
4508
+ const password = (await readCredentials())[name];
4509
+ if (password === void 0) fail(`profile ${name} has no password yet; run \`channelvault profile set-password ${name}\` first`, "no-password");
4510
+ const presented = await presentedFingerprint(profile.host, profile.port);
4511
+ if (presented === profile.tlsFingerprint) {
4512
+ process.stdout.write(`profile ${name} already pins the certificate ${profile.host}:${profile.port} presents
4513
+ `);
4514
+ return;
4515
+ }
4516
+ process.stdout.write(`Profile ${name}: ${profile.host}:${profile.port}
4517
+ pinned: ${profile.tlsFingerprint ? formatFingerprint(profile.tlsFingerprint) : "(none)"}
4518
+ presented: ${formatFingerprint(presented)}
4519
+ Accept the new certificate only if the administrator replaced it and gave you this fingerprint; otherwise someone may be impersonating the server.
4520
+ `);
4521
+ if (!await confirm("Pin the presented certificate?")) {
4522
+ process.stdout.write("aborted.\n");
4523
+ return;
4524
+ }
4525
+ const repinned = { ...profile, tlsFingerprint: presented };
4526
+ await loginCheck(connectionOfProfile(name, repinned, password));
4527
+ const latest = await loadProfiles();
4528
+ await saveProfiles({ ...latest, [name]: { ...existingProfile(latest, name), tlsFingerprint: presented } });
4529
+ process.stdout.write(`profile ${name} now pins ${formatFingerprint(presented)}
4530
+ `);
4531
+ });
4532
+ var unlocks = [];
4533
+ var locked = [];
4534
+ async function lockAlso(file) {
4535
+ const key = await canonical(file);
4536
+ if (locked.some((l) => samePath(l, key))) return;
4537
+ unlocks.push(await lockTree(path9.resolve(file)));
4538
+ locked.push(key);
4539
+ }
3822
4540
  program.hook("preAction", async (_program, command) => {
3823
4541
  const name = command.name();
3824
- if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
4542
+ if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name) || command.parent !== program) return;
3825
4543
  if (name === "diff") errorExitCode = 2;
3826
- const root = path7.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3827
- unlock = await lockTree(root);
3828
- await recoverTree(root, envFilePath(root, command.opts()));
4544
+ const root = path9.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
4545
+ unlocks.push(await lockTree(root));
4546
+ const pending = await pendingEnvFile(root);
4547
+ if (pending === null) return;
4548
+ if (!isWithin(pending, await resolvedPath(root))) await lockAlso(pending);
4549
+ await recoverTree(root, await recoveryCandidates(root, command.opts()));
3829
4550
  });
3830
- program.parseAsync().catch((err) => {
4551
+ function describeError(err) {
4552
+ const code = err?.code;
4553
+ const reason = err instanceof ReasonError ? err.reason : code === "TLS_PIN_MISMATCH" ? "tls-pin-mismatch" : void 0;
4554
+ return `${reason ? `[${reason}] ` : ""}${err instanceof Error ? err.message : String(err)}`;
4555
+ }
4556
+ async function certificateHint(code) {
4557
+ const conn = activeConnection;
4558
+ if (code === "TLS_PIN_MISMATCH") {
4559
+ 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)";
4560
+ }
4561
+ if (!UNTRUSTED_CERT_CODES.has(code)) return void 0;
4562
+ const presented = conn ? await presentedFingerprint(conn.host, conn.port, 5e3).catch(() => void 0) : void 0;
4563
+ const pin = presented ? ` It presents SHA-256 ${formatFingerprint(presented)}.` : "";
4564
+ const loopback = conn ? isLoopback(conn.host) : false;
4565
+ 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" : ""}.`;
4566
+ }
4567
+ program.parseAsync().catch(async (err) => {
3831
4568
  if (err instanceof CommanderError) return;
3832
- process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}
4569
+ process.stderr.write(`error: ${scrub(describeError(err))}
3833
4570
  `);
3834
4571
  const code = err?.code;
3835
- if (typeof code === "string" && UNTRUSTED_CERT_CODES.has(code)) {
3836
- process.stderr.write(
3837
- "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"
3838
- );
3839
- }
3840
- if (!(err instanceof CliError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {
4572
+ const hint = typeof code === "string" ? await certificateHint(code) : void 0;
4573
+ if (hint) process.stderr.write(`hint: ${hint}
4574
+ `);
4575
+ if (!(err instanceof ReasonError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {
3841
4576
  process.stderr.write(`${scrub(err.stack ?? "")}
3842
4577
  `);
3843
4578
  }
3844
4579
  process.exitCode = errorExitCode;
3845
4580
  }).finally(async () => {
3846
- if (unlock) {
4581
+ for (const unlock of unlocks.reverse()) {
3847
4582
  try {
3848
4583
  await unlock();
3849
4584
  } catch (err) {
3850
- process.stderr.write(`error: could not release working-tree lock: ${scrub(err instanceof Error ? err.message : String(err))}
4585
+ process.stderr.write(`error: could not release a lock: ${scrub(err instanceof Error ? err.message : String(err))}
3851
4586
  `);
3852
4587
  process.exitCode = errorExitCode;
3853
4588
  }