@ubercode/channelvault 0.3.0-rc.3 → 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/CHANGELOG.md +32 -0
- package/README.md +61 -10
- package/dist/cli.js +1406 -786
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +24 -2
- package/dist/index.js.map +1 -1
- package/docs/roadmap.md +2 -1
- package/package.json +1 -1
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
|
|
6
|
-
import { existsSync as
|
|
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
|
|
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 {
|
|
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,
|
|
1006
|
+
const walk = (node, key, path10, labels, section, cmKey) => {
|
|
1004
1007
|
if (typeof node === "string") {
|
|
1005
|
-
return visit(node, { location:
|
|
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, [...
|
|
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, [...
|
|
1019
|
+
out[k] = walk(v, k, [...path10, k], inner, section || k, mapKey);
|
|
1017
1020
|
}
|
|
1018
1021
|
return out;
|
|
1019
1022
|
}
|
|
@@ -1411,6 +1414,38 @@ 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
|
+
}
|
|
1414
1449
|
function redirectTarget(url, response) {
|
|
1415
1450
|
const location = response.headers.get("location");
|
|
1416
1451
|
if (!location) return "";
|
|
@@ -1442,7 +1477,7 @@ var MirthClientImpl = class {
|
|
|
1442
1477
|
const protocol = config.https !== false ? "https" : "http";
|
|
1443
1478
|
this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;
|
|
1444
1479
|
this.cookieJar = new CookieJar();
|
|
1445
|
-
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 } } : {});
|
|
1446
1481
|
}
|
|
1447
1482
|
isAuthenticated() {
|
|
1448
1483
|
return this.authenticated;
|
|
@@ -1622,15 +1657,15 @@ var MirthClientImpl = class {
|
|
|
1622
1657
|
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1623
1658
|
}
|
|
1624
1659
|
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1625
|
-
async sendJson(method,
|
|
1626
|
-
const response = await this.request(method,
|
|
1660
|
+
async sendJson(method, path10, body, query) {
|
|
1661
|
+
const response = await this.request(method, path10, {
|
|
1627
1662
|
query,
|
|
1628
1663
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1629
1664
|
body: JSON.stringify(body)
|
|
1630
1665
|
});
|
|
1631
1666
|
const text = await response.text();
|
|
1632
1667
|
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1633
|
-
throw new Error(`${method} ${
|
|
1668
|
+
throw new Error(`${method} ${path10}: the server refused the update`);
|
|
1634
1669
|
}
|
|
1635
1670
|
}
|
|
1636
1671
|
// --- internal transport ---------------------------------------------------
|
|
@@ -1639,11 +1674,11 @@ var MirthClientImpl = class {
|
|
|
1639
1674
|
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1640
1675
|
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1641
1676
|
*/
|
|
1642
|
-
async request(method,
|
|
1677
|
+
async request(method, path10, options = {}, isRetry = false) {
|
|
1643
1678
|
if (!this.authenticated) {
|
|
1644
1679
|
await this.login();
|
|
1645
1680
|
}
|
|
1646
|
-
const url = this.buildUrl(
|
|
1681
|
+
const url = this.buildUrl(path10, options.query);
|
|
1647
1682
|
const headers = {
|
|
1648
1683
|
"X-Requested-With": "XMLHttpRequest",
|
|
1649
1684
|
...options.headers
|
|
@@ -1657,7 +1692,7 @@ var MirthClientImpl = class {
|
|
|
1657
1692
|
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1658
1693
|
this.authenticated = false;
|
|
1659
1694
|
await this.login();
|
|
1660
|
-
return this.request(method,
|
|
1695
|
+
return this.request(method, path10, options, true);
|
|
1661
1696
|
}
|
|
1662
1697
|
if (!response.ok) {
|
|
1663
1698
|
throw await this.toApiError(response);
|
|
@@ -1688,8 +1723,8 @@ var MirthClientImpl = class {
|
|
|
1688
1723
|
return response;
|
|
1689
1724
|
}
|
|
1690
1725
|
/** Build an absolute URL with an optional query string. */
|
|
1691
|
-
buildUrl(
|
|
1692
|
-
const url = `${this.baseUrl}${
|
|
1726
|
+
buildUrl(path10, query) {
|
|
1727
|
+
const url = `${this.baseUrl}${path10}`;
|
|
1693
1728
|
if (!query || Object.keys(query).length === 0) {
|
|
1694
1729
|
return url;
|
|
1695
1730
|
}
|
|
@@ -1756,178 +1791,744 @@ function createMirthClient(config) {
|
|
|
1756
1791
|
return new MirthClientImpl(config);
|
|
1757
1792
|
}
|
|
1758
1793
|
|
|
1759
|
-
// src/
|
|
1760
|
-
import {
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
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");
|
|
1765
1808
|
}
|
|
1766
|
-
|
|
1767
|
-
|
|
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, "");
|
|
1768
1814
|
}
|
|
1769
|
-
function
|
|
1770
|
-
return
|
|
1815
|
+
function backupName(config, fallback) {
|
|
1816
|
+
return configuredName(config) || serverSlug(fallback) || "mirth";
|
|
1771
1817
|
}
|
|
1772
|
-
function
|
|
1773
|
-
|
|
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");
|
|
1774
1825
|
}
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
var revisionOf = (o) => Number(o["revision"] ?? 0);
|
|
1778
|
-
function normalizeEol(s) {
|
|
1779
|
-
return s.replace(/\r\n?/g, "\n");
|
|
1826
|
+
function stamp(date) {
|
|
1827
|
+
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
1780
1828
|
}
|
|
1781
|
-
function
|
|
1782
|
-
if (
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
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);
|
|
1786
1837
|
}
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
if (
|
|
1791
|
-
|
|
1792
|
-
const
|
|
1793
|
-
return
|
|
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`);
|
|
1794
1847
|
}
|
|
1795
|
-
return false;
|
|
1796
1848
|
}
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
const types = isObj(delegate) ? delegate["contextType"] : void 0;
|
|
1802
|
-
if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
|
|
1803
|
-
const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
|
|
1804
|
-
return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
|
|
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
|
+
`);
|
|
1805
1853
|
}
|
|
1806
|
-
function
|
|
1807
|
-
const
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
if (
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
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);
|
|
1818
1881
|
}
|
|
1819
|
-
|
|
1882
|
+
await writeManifest(dir, manifest);
|
|
1883
|
+
return file;
|
|
1820
1884
|
}
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
delete o["revision"];
|
|
1826
|
-
delete o["lastModified"];
|
|
1827
|
-
const exportData = o["exportData"];
|
|
1828
|
-
const md = isObj(exportData) ? exportData["metadata"] : void 0;
|
|
1829
|
-
if (isObj(md)) {
|
|
1830
|
-
delete md["lastModified"];
|
|
1831
|
-
delete md["userId"];
|
|
1832
|
-
}
|
|
1833
|
-
if (isObj(exportData)) {
|
|
1834
|
-
for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
|
|
1835
|
-
}
|
|
1836
|
-
if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
|
|
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;
|
|
1837
1889
|
};
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
}
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
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;
|
|
1846
1905
|
}
|
|
1847
|
-
return out;
|
|
1848
1906
|
}
|
|
1849
|
-
function
|
|
1850
|
-
const
|
|
1851
|
-
|
|
1852
|
-
const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
|
|
1853
|
-
for (const r of remote) {
|
|
1854
|
-
const rev = mine.get(idOf(r));
|
|
1855
|
-
if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
|
|
1856
|
-
}
|
|
1857
|
-
};
|
|
1858
|
-
compare("channel", channelsOf(tree), channelsOf(server));
|
|
1859
|
-
compare("library", librariesOf(tree), librariesOf(server));
|
|
1860
|
-
compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
|
|
1861
|
-
compare("channel group", groupsOf(tree), groupsOf(server));
|
|
1862
|
-
return out;
|
|
1907
|
+
function numericVersion(v) {
|
|
1908
|
+
const m = /^\d+(?:\.\d+)*/.exec(v.trim());
|
|
1909
|
+
return m ? m[0].split(".").map(Number) : null;
|
|
1863
1910
|
}
|
|
1864
|
-
function
|
|
1865
|
-
const
|
|
1866
|
-
|
|
1867
|
-
|
|
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;
|
|
1868
1919
|
}
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
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;
|
|
1876
1927
|
}
|
|
1877
|
-
function
|
|
1878
|
-
|
|
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);
|
|
1879
1932
|
}
|
|
1880
|
-
function
|
|
1881
|
-
const
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
libraries: revs(libs),
|
|
1886
|
-
codeTemplates: revs(libs.flatMap(templatesOf2)),
|
|
1887
|
-
globalScripts: hashGlobalScripts(c)
|
|
1888
|
-
};
|
|
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));
|
|
1889
1938
|
}
|
|
1890
|
-
function
|
|
1891
|
-
const
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
const known = {
|
|
1896
|
-
channels: intersect("channels"),
|
|
1897
|
-
libraries: intersect("libraries"),
|
|
1898
|
-
codeTemplates: intersect("codeTemplates"),
|
|
1899
|
-
globalScripts: theirs.globalScripts
|
|
1900
|
-
};
|
|
1901
|
-
const rebase = (items, revisions) => {
|
|
1902
|
-
for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
|
|
1903
|
-
};
|
|
1904
|
-
rebase(channelsOf(config), theirs.channels);
|
|
1905
|
-
rebase(librariesOf(config), theirs.libraries);
|
|
1906
|
-
rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
|
|
1907
|
-
return { config, known };
|
|
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));
|
|
1908
1944
|
}
|
|
1909
|
-
function
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
channels: map(r["channels"]),
|
|
1915
|
-
libraries: map(r["libraries"]),
|
|
1916
|
-
codeTemplates: map(r["codeTemplates"]),
|
|
1917
|
-
globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
|
|
1918
|
-
};
|
|
1945
|
+
async function present(file) {
|
|
1946
|
+
return lstat2(file).then(() => true, (err) => {
|
|
1947
|
+
if (err.code === "ENOENT") return false;
|
|
1948
|
+
throw err;
|
|
1949
|
+
});
|
|
1919
1950
|
}
|
|
1920
|
-
function
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
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
|
|
2528
|
+
};
|
|
2529
|
+
const key = { channel: "channels", library: "libraries", codeTemplate: "codeTemplates" };
|
|
2530
|
+
for (const c of applied) {
|
|
2531
|
+
if (c.kind === "globalScripts") {
|
|
1931
2532
|
next.globalScripts = now.globalScripts;
|
|
1932
2533
|
} else if (c.op === "delete") {
|
|
1933
2534
|
delete next[key[c.kind]][c.id];
|
|
@@ -2199,9 +2800,9 @@ function findChannel(c, id) {
|
|
|
2199
2800
|
}
|
|
2200
2801
|
|
|
2201
2802
|
// src/push/apply.ts
|
|
2202
|
-
import { readdir as
|
|
2203
|
-
import { existsSync as
|
|
2204
|
-
import * as
|
|
2803
|
+
import { readdir as readdir4, writeFile as writeFile4 } from "fs/promises";
|
|
2804
|
+
import { existsSync as existsSync6 } from "fs";
|
|
2805
|
+
import * as path6 from "path";
|
|
2205
2806
|
var ORDER = [
|
|
2206
2807
|
["codeTemplate", ["create", "update"]],
|
|
2207
2808
|
["library", ["create", "update", "delete"]],
|
|
@@ -2254,362 +2855,116 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
|
2254
2855
|
await withServerAssociations(client, channel, change, before, opts.force === true)
|
|
2255
2856
|
);
|
|
2256
2857
|
} else {
|
|
2257
|
-
const current = await client.getServerConfiguration();
|
|
2258
|
-
if (!opts.force && changedSince({ ...plan, changes: [change] }, remote, current).length) {
|
|
2259
|
-
throw new Error("global scripts changed on the server during the push; pull and try again");
|
|
2260
|
-
}
|
|
2261
|
-
await client.putGlobalScripts(local["globalScripts"]);
|
|
2262
|
-
}
|
|
2263
|
-
} catch (err) {
|
|
2264
|
-
return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds, sentLibraries };
|
|
2265
|
-
}
|
|
2266
|
-
applied.push(change);
|
|
2267
|
-
touchedIds.add(change.id);
|
|
2268
|
-
}
|
|
2269
|
-
}
|
|
2270
|
-
return { applied, touchedIds, sentLibraries };
|
|
2271
|
-
}
|
|
2272
|
-
function checkResource(change, before, current, force) {
|
|
2273
|
-
if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
|
|
2274
|
-
throw new Error(`${change.label} changed on the server during the push (revision ${String(current?.["revision"] ?? "absent")}, planned against ${String(before?.["revision"] ?? "absent")}); pull and try again`);
|
|
2275
|
-
}
|
|
2276
|
-
}
|
|
2277
|
-
async function checkTemplate(client, change, remote, force) {
|
|
2278
|
-
checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
|
|
2279
|
-
}
|
|
2280
|
-
async function withServerAssociations(client, channel, change, planned, force) {
|
|
2281
|
-
const server = await client.getChannel(String(channel["id"]));
|
|
2282
|
-
checkResource(change, planned, server, force);
|
|
2283
|
-
if (change.op !== "update") return channel;
|
|
2284
|
-
const serverExport = server?.["exportData"];
|
|
2285
|
-
if (!serverExport) return channel;
|
|
2286
|
-
const exportData = { ...channel["exportData"] ?? {} };
|
|
2287
|
-
for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
|
|
2288
|
-
return { ...channel, exportData };
|
|
2289
|
-
}
|
|
2290
|
-
async function deployChannels(client, ids, nameOf2) {
|
|
2291
|
-
const deployed = [];
|
|
2292
|
-
const skipped = [];
|
|
2293
|
-
const failures = [];
|
|
2294
|
-
for (const id of ids) {
|
|
2295
|
-
try {
|
|
2296
|
-
if (!(await client.getDeployedChannelIds()).has(id)) {
|
|
2297
|
-
skipped.push(nameOf2(id));
|
|
2298
|
-
continue;
|
|
2299
|
-
}
|
|
2300
|
-
await client.deployChannel(id);
|
|
2301
|
-
deployed.push(nameOf2(id));
|
|
2302
|
-
} catch (err) {
|
|
2303
|
-
failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
return { deployed, skipped, failures };
|
|
2307
|
-
}
|
|
2308
|
-
function copyVersionFields(target, source) {
|
|
2309
|
-
if (!source) return false;
|
|
2310
|
-
let changed = false;
|
|
2311
|
-
for (const key of ["revision", "lastModified"]) {
|
|
2312
|
-
if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
|
|
2313
|
-
target[key] = source[key];
|
|
2314
|
-
changed = true;
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
const tm = target["exportData"]?.["metadata"];
|
|
2318
|
-
const sm = source["exportData"]?.["metadata"];
|
|
2319
|
-
if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
|
|
2320
|
-
tm["lastModified"] = sm["lastModified"];
|
|
2321
|
-
changed = true;
|
|
2322
|
-
}
|
|
2323
|
-
return changed;
|
|
2324
|
-
}
|
|
2325
|
-
async function jsonFiles(dir, name) {
|
|
2326
|
-
if (!existsSync2(dir)) return [];
|
|
2327
|
-
const entries = await readdir2(dir, { withFileTypes: true });
|
|
2328
|
-
return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
|
|
2329
|
-
}
|
|
2330
|
-
async function refreshRevisions(root, server, ids) {
|
|
2331
|
-
for (const file of await jsonFiles(path2.join(root, "channels"), "channel.json")) {
|
|
2332
|
-
const json = await readJson(file);
|
|
2333
|
-
if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
|
|
2334
|
-
await writeFile2(file, JSON.stringify(json, null, 2));
|
|
2335
|
-
}
|
|
2336
|
-
}
|
|
2337
|
-
const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
|
|
2338
|
-
for (const file of await jsonFiles(path2.join(root, "codeTemplates"), "library.json")) {
|
|
2339
|
-
const json = await readJson(file);
|
|
2340
|
-
let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
|
|
2341
|
-
const container = json["codeTemplates"];
|
|
2342
|
-
for (const t of list(container?.["codeTemplate"])) {
|
|
2343
|
-
if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
|
|
2344
|
-
}
|
|
2345
|
-
if (changed) await writeFile2(file, JSON.stringify(json, null, 2));
|
|
2346
|
-
}
|
|
2347
|
-
}
|
|
2348
|
-
|
|
2349
|
-
// src/secrets/envfile.ts
|
|
2350
|
-
import { randomBytes } from "crypto";
|
|
2351
|
-
import { existsSync as existsSync3 } from "fs";
|
|
2352
|
-
import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as readdir3, realpath as realpath2, rename, rm, writeFile as writeFile3 } from "fs/promises";
|
|
2353
|
-
import * as path3 from "path";
|
|
2354
|
-
import { parse } from "dotenv";
|
|
2355
|
-
var BASE64_PREFIX = "cv-base64:";
|
|
2356
|
-
function parseEnv(text) {
|
|
2357
|
-
const out = parse(text);
|
|
2358
|
-
for (const [k, v] of Object.entries(out)) {
|
|
2359
|
-
if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
|
|
2360
|
-
}
|
|
2361
|
-
return out;
|
|
2362
|
-
}
|
|
2363
|
-
async function readEnvFile(file) {
|
|
2364
|
-
if (!existsSync3(file)) return {};
|
|
2365
|
-
return parseEnv(await readFile3(file, "utf8"));
|
|
2366
|
-
}
|
|
2367
|
-
function formatValue(value) {
|
|
2368
|
-
const candidates = [
|
|
2369
|
-
/^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
|
|
2370
|
-
value.includes("'") ? null : `'${value}'`,
|
|
2371
|
-
value.includes("`") ? null : `\`${value}\``,
|
|
2372
|
-
value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
|
|
2373
|
-
];
|
|
2374
|
-
for (const c of candidates) {
|
|
2375
|
-
if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
|
|
2376
|
-
}
|
|
2377
|
-
return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
|
|
2378
|
-
}
|
|
2379
|
-
async function updateEnvFile(file, updates) {
|
|
2380
|
-
const names = Object.keys(updates);
|
|
2381
|
-
if (names.length === 0) return;
|
|
2382
|
-
const existing = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2383
|
-
const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
|
|
2384
|
-
const written = /* @__PURE__ */ new Set();
|
|
2385
|
-
const out = [];
|
|
2386
|
-
let inQuote = null;
|
|
2387
|
-
let dropping = false;
|
|
2388
|
-
for (const line of lines) {
|
|
2389
|
-
if (inQuote !== null) {
|
|
2390
|
-
if (!dropping) out.push(line);
|
|
2391
|
-
if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
|
|
2392
|
-
continue;
|
|
2393
|
-
}
|
|
2394
|
-
const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
|
|
2395
|
-
const q = m?.[2][0];
|
|
2396
|
-
const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
|
|
2397
|
-
if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
|
|
2398
|
-
if (!written.has(m[1])) {
|
|
2399
|
-
out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
|
|
2400
|
-
written.add(m[1]);
|
|
2401
|
-
}
|
|
2402
|
-
if (opens) [inQuote, dropping] = [opens, true];
|
|
2403
|
-
continue;
|
|
2404
|
-
}
|
|
2405
|
-
out.push(line);
|
|
2406
|
-
if (opens) inQuote = opens;
|
|
2407
|
-
}
|
|
2408
|
-
for (const name of names) {
|
|
2409
|
-
if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
|
|
2410
|
-
}
|
|
2411
|
-
const text = `${out.join("\n")}
|
|
2412
|
-
`;
|
|
2413
|
-
const readBack = parseEnv(text);
|
|
2414
|
-
const wrong = names.filter((n) => readBack[n] !== updates[n]);
|
|
2415
|
-
if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
|
|
2416
|
-
const target = existsSync3(file) ? await realpath2(file) : file;
|
|
2417
|
-
const temp = `${target}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
|
|
2418
|
-
try {
|
|
2419
|
-
await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
|
|
2420
|
-
await rename(temp, target);
|
|
2421
|
-
} catch (err) {
|
|
2422
|
-
await rm(temp, { force: true });
|
|
2423
|
-
throw err;
|
|
2424
|
-
}
|
|
2425
|
-
}
|
|
2426
|
-
var ENV_BACKUPS_KEPT = 5;
|
|
2427
|
-
async function backupEnvFile(file, updates, dir) {
|
|
2428
|
-
if (!existsSync3(file)) return null;
|
|
2429
|
-
const current = parseEnv(await readFile3(file, "utf8"));
|
|
2430
|
-
if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
|
|
2431
|
-
await mkdir2(dir, { recursive: true });
|
|
2432
|
-
const prefix = `${path3.basename(file)}-`;
|
|
2433
|
-
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
|
|
2434
|
-
let target = path3.join(dir, `${prefix}${stamp2}`);
|
|
2435
|
-
for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
|
|
2436
|
-
await copyFile(file, target);
|
|
2437
|
-
await chmod(target, 384);
|
|
2438
|
-
const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
|
|
2439
|
-
for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
|
|
2440
|
-
await rm(path3.join(dir, old));
|
|
2441
|
-
}
|
|
2442
|
-
return target;
|
|
2443
|
-
}
|
|
2444
|
-
var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
|
|
2445
|
-
async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
|
|
2446
|
-
const file = path3.join(dir, ".gitignore");
|
|
2447
|
-
const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2448
|
-
const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
|
|
2449
|
-
const wanted = [...IGNORE_LINES];
|
|
2450
|
-
if (envFile) {
|
|
2451
|
-
const rel = path3.relative(treeRoot, envFile).split(path3.sep).join("/");
|
|
2452
|
-
const base = path3.basename(envFile);
|
|
2453
|
-
const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
|
|
2454
|
-
if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
|
|
2455
|
-
}
|
|
2456
|
-
const missing = wanted.filter((l) => !present2.has(l));
|
|
2457
|
-
if (missing.length === 0) return false;
|
|
2458
|
-
const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
|
|
2459
|
-
await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
|
|
2460
|
-
${missing.join("\n")}
|
|
2461
|
-
`);
|
|
2462
|
-
return true;
|
|
2463
|
-
}
|
|
2464
|
-
|
|
2465
|
-
// src/backup/index.ts
|
|
2466
|
-
import { randomBytes as randomBytes2 } from "crypto";
|
|
2467
|
-
import { existsSync as existsSync4, realpathSync } from "fs";
|
|
2468
|
-
import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
|
|
2469
|
-
import * as path5 from "path";
|
|
2470
|
-
|
|
2471
|
-
// src/profiles.ts
|
|
2472
|
-
import { homedir } from "os";
|
|
2473
|
-
import * as path4 from "path";
|
|
2474
|
-
function configDir() {
|
|
2475
|
-
const override = process.env.CHANNELVAULT_CONFIG_DIR;
|
|
2476
|
-
return override ? path4.resolve(override) : path4.join(homedir(), ".channelvault");
|
|
2477
|
-
}
|
|
2478
|
-
|
|
2479
|
-
// src/backup/index.ts
|
|
2480
|
-
function defaultBackupDir() {
|
|
2481
|
-
return path5.join(configDir(), "backups");
|
|
2482
|
-
}
|
|
2483
|
-
var LEGACY_BACKUP_DIR = ".backup";
|
|
2484
|
-
var DEFAULT_KEEP = 10;
|
|
2485
|
-
var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
|
|
2486
|
-
function serverSlug(name) {
|
|
2487
|
-
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
2488
|
-
}
|
|
2489
|
-
function backupName(config, fallback) {
|
|
2490
|
-
return configuredName(config) || serverSlug(fallback) || "mirth";
|
|
2491
|
-
}
|
|
2492
|
-
function configuredName(config) {
|
|
2493
|
-
const settings = config["serverSettings"];
|
|
2494
|
-
const field = (key) => {
|
|
2495
|
-
const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
|
|
2496
|
-
return typeof v === "string" ? serverSlug(v) : "";
|
|
2497
|
-
};
|
|
2498
|
-
return field("serverName") || field("environmentName");
|
|
2499
|
-
}
|
|
2500
|
-
function stamp(date) {
|
|
2501
|
-
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
2502
|
-
}
|
|
2503
|
-
async function listBackups(dir) {
|
|
2504
|
-
if (!existsSync4(dir)) return [];
|
|
2505
|
-
const out = [];
|
|
2506
|
-
for (const name of await readdir4(dir)) {
|
|
2507
|
-
const m = FILE_NAME.exec(name);
|
|
2508
|
-
if (m) out.push({ file: path5.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
|
|
2858
|
+
const current = await client.getServerConfiguration();
|
|
2859
|
+
if (!opts.force && changedSince({ ...plan, changes: [change] }, remote, current).length) {
|
|
2860
|
+
throw new Error("global scripts changed on the server during the push; pull and try again");
|
|
2861
|
+
}
|
|
2862
|
+
await client.putGlobalScripts(local["globalScripts"]);
|
|
2863
|
+
}
|
|
2864
|
+
} catch (err) {
|
|
2865
|
+
return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds, sentLibraries };
|
|
2866
|
+
}
|
|
2867
|
+
applied.push(change);
|
|
2868
|
+
touchedIds.add(change.id);
|
|
2869
|
+
}
|
|
2509
2870
|
}
|
|
2510
|
-
return
|
|
2871
|
+
return { applied, touchedIds, sentLibraries };
|
|
2511
2872
|
}
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
if (!existsSync4(file)) return {};
|
|
2516
|
-
try {
|
|
2517
|
-
const parsed = JSON.parse(await readFile4(file, "utf8"));
|
|
2518
|
-
return parsed.files ?? {};
|
|
2519
|
-
} catch (err) {
|
|
2520
|
-
throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
|
|
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`);
|
|
2521
2876
|
}
|
|
2522
2877
|
}
|
|
2523
|
-
async function
|
|
2524
|
-
|
|
2525
|
-
await writePrivate(path5.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
|
|
2526
|
-
`);
|
|
2527
|
-
}
|
|
2528
|
-
async function backupsOf(dir, serverId) {
|
|
2529
|
-
const manifest = await readManifest(dir);
|
|
2530
|
-
return (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === serverId);
|
|
2531
|
-
}
|
|
2532
|
-
async function originOf(dir, file) {
|
|
2533
|
-
if (!existsSync4(dir) || !sameFile(path5.dirname(file), dir)) return null;
|
|
2534
|
-
return (await readManifest(dir))[path5.basename(file)] ?? null;
|
|
2878
|
+
async function checkTemplate(client, change, remote, force) {
|
|
2879
|
+
checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
|
|
2535
2880
|
}
|
|
2536
|
-
async function
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
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 };
|
|
2541
2890
|
}
|
|
2542
|
-
async function
|
|
2543
|
-
|
|
2544
|
-
const
|
|
2545
|
-
const
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
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
|
+
}
|
|
2555
2906
|
}
|
|
2556
|
-
|
|
2557
|
-
return file;
|
|
2558
|
-
}
|
|
2559
|
-
function sameFile(a, b) {
|
|
2560
|
-
const real = (p) => {
|
|
2561
|
-
const resolved = existsSync4(p) ? realpathSync.native(p) : path5.resolve(p);
|
|
2562
|
-
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
2563
|
-
};
|
|
2564
|
-
return real(a) === real(b);
|
|
2565
|
-
}
|
|
2566
|
-
async function ensureBackupDir(dir) {
|
|
2567
|
-
if (existsSync4(dir)) return;
|
|
2568
|
-
await mkdir3(dir, { recursive: true, mode: 448 });
|
|
2569
|
-
await writeFile4(path5.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
|
|
2907
|
+
return { deployed, skipped, failures };
|
|
2570
2908
|
}
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
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;
|
|
2579
2923
|
}
|
|
2924
|
+
return changed;
|
|
2580
2925
|
}
|
|
2581
|
-
function
|
|
2582
|
-
|
|
2583
|
-
|
|
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));
|
|
2584
2930
|
}
|
|
2585
|
-
function
|
|
2586
|
-
const
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
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));
|
|
2591
2947
|
}
|
|
2592
|
-
return 0;
|
|
2593
2948
|
}
|
|
2594
2949
|
|
|
2595
2950
|
// src/xml/chars.ts
|
|
2596
2951
|
import { readFile as readFile5 } from "fs/promises";
|
|
2597
|
-
import * as
|
|
2952
|
+
import * as path8 from "path";
|
|
2598
2953
|
|
|
2599
2954
|
// src/tree/transaction.ts
|
|
2600
2955
|
import { randomUUID } from "crypto";
|
|
2601
|
-
import { constants, existsSync as
|
|
2602
|
-
import { copyFile as copyFile2, lstat as
|
|
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";
|
|
2603
2958
|
import { hostname } from "os";
|
|
2604
|
-
import * as
|
|
2959
|
+
import * as path7 from "path";
|
|
2605
2960
|
import { setTimeout as delay } from "timers/promises";
|
|
2606
2961
|
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2607
2962
|
async function treeFiles(base) {
|
|
2608
2963
|
const out = [];
|
|
2609
2964
|
for (const d of MANAGED_DIRS) {
|
|
2610
|
-
if (!
|
|
2611
|
-
for (const entry of await readdir5(
|
|
2612
|
-
if (entry.isFile()) out.push(
|
|
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("/"));
|
|
2613
2968
|
}
|
|
2614
2969
|
}
|
|
2615
2970
|
return out;
|
|
@@ -2618,21 +2973,6 @@ var STAGING_DIR = ".channelvault-staging";
|
|
|
2618
2973
|
var JOURNAL = ".channelvault-transaction.json";
|
|
2619
2974
|
var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
|
|
2620
2975
|
var RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2621
|
-
async function present(file) {
|
|
2622
|
-
return lstat2(file).then(() => true, (err) => {
|
|
2623
|
-
if (err.code === "ENOENT") return false;
|
|
2624
|
-
throw err;
|
|
2625
|
-
});
|
|
2626
|
-
}
|
|
2627
|
-
async function canonical(file, depth = 0) {
|
|
2628
|
-
if (depth > 64) throw new Error(`too many links in path: ${file}`);
|
|
2629
|
-
let existing = path6.resolve(file);
|
|
2630
|
-
while (!await present(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
|
|
2631
|
-
const info = await lstat2(existing);
|
|
2632
|
-
const base = info.isSymbolicLink() ? await canonical(path6.resolve(path6.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
|
|
2633
|
-
return path6.join(base, path6.relative(existing, path6.resolve(file)));
|
|
2634
|
-
}
|
|
2635
|
-
var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
2636
2976
|
async function move(from, to) {
|
|
2637
2977
|
for (let attempt = 0; ; attempt++) {
|
|
2638
2978
|
try {
|
|
@@ -2645,15 +2985,15 @@ async function move(from, to) {
|
|
|
2645
2985
|
}
|
|
2646
2986
|
}
|
|
2647
2987
|
async function lockTree(root) {
|
|
2648
|
-
await
|
|
2988
|
+
await mkdir5(path7.dirname(root), { recursive: true });
|
|
2649
2989
|
const lock = `${await canonical(root)}.channelvault-lock`;
|
|
2650
|
-
const ownerFile =
|
|
2990
|
+
const ownerFile = path7.join(lock, "owner.json");
|
|
2651
2991
|
const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
|
|
2652
2992
|
try {
|
|
2653
|
-
await
|
|
2993
|
+
await mkdir5(lock);
|
|
2654
2994
|
} catch (err) {
|
|
2655
2995
|
if (err.code !== "EEXIST") throw err;
|
|
2656
|
-
if ((await
|
|
2996
|
+
if ((await lstat3(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
|
|
2657
2997
|
let previous;
|
|
2658
2998
|
try {
|
|
2659
2999
|
previous = await readJson(ownerFile);
|
|
@@ -2670,9 +3010,9 @@ async function lockTree(root) {
|
|
|
2670
3010
|
}
|
|
2671
3011
|
};
|
|
2672
3012
|
if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
|
|
2673
|
-
const reaping =
|
|
3013
|
+
const reaping = path7.join(lock, "reaping");
|
|
2674
3014
|
try {
|
|
2675
|
-
await
|
|
3015
|
+
await mkdir5(reaping);
|
|
2676
3016
|
} catch {
|
|
2677
3017
|
throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
|
|
2678
3018
|
}
|
|
@@ -2684,7 +3024,7 @@ async function lockTree(root) {
|
|
|
2684
3024
|
await rmdir(reaping);
|
|
2685
3025
|
}
|
|
2686
3026
|
await rmdir(lock);
|
|
2687
|
-
await
|
|
3027
|
+
await mkdir5(lock);
|
|
2688
3028
|
}
|
|
2689
3029
|
try {
|
|
2690
3030
|
await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
|
|
@@ -2701,8 +3041,8 @@ async function lockTree(root) {
|
|
|
2701
3041
|
}
|
|
2702
3042
|
async function assertStage(root) {
|
|
2703
3043
|
for (const suffix of ["", "next", "previous"]) {
|
|
2704
|
-
const stage =
|
|
2705
|
-
const info = await
|
|
3044
|
+
const stage = path7.join(root, STAGING_DIR, suffix);
|
|
3045
|
+
const info = await lstat3(stage).catch((err) => {
|
|
2706
3046
|
if (err.code !== "ENOENT") throw err;
|
|
2707
3047
|
return void 0;
|
|
2708
3048
|
});
|
|
@@ -2710,10 +3050,10 @@ async function assertStage(root) {
|
|
|
2710
3050
|
}
|
|
2711
3051
|
}
|
|
2712
3052
|
function targetOf(root, journal, name) {
|
|
2713
|
-
return name === "env" ? journal.envFile :
|
|
3053
|
+
return name === "env" ? journal.envFile : path7.join(root, name);
|
|
2714
3054
|
}
|
|
2715
3055
|
function copies(root, journal, name) {
|
|
2716
|
-
return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old:
|
|
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) };
|
|
2717
3057
|
}
|
|
2718
3058
|
async function cleanup(root, journal) {
|
|
2719
3059
|
if (journal.entries.some((e) => e.name === "env")) {
|
|
@@ -2721,7 +3061,7 @@ async function cleanup(root, journal) {
|
|
|
2721
3061
|
await rm3(old, { force: true });
|
|
2722
3062
|
await rm3(next, { force: true });
|
|
2723
3063
|
}
|
|
2724
|
-
await rm3(
|
|
3064
|
+
await rm3(path7.join(root, STAGING_DIR), RM);
|
|
2725
3065
|
}
|
|
2726
3066
|
async function rollback(root, journal) {
|
|
2727
3067
|
for (const entry of [...journal.entries].reverse()) {
|
|
@@ -2735,12 +3075,19 @@ async function rollback(root, journal) {
|
|
|
2735
3075
|
}
|
|
2736
3076
|
}
|
|
2737
3077
|
}
|
|
2738
|
-
async function
|
|
2739
|
-
const file =
|
|
2740
|
-
if (!
|
|
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;
|
|
2741
3087
|
await assertStage(root);
|
|
2742
3088
|
const journal = await readJson(file);
|
|
2743
|
-
|
|
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))) {
|
|
2744
3091
|
throw new Error(`invalid transaction journal or different env file: ${file}; use the original --dotenv selection to recover`);
|
|
2745
3092
|
}
|
|
2746
3093
|
if (journal.state === "prepared") await rollback(root, journal);
|
|
@@ -2750,56 +3097,56 @@ async function recoverTree(root, envFile) {
|
|
|
2750
3097
|
async function replaceTree(root, envFile, prepare) {
|
|
2751
3098
|
await recoverTree(root, envFile);
|
|
2752
3099
|
await assertStage(root);
|
|
2753
|
-
const stage =
|
|
3100
|
+
const stage = path7.join(root, STAGING_DIR);
|
|
2754
3101
|
await rm3(stage, RM);
|
|
2755
|
-
const next =
|
|
2756
|
-
await
|
|
3102
|
+
const next = path7.join(stage, "next");
|
|
3103
|
+
await mkdir5(next, { recursive: true });
|
|
2757
3104
|
let journal;
|
|
2758
3105
|
try {
|
|
2759
3106
|
await prepare(next);
|
|
2760
3107
|
const targetEnv = await canonical(envFile);
|
|
2761
3108
|
journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
|
|
2762
3109
|
for (const name of ITEMS) {
|
|
2763
|
-
if (!MANAGED_DIRS.includes(name) && !
|
|
3110
|
+
if (!MANAGED_DIRS.includes(name) && !existsSync7(path7.join(next, name === "env" ? ".env" : name))) continue;
|
|
2764
3111
|
const target = targetOf(root, journal, name);
|
|
2765
|
-
const info = await
|
|
3112
|
+
const info = await lstat3(target).catch((err) => {
|
|
2766
3113
|
if (err.code !== "ENOENT") throw err;
|
|
2767
3114
|
return void 0;
|
|
2768
3115
|
});
|
|
2769
3116
|
journal.entries.push({ name, hadOld: info !== void 0 });
|
|
2770
3117
|
}
|
|
2771
|
-
await
|
|
2772
|
-
await writePrivate(
|
|
3118
|
+
await mkdir5(path7.join(stage, "previous"));
|
|
3119
|
+
await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
|
|
2773
3120
|
if (journal.entries.some((e) => e.name === "env")) {
|
|
2774
|
-
await
|
|
2775
|
-
await copyFile2(
|
|
3121
|
+
await mkdir5(path7.dirname(targetEnv), { recursive: true });
|
|
3122
|
+
await copyFile2(path7.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
|
|
2776
3123
|
}
|
|
2777
3124
|
for (const entry of journal.entries) {
|
|
2778
3125
|
const target = targetOf(root, journal, entry.name);
|
|
2779
3126
|
const files = copies(root, journal, entry.name);
|
|
2780
3127
|
if (entry.hadOld) await move(target, files.old);
|
|
2781
|
-
if (
|
|
2782
|
-
await
|
|
3128
|
+
if (existsSync7(files.next)) {
|
|
3129
|
+
await mkdir5(path7.dirname(target), { recursive: true });
|
|
2783
3130
|
await move(files.next, target);
|
|
2784
3131
|
}
|
|
2785
3132
|
}
|
|
2786
3133
|
journal.state = "committed";
|
|
2787
|
-
await writePrivate(
|
|
3134
|
+
await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
|
|
2788
3135
|
} catch (err) {
|
|
2789
|
-
if (journal &&
|
|
3136
|
+
if (journal && existsSync7(path7.join(root, JOURNAL))) {
|
|
2790
3137
|
try {
|
|
2791
3138
|
await rollback(root, journal);
|
|
2792
3139
|
} catch (recoveryError) {
|
|
2793
|
-
throw new Error(`replacement failed and recovery is pending in ${
|
|
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 });
|
|
2794
3141
|
}
|
|
2795
3142
|
await cleanup(root, journal);
|
|
2796
|
-
await unlink(
|
|
3143
|
+
await unlink(path7.join(root, JOURNAL));
|
|
2797
3144
|
}
|
|
2798
3145
|
await rm3(stage, RM);
|
|
2799
3146
|
throw err;
|
|
2800
3147
|
}
|
|
2801
3148
|
await cleanup(root, journal);
|
|
2802
|
-
await unlink(
|
|
3149
|
+
await unlink(path7.join(root, JOURNAL));
|
|
2803
3150
|
}
|
|
2804
3151
|
|
|
2805
3152
|
// src/xml/chars.ts
|
|
@@ -2826,7 +3173,7 @@ function forbiddenXmlChars(config) {
|
|
|
2826
3173
|
async function forbiddenInFiles(root) {
|
|
2827
3174
|
const out = [];
|
|
2828
3175
|
for (const file of await treeFiles(root)) {
|
|
2829
|
-
for (const p of positions(await readFile5(
|
|
3176
|
+
for (const p of positions(await readFile5(path8.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
|
|
2830
3177
|
}
|
|
2831
3178
|
return out;
|
|
2832
3179
|
}
|
|
@@ -2846,43 +3193,64 @@ async function xmlSafetyProblem(config, treeRoot) {
|
|
|
2846
3193
|
var engine = createExplodeEngine();
|
|
2847
3194
|
var xml = new XmlConfigAdapter();
|
|
2848
3195
|
var VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
2849
|
-
var CliError = class extends
|
|
3196
|
+
var CliError = class extends ReasonError {
|
|
2850
3197
|
};
|
|
2851
|
-
function fail(message) {
|
|
2852
|
-
throw new CliError(message);
|
|
3198
|
+
function fail(message, reason) {
|
|
3199
|
+
throw new CliError(message, reason);
|
|
2853
3200
|
}
|
|
2854
3201
|
var errorExitCode = 1;
|
|
2855
3202
|
var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2856
|
-
function
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
const password = flags.pass ?? process.env.MIRTH_PASS;
|
|
2861
|
-
if (!host) fail("no server host (pass --host or set MIRTH_HOST)");
|
|
2862
|
-
if (!portStr) fail("no server port (pass --port or set MIRTH_PORT)");
|
|
2863
|
-
if (!username) fail("no username (pass --user or set MIRTH_USER)");
|
|
2864
|
-
if (password == null) fail("no password (pass --pass or set MIRTH_PASS)");
|
|
2865
|
-
const port = Number(portStr);
|
|
2866
|
-
if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);
|
|
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) {
|
|
2867
3207
|
return {
|
|
2868
|
-
host,
|
|
2869
|
-
port,
|
|
2870
|
-
username,
|
|
2871
|
-
password,
|
|
2872
|
-
https:
|
|
2873
|
-
disableTlsCheck:
|
|
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 } : {},
|
|
2874
3215
|
// Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).
|
|
2875
3216
|
includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG)
|
|
2876
3217
|
};
|
|
2877
3218
|
}
|
|
2878
|
-
|
|
2879
|
-
|
|
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);
|
|
2880
3240
|
}
|
|
2881
|
-
async function withClient(
|
|
2882
|
-
const client = createMirthClient(
|
|
3241
|
+
async function withClient(conn, fn, opts = {}) {
|
|
3242
|
+
const client = createMirthClient(clientConfigOf(conn));
|
|
2883
3243
|
try {
|
|
2884
3244
|
await client.login();
|
|
2885
|
-
|
|
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);
|
|
2886
3254
|
} finally {
|
|
2887
3255
|
await client.logout().catch(() => void 0);
|
|
2888
3256
|
await client.close().catch(() => void 0);
|
|
@@ -2899,7 +3267,7 @@ function addBackupDirFlags(cmd) {
|
|
|
2899
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})`);
|
|
2900
3268
|
}
|
|
2901
3269
|
function backupDirOf(flags) {
|
|
2902
|
-
return
|
|
3270
|
+
return path9.resolve(flags.backupDir ?? defaultBackupDir());
|
|
2903
3271
|
}
|
|
2904
3272
|
function keepOf(flags) {
|
|
2905
3273
|
if (flags.keep === void 0) return DEFAULT_KEEP;
|
|
@@ -2907,9 +3275,8 @@ function keepOf(flags) {
|
|
|
2907
3275
|
if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);
|
|
2908
3276
|
return n;
|
|
2909
3277
|
}
|
|
2910
|
-
function serverNameOf(config,
|
|
2911
|
-
|
|
2912
|
-
return backupName(config, `${cfg.host}-${cfg.port}`);
|
|
3278
|
+
function serverNameOf(config, conn) {
|
|
3279
|
+
return backupName(config, `${conn.host}-${conn.port}`);
|
|
2913
3280
|
}
|
|
2914
3281
|
function parseBackup(text, where) {
|
|
2915
3282
|
try {
|
|
@@ -2918,61 +3285,61 @@ function parseBackup(text, where) {
|
|
|
2918
3285
|
fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2919
3286
|
}
|
|
2920
3287
|
}
|
|
2921
|
-
async function saveServerBackup(client, text, flags, protect) {
|
|
3288
|
+
async function saveServerBackup(client, text, conn, flags, protect) {
|
|
2922
3289
|
const config = parseBackup(text, "the server configuration");
|
|
2923
|
-
const origin = { serverId: await client.getServerId(), host: hostOf(
|
|
2924
|
-
const file = await saveBackup(backupDirOf(flags), serverNameOf(config,
|
|
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 });
|
|
2925
3292
|
if (gitWouldCommit(file)) {
|
|
2926
3293
|
process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore
|
|
2927
3294
|
`);
|
|
2928
3295
|
}
|
|
2929
3296
|
return file;
|
|
2930
3297
|
}
|
|
2931
|
-
async function backupBeforePush(client, flags) {
|
|
3298
|
+
async function backupBeforePush(client, conn, flags) {
|
|
2932
3299
|
if (flags.backup === false) return;
|
|
2933
|
-
const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
|
|
2934
|
-
process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, flags)})
|
|
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)})
|
|
2935
3302
|
`);
|
|
2936
|
-
printUndoLimits(flags);
|
|
3303
|
+
printUndoLimits(conn, flags);
|
|
2937
3304
|
}
|
|
2938
3305
|
function shellArgument(value) {
|
|
2939
3306
|
return process.platform === "win32" ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, "'\\''")}'`;
|
|
2940
3307
|
}
|
|
2941
|
-
function undoCommand(file, flags) {
|
|
2942
|
-
const
|
|
2943
|
-
|
|
2944
|
-
"
|
|
2945
|
-
|
|
2946
|
-
shellArgument(
|
|
2947
|
-
"--
|
|
2948
|
-
|
|
2949
|
-
"--
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
shellArgument(cfg.username),
|
|
2953
|
-
"--backup-dir",
|
|
2954
|
-
shellArgument(backupDirOf(flags))
|
|
2955
|
-
];
|
|
2956
|
-
if (cfg.https === false) args.push("--no-https");
|
|
2957
|
-
if (cfg.disableTlsCheck) args.push("--insecure");
|
|
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)));
|
|
2958
3319
|
if (flags.overwriteConfigMap) args.push("--overwrite-config-map");
|
|
2959
3320
|
return args.join(" ");
|
|
2960
3321
|
}
|
|
2961
|
-
function printUndoLimits(flags) {
|
|
2962
|
-
if (
|
|
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");
|
|
2963
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");
|
|
2964
3325
|
}
|
|
2965
|
-
function hostOf(
|
|
2966
|
-
|
|
2967
|
-
return `${cfg.host}:${cfg.port}`;
|
|
3326
|
+
function hostOf(conn) {
|
|
3327
|
+
return `${conn.host}:${conn.port}`;
|
|
2968
3328
|
}
|
|
2969
|
-
async function ask(question) {
|
|
2970
|
-
|
|
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 });
|
|
2971
3336
|
const controller = new AbortController();
|
|
2972
3337
|
rl.once("close", () => controller.abort());
|
|
2973
3338
|
rl.once("SIGINT", () => controller.abort());
|
|
2974
3339
|
try {
|
|
2975
|
-
|
|
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();
|
|
2976
3343
|
} catch (err) {
|
|
2977
3344
|
if (controller.signal.aborted) fail("confirmation interrupted; nothing was changed");
|
|
2978
3345
|
throw err;
|
|
@@ -3005,6 +3372,22 @@ function summarize(config) {
|
|
|
3005
3372
|
codeTemplates
|
|
3006
3373
|
};
|
|
3007
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
|
+
}
|
|
3008
3391
|
async function writeMeta(root, source, config, previous, serverId, resources = resourceIds(config)) {
|
|
3009
3392
|
const meta = {
|
|
3010
3393
|
tool: "channelvault",
|
|
@@ -3016,12 +3399,33 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
|
|
|
3016
3399
|
resources,
|
|
3017
3400
|
serverId
|
|
3018
3401
|
};
|
|
3019
|
-
const file =
|
|
3402
|
+
const file = path9.join(root, "channelvault.json");
|
|
3020
3403
|
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
|
|
3021
3404
|
await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
3022
3405
|
}
|
|
3023
|
-
function
|
|
3024
|
-
|
|
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];
|
|
3025
3429
|
}
|
|
3026
3430
|
async function loadEnv(file) {
|
|
3027
3431
|
return { ...await readEnvFile(file), ...process.env };
|
|
@@ -3033,26 +3437,38 @@ function addExtractFlag(cmd) {
|
|
|
3033
3437
|
return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
|
|
3034
3438
|
}
|
|
3035
3439
|
async function existingTree(root) {
|
|
3036
|
-
return
|
|
3440
|
+
return existsSync8(path9.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
|
|
3037
3441
|
}
|
|
3038
|
-
async function renderedTree(root,
|
|
3442
|
+
async function renderedTree(root, envFile) {
|
|
3039
3443
|
const tree = await engine.implode({ root });
|
|
3040
|
-
const env = await loadEnv(
|
|
3444
|
+
const env = await loadEnv(envFile);
|
|
3041
3445
|
rememberSecrets(tree, env);
|
|
3042
3446
|
return render(tree, env);
|
|
3043
3447
|
}
|
|
3044
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
|
+
}
|
|
3045
3455
|
function rememberSecrets(tree, env) {
|
|
3046
3456
|
mapLeaves(tree, (value) => {
|
|
3047
|
-
for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g))
|
|
3048
|
-
const secret = env[m[1]];
|
|
3049
|
-
if (secret !== void 0 && secret.length >= 4) knownSecrets.add(secret);
|
|
3050
|
-
}
|
|
3457
|
+
for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) rememberSecret(env[m[1]]);
|
|
3051
3458
|
return value;
|
|
3052
3459
|
});
|
|
3053
3460
|
}
|
|
3054
|
-
|
|
3055
|
-
const
|
|
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) => [
|
|
3056
3472
|
s,
|
|
3057
3473
|
JSON.stringify(s).slice(1, -1),
|
|
3058
3474
|
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"),
|
|
@@ -3062,13 +3478,12 @@ function scrub(text) {
|
|
|
3062
3478
|
}
|
|
3063
3479
|
var ALLOW_FILE = "channelvault.allow.json";
|
|
3064
3480
|
async function readAllow(root) {
|
|
3065
|
-
const file =
|
|
3066
|
-
if (!
|
|
3481
|
+
const file = path9.join(root, ALLOW_FILE);
|
|
3482
|
+
if (!existsSync8(file)) return [];
|
|
3067
3483
|
const parsed = await readJson(file);
|
|
3068
3484
|
return parsed.ignore ?? [];
|
|
3069
3485
|
}
|
|
3070
|
-
async function writeTree(root, fetched, source, flags, serverId) {
|
|
3071
|
-
const envFile = envFilePath(root, flags);
|
|
3486
|
+
async function writeTree(root, fetched, source, flags, envFile, serverId) {
|
|
3072
3487
|
const previousMeta = await preflightTree(root, envFile);
|
|
3073
3488
|
const env = await loadEnv(envFile);
|
|
3074
3489
|
const templated = templatize(fetched, await existingTree(root), env);
|
|
@@ -3088,27 +3503,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
3088
3503
|
const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
|
|
3089
3504
|
rememberSecrets(config, { ...env, ...envUpdates });
|
|
3090
3505
|
const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
|
|
3091
|
-
const rel =
|
|
3092
|
-
const envInTree = !rel.startsWith("..") && !
|
|
3506
|
+
const rel = path9.relative(root, envFile);
|
|
3507
|
+
const envInTree = !rel.startsWith("..") && !path9.isAbsolute(rel);
|
|
3093
3508
|
let backup = null;
|
|
3094
3509
|
await replaceTree(root, envFile, async (next) => {
|
|
3095
3510
|
await engine.explode(config, { root: next });
|
|
3096
3511
|
await writeMeta(next, source, fetched, previousMeta, serverId);
|
|
3097
3512
|
if (Object.keys(envUpdates).length > 0) {
|
|
3098
|
-
const history =
|
|
3099
|
-
if (
|
|
3100
|
-
if ((await
|
|
3101
|
-
await cp(history,
|
|
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 });
|
|
3102
3517
|
}
|
|
3103
|
-
const stagedBackup = await backupEnvFile(envFile, envUpdates,
|
|
3104
|
-
if (stagedBackup) backup =
|
|
3518
|
+
const stagedBackup = await backupEnvFile(envFile, envUpdates, path9.join(next, ".secrets"));
|
|
3519
|
+
if (stagedBackup) backup = path9.join(root, ".secrets", path9.basename(stagedBackup));
|
|
3105
3520
|
if (backup || envInTree) {
|
|
3106
|
-
const ignore =
|
|
3107
|
-
if (
|
|
3521
|
+
const ignore = path9.join(root, ".gitignore");
|
|
3522
|
+
if (existsSync8(ignore)) await writeFile6(path9.join(next, ".gitignore"), await readFile6(ignore));
|
|
3108
3523
|
await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
|
|
3109
3524
|
}
|
|
3110
|
-
const stagedEnv =
|
|
3111
|
-
if (
|
|
3525
|
+
const stagedEnv = path9.join(next, ".env");
|
|
3526
|
+
if (existsSync8(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
|
|
3112
3527
|
await updateEnvFile(stagedEnv, envUpdates);
|
|
3113
3528
|
}
|
|
3114
3529
|
});
|
|
@@ -3125,48 +3540,24 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
3125
3540
|
process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
|
|
3126
3541
|
`);
|
|
3127
3542
|
}
|
|
3128
|
-
if (
|
|
3543
|
+
if (existsSync8(envFile) && gitWouldCommit(envFile)) {
|
|
3129
3544
|
process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
|
|
3130
3545
|
`);
|
|
3131
3546
|
}
|
|
3132
3547
|
}
|
|
3133
3548
|
function gitWouldCommit(file) {
|
|
3134
|
-
const r =
|
|
3549
|
+
const r = spawnSync2("git", ["check-ignore", "-q", path9.basename(file)], { cwd: path9.dirname(file) });
|
|
3135
3550
|
return r.status === 1;
|
|
3136
3551
|
}
|
|
3137
|
-
async function resolvedPath(p) {
|
|
3138
|
-
const abs = path8.resolve(p);
|
|
3139
|
-
let existing = abs;
|
|
3140
|
-
while (!existsSync6(existing) && path8.dirname(existing) !== existing) existing = path8.dirname(existing);
|
|
3141
|
-
return path8.join(await realpath4(existing), path8.relative(existing, abs));
|
|
3142
|
-
}
|
|
3143
|
-
function isWithin(child, parent) {
|
|
3144
|
-
const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
3145
|
-
const rel = path8.relative(norm(parent), norm(child));
|
|
3146
|
-
return rel === "" || rel !== ".." && !rel.startsWith(`..${path8.sep}`) && !path8.isAbsolute(rel);
|
|
3147
|
-
}
|
|
3148
3552
|
async function preflightTree(root, envFile) {
|
|
3149
3553
|
const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
|
|
3150
3554
|
const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
|
|
3151
|
-
(d) => isWithin(
|
|
3555
|
+
(d) => isWithin(path9.resolve(envFile), path9.resolve(root, d)) || isWithin(realEnv, path9.join(realRoot, d))
|
|
3152
3556
|
);
|
|
3153
3557
|
if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
|
|
3154
|
-
const
|
|
3155
|
-
if (
|
|
3156
|
-
|
|
3157
|
-
try {
|
|
3158
|
-
meta = await readJson(metaPath);
|
|
3159
|
-
} catch (err) {
|
|
3160
|
-
meta = err;
|
|
3161
|
-
}
|
|
3162
|
-
if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
|
|
3163
|
-
fail(
|
|
3164
|
-
`${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ""}; nothing was written. Restore it (for example \`git checkout -- channelvault.json\`) and retry.`
|
|
3165
|
-
);
|
|
3166
|
-
}
|
|
3167
|
-
return meta;
|
|
3168
|
-
}
|
|
3169
|
-
const foreign = MANAGED_DIRS.filter((d) => existsSync6(path8.join(root, d)));
|
|
3558
|
+
const meta = await readMeta(root);
|
|
3559
|
+
if (meta) return meta;
|
|
3560
|
+
const foreign = MANAGED_DIRS.filter((d) => existsSync8(path9.join(root, d)));
|
|
3170
3561
|
if (foreign.length > 0) {
|
|
3171
3562
|
fail(
|
|
3172
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).`
|
|
@@ -3175,16 +3566,14 @@ async function preflightTree(root, envFile) {
|
|
|
3175
3566
|
return null;
|
|
3176
3567
|
}
|
|
3177
3568
|
function assertTree(root) {
|
|
3178
|
-
if (!
|
|
3569
|
+
if (!existsSync8(path9.join(root, "server", "configuration.json"))) {
|
|
3179
3570
|
fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
|
|
3180
3571
|
}
|
|
3181
3572
|
}
|
|
3182
3573
|
async function readTreeOrigin(root) {
|
|
3183
|
-
const metaPath = path8.join(root, "channelvault.json");
|
|
3184
|
-
if (!existsSync6(metaPath)) return "unknown";
|
|
3185
3574
|
try {
|
|
3186
|
-
const meta = await
|
|
3187
|
-
if (typeof meta
|
|
3575
|
+
const meta = await readMeta(root);
|
|
3576
|
+
if (typeof meta?.source === "string") {
|
|
3188
3577
|
if (meta.source.startsWith("file:")) return "xml";
|
|
3189
3578
|
if (/^https?:\/\//i.test(meta.source)) return "live";
|
|
3190
3579
|
}
|
|
@@ -3209,31 +3598,27 @@ function collect(value, previous) {
|
|
|
3209
3598
|
return [...previous ?? [], value];
|
|
3210
3599
|
}
|
|
3211
3600
|
async function bindingProblems(root, serverId) {
|
|
3212
|
-
const
|
|
3213
|
-
const meta = existsSync6(file) ? await readJson(file) : null;
|
|
3601
|
+
const meta = await readMeta(root);
|
|
3214
3602
|
if (meta?.serverId === serverId) return [];
|
|
3215
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`];
|
|
3216
3604
|
}
|
|
3217
3605
|
async function xmlProblems(root, config) {
|
|
3218
|
-
const
|
|
3219
|
-
return
|
|
3606
|
+
const problem2 = await xmlSafetyProblem(config, root);
|
|
3607
|
+
return problem2 ? [problem2] : [];
|
|
3220
3608
|
}
|
|
3221
3609
|
async function assertBinding(client, root) {
|
|
3222
3610
|
const problems = await bindingProblems(root, await client.getServerId());
|
|
3223
3611
|
if (problems.length) fail(problems.join("\n"));
|
|
3224
3612
|
}
|
|
3225
3613
|
async function readKnown(root) {
|
|
3226
|
-
const
|
|
3227
|
-
|
|
3228
|
-
return knownFrom((await readJson(metaPath)).resources);
|
|
3614
|
+
const meta = await readMeta(root);
|
|
3615
|
+
return meta ? knownFrom(meta.resources) : void 0;
|
|
3229
3616
|
}
|
|
3230
3617
|
async function writeKnown(root, known) {
|
|
3231
|
-
const
|
|
3232
|
-
if (!
|
|
3233
|
-
const meta = await readJson(metaPath);
|
|
3234
|
-
if (!meta.resources) return;
|
|
3618
|
+
const meta = await readMeta(root);
|
|
3619
|
+
if (!meta?.resources) return;
|
|
3235
3620
|
meta.resources = known;
|
|
3236
|
-
await writeFile6(
|
|
3621
|
+
await writeFile6(path9.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
3237
3622
|
}
|
|
3238
3623
|
function printNameChange(incoming, current) {
|
|
3239
3624
|
const [to, from] = [configuredName(incoming), configuredName(current)];
|
|
@@ -3270,12 +3655,13 @@ function wholeServerProblems(plan, flags) {
|
|
|
3270
3655
|
if (plan.conflicts.length > 0 && !flags.force) problems.push(...planProblems({ ...plan, changes: [] }, flags));
|
|
3271
3656
|
return problems;
|
|
3272
3657
|
}
|
|
3273
|
-
function reportPlanOnly(flags, plan, problems, extra) {
|
|
3658
|
+
function reportPlanOnly(flags, plan, problems, live, extra) {
|
|
3274
3659
|
if (flags.json) {
|
|
3275
3660
|
writeJson2({
|
|
3276
3661
|
target: extra.target,
|
|
3277
3662
|
mode: extra.mode,
|
|
3278
|
-
|
|
3663
|
+
serverId: live.serverId,
|
|
3664
|
+
connection: connectionJson(live.conn, live.serverId, live.envFile),
|
|
3279
3665
|
changes: plan.changes,
|
|
3280
3666
|
conflicts: plan.conflicts,
|
|
3281
3667
|
serverOnly: plan.serverOnly,
|
|
@@ -3289,11 +3675,11 @@ function reportPlanOnly(flags, plan, problems, extra) {
|
|
|
3289
3675
|
`);
|
|
3290
3676
|
process.stdout.write("plan only: nothing was changed\n");
|
|
3291
3677
|
}
|
|
3292
|
-
async function scopedPush(client, root, local, scope, target, flags) {
|
|
3678
|
+
async function scopedPush(client, root, local, scope, target, flags, live) {
|
|
3293
3679
|
const remote = await client.getServerConfiguration();
|
|
3294
3680
|
const known = await readKnown(root);
|
|
3295
3681
|
const plan = planPush(local, remote, scope, known);
|
|
3296
|
-
const problems = [...await bindingProblems(root,
|
|
3682
|
+
const problems = [...await bindingProblems(root, live.serverId), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
|
|
3297
3683
|
const names = new Map(
|
|
3298
3684
|
[...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
|
|
3299
3685
|
);
|
|
@@ -3303,7 +3689,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
3303
3689
|
const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
|
|
3304
3690
|
if (flags.planOnly && flags.json) {
|
|
3305
3691
|
const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
|
|
3306
|
-
reportPlanOnly(flags, plan, problems, { target, mode: "scoped", ...redeploy });
|
|
3692
|
+
reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped", ...redeploy });
|
|
3307
3693
|
return;
|
|
3308
3694
|
}
|
|
3309
3695
|
if (plan.changes.length === 0) {
|
|
@@ -3329,7 +3715,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
3329
3715
|
`);
|
|
3330
3716
|
}
|
|
3331
3717
|
if (flags.planOnly) {
|
|
3332
|
-
reportPlanOnly(flags, plan, problems, { target, mode: "scoped" });
|
|
3718
|
+
reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped" });
|
|
3333
3719
|
return;
|
|
3334
3720
|
}
|
|
3335
3721
|
if (problems.length > 0) fail(problems.join("\n"));
|
|
@@ -3345,7 +3731,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
3345
3731
|
${moved.join("\n ")}
|
|
3346
3732
|
pull and try again, or pass --force`);
|
|
3347
3733
|
}
|
|
3348
|
-
await backupBeforePush(client, flags);
|
|
3734
|
+
await backupBeforePush(client, live.conn, flags);
|
|
3349
3735
|
const afterBackup = await client.getServerConfiguration();
|
|
3350
3736
|
const changedDuringBackup = changedSince(plan, fresh, afterBackup);
|
|
3351
3737
|
if (!flags.force && changedDuringBackup.length) {
|
|
@@ -3411,7 +3797,7 @@ not checked after saving (these cannot be read one at a time): ${unverified.join
|
|
|
3411
3797
|
printCommitHint(root);
|
|
3412
3798
|
}
|
|
3413
3799
|
function printCommitHint(root) {
|
|
3414
|
-
const r =
|
|
3800
|
+
const r = spawnSync2("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
|
|
3415
3801
|
if (r.status !== 0 || !r.stdout) return;
|
|
3416
3802
|
const entries = r.stdout.split("\0");
|
|
3417
3803
|
const files = [];
|
|
@@ -3449,13 +3835,13 @@ async function changedAgainSingly(client, applied, local) {
|
|
|
3449
3835
|
}
|
|
3450
3836
|
return { changed, unverified };
|
|
3451
3837
|
}
|
|
3452
|
-
async function wholeServerPush(client, root, local, target, flags) {
|
|
3838
|
+
async function wholeServerPush(client, root, local, target, flags, live) {
|
|
3453
3839
|
const remote = await client.getServerConfiguration();
|
|
3454
3840
|
const known = await readKnown(root);
|
|
3455
3841
|
const plan = planPush(local, remote, {}, known, { wholeReplace: true });
|
|
3456
|
-
const problems = [...await bindingProblems(root,
|
|
3842
|
+
const problems = [...await bindingProblems(root, live.serverId), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
|
|
3457
3843
|
if (flags.planOnly && flags.json) {
|
|
3458
|
-
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
3844
|
+
reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
|
|
3459
3845
|
return;
|
|
3460
3846
|
}
|
|
3461
3847
|
const s = summarize(local);
|
|
@@ -3476,7 +3862,7 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
3476
3862
|
`);
|
|
3477
3863
|
if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
|
|
3478
3864
|
if (flags.planOnly) {
|
|
3479
|
-
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
3865
|
+
reportPlanOnly(flags, plan, problems, live, { target, mode: "whole-server" });
|
|
3480
3866
|
return;
|
|
3481
3867
|
}
|
|
3482
3868
|
if (problems.length > 0) fail(problems.join("\n"));
|
|
@@ -3492,7 +3878,7 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
3492
3878
|
if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some((c) => c.op === "delete"))) {
|
|
3493
3879
|
fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
|
|
3494
3880
|
}
|
|
3495
|
-
await backupBeforePush(client, flags);
|
|
3881
|
+
await backupBeforePush(client, live.conn, flags);
|
|
3496
3882
|
const afterBackup = await client.getServerConfiguration();
|
|
3497
3883
|
if (!sameServerConfig(fresh, afterBackup) && !flags.force) fail("the server changed during backup; pull and try again");
|
|
3498
3884
|
const finalPlan = planPush(local, afterBackup, {}, known, { wholeReplace: true });
|
|
@@ -3526,8 +3912,8 @@ addExtractFlag(addEnvFlag(
|
|
|
3526
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")
|
|
3527
3913
|
)).action(async (backupPath, dir, flags) => {
|
|
3528
3914
|
const config = xml.parse(await readFile6(backupPath, "utf8"));
|
|
3529
|
-
const root =
|
|
3530
|
-
await writeTree(root, config, `file:${
|
|
3915
|
+
const root = path9.resolve(dir);
|
|
3916
|
+
await writeTree(root, config, `file:${path9.resolve(backupPath)}`, flags, await envFileFor(root, flags));
|
|
3531
3917
|
const s = summarize(config);
|
|
3532
3918
|
process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
3533
3919
|
`);
|
|
@@ -3535,28 +3921,32 @@ addExtractFlag(addEnvFlag(
|
|
|
3535
3921
|
addEnvFlag(
|
|
3536
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)
|
|
3537
3923
|
).action(async (dir, outPath, flags) => {
|
|
3538
|
-
const root =
|
|
3924
|
+
const root = path9.resolve(dir);
|
|
3539
3925
|
assertTree(root);
|
|
3540
|
-
const config = await renderedTree(root, flags);
|
|
3926
|
+
const config = await renderedTree(root, await envFileFor(root, flags));
|
|
3541
3927
|
await assertCompatibleOrigin(root, config, "xml", flags.force === true);
|
|
3542
3928
|
const xmlStr = xml.build(config);
|
|
3543
3929
|
await writeFile6(outPath, xmlStr, "utf8");
|
|
3544
|
-
process.stdout.write(`imploded ${root} -> ${
|
|
3930
|
+
process.stdout.write(`imploded ${root} -> ${path9.resolve(outPath)}
|
|
3545
3931
|
`);
|
|
3546
3932
|
});
|
|
3547
3933
|
addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
3548
3934
|
program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
|
|
3549
3935
|
))).action(async (dir, flags) => {
|
|
3550
|
-
const root =
|
|
3551
|
-
await
|
|
3552
|
-
const
|
|
3553
|
-
|
|
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
|
+
}
|
|
3554
3945
|
const config2 = await client.getServerConfiguration();
|
|
3555
3946
|
if (await client.getServerId() !== serverId2) fail("the installation changed while pulling; nothing was written");
|
|
3556
3947
|
return { config: config2, serverId: serverId2 };
|
|
3557
|
-
});
|
|
3558
|
-
|
|
3559
|
-
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);
|
|
3560
3950
|
const s = summarize(config);
|
|
3561
3951
|
process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
3562
3952
|
`);
|
|
@@ -3564,23 +3954,23 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
|
3564
3954
|
addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
3565
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)
|
|
3566
3956
|
))).action(async (dir, flags) => {
|
|
3567
|
-
const root =
|
|
3957
|
+
const root = path9.resolve(dir);
|
|
3568
3958
|
assertTree(root);
|
|
3569
|
-
const previous = await preflightTree(root, envFilePath(root, flags));
|
|
3570
|
-
const stored = await engine.implode({ root });
|
|
3571
|
-
const local = await renderedTree(root, flags);
|
|
3572
|
-
await assertCompatibleOrigin(root, local, "live", false);
|
|
3573
3959
|
if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
|
|
3574
3960
|
if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
|
|
3575
|
-
const
|
|
3576
|
-
const
|
|
3577
|
-
await
|
|
3578
|
-
|
|
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) => {
|
|
3579
3969
|
const remote = await client.getServerConfiguration();
|
|
3580
3970
|
const adopted = adoptTarget(local, remote);
|
|
3581
3971
|
const plan = planPush(adopted.config, remote, {}, adopted.known);
|
|
3582
3972
|
if (!flags.json) {
|
|
3583
|
-
process.stdout.write(`Adopt ${
|
|
3973
|
+
process.stdout.write(`Adopt ${targetOf2(conn)} (installation ${serverId}) as this tree's baseline.
|
|
3584
3974
|
Local content is preserved; the following differences become reviewed edits for a subsequent push:
|
|
3585
3975
|
`);
|
|
3586
3976
|
printChanges(plan);
|
|
@@ -3590,7 +3980,7 @@ Local content is preserved; the following differences become reviewed edits for
|
|
|
3590
3980
|
`);
|
|
3591
3981
|
}
|
|
3592
3982
|
if (flags.planOnly) {
|
|
3593
|
-
reportPlanOnly(flags, plan, planProblems(plan, {}), { target, mode: "adopt"
|
|
3983
|
+
reportPlanOnly(flags, plan, planProblems(plan, {}), { conn, serverId, envFile }, { target, mode: "adopt" });
|
|
3594
3984
|
return;
|
|
3595
3985
|
}
|
|
3596
3986
|
if (!flags.yes && !await confirm("Accept this baseline?")) {
|
|
@@ -3601,14 +3991,14 @@ Local content is preserved; the following differences become reviewed edits for
|
|
|
3601
3991
|
fail("the target changed while adopting; nothing was written. Review the new baseline and try again");
|
|
3602
3992
|
}
|
|
3603
3993
|
if (!sameServerConfig(stored, await engine.implode({ root }))) fail("the local tree changed while adopting; nothing was written");
|
|
3604
|
-
await replaceTree(root,
|
|
3994
|
+
await replaceTree(root, envFile, async (next) => {
|
|
3605
3995
|
const rebased = adoptTarget(stored, remote);
|
|
3606
3996
|
await engine.explode(rebased.config, { root: next });
|
|
3607
3997
|
await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
|
|
3608
3998
|
});
|
|
3609
3999
|
process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
|
|
3610
4000
|
`);
|
|
3611
|
-
});
|
|
4001
|
+
}, { envFile, quiet: flags.json });
|
|
3612
4002
|
});
|
|
3613
4003
|
addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
3614
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)
|
|
@@ -3618,36 +4008,38 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
|
3618
4008
|
fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
|
|
3619
4009
|
}
|
|
3620
4010
|
if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
|
|
3621
|
-
const root =
|
|
4011
|
+
const root = path9.resolve(dir);
|
|
3622
4012
|
assertTree(root);
|
|
3623
|
-
const config = await renderedTree(root, flags);
|
|
3624
|
-
await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
|
|
3625
|
-
const cfg = resolveClientConfig(flags);
|
|
3626
|
-
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
3627
4013
|
if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
|
|
3628
4014
|
if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {
|
|
3629
4015
|
fail("no terminal to confirm on; review with `push --plan-only` or `diff`, and pass --yes");
|
|
3630
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;
|
|
3631
4023
|
if (flags.wholeServer) {
|
|
3632
|
-
await withClient(
|
|
4024
|
+
await withClient(conn, (client, serverId) => wholeServerPush(client, root, config, target, flags, { conn, serverId, envFile }), { envFile, quiet });
|
|
3633
4025
|
return;
|
|
3634
4026
|
}
|
|
3635
4027
|
const scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
|
|
3636
|
-
await withClient(
|
|
4028
|
+
await withClient(conn, (client, serverId) => scopedPush(client, root, config, scope, target, flags, { conn, serverId, envFile }), { envFile, quiet });
|
|
3637
4029
|
}
|
|
3638
4030
|
);
|
|
3639
4031
|
addBackupDirFlags(addConnectionFlags(
|
|
3640
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)")
|
|
3641
4033
|
)).action(async (flags) => {
|
|
3642
|
-
const
|
|
3643
|
-
const target =
|
|
3644
|
-
const file = await withClient(
|
|
4034
|
+
const conn = await selectConnection(void 0, flags);
|
|
4035
|
+
const target = targetOf2(conn);
|
|
4036
|
+
const file = await withClient(conn, async (client) => {
|
|
3645
4037
|
const text = await client.getServerConfigurationXml();
|
|
3646
|
-
if (!flags.out) return saveServerBackup(client, text, flags);
|
|
3647
|
-
const out =
|
|
4038
|
+
if (!flags.out) return saveServerBackup(client, text, conn, flags);
|
|
4039
|
+
const out = path9.resolve(flags.out);
|
|
3648
4040
|
parseBackup(text, "the server configuration");
|
|
3649
|
-
if (
|
|
3650
|
-
await
|
|
4041
|
+
if (existsSync8(out)) fail(`${out} already exists; choose another name`);
|
|
4042
|
+
await mkdir6(path9.dirname(out), { recursive: true });
|
|
3651
4043
|
await writePrivate(out, text);
|
|
3652
4044
|
if (gitWouldCommit(out)) {
|
|
3653
4045
|
process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
|
|
@@ -3660,20 +4052,20 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
3660
4052
|
});
|
|
3661
4053
|
async function chooseBackup(dir, file, serverId, target) {
|
|
3662
4054
|
if (file) {
|
|
3663
|
-
const chosen =
|
|
3664
|
-
if (!
|
|
4055
|
+
const chosen = path9.resolve(file);
|
|
4056
|
+
if (!existsSync8(chosen)) fail(`${chosen} does not exist`);
|
|
3665
4057
|
return chosen;
|
|
3666
4058
|
}
|
|
3667
4059
|
const mine = await backupsOf(dir, serverId);
|
|
3668
4060
|
if (mine.length === 0) {
|
|
3669
4061
|
const others = (await originsIn(dir)).map((o) => o.host);
|
|
3670
|
-
const legacy =
|
|
4062
|
+
const legacy = path9.resolve(LEGACY_BACKUP_DIR);
|
|
3671
4063
|
const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
|
|
3672
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)}` : ""));
|
|
3673
4065
|
}
|
|
3674
4066
|
return mine[mine.length - 1].file;
|
|
3675
4067
|
}
|
|
3676
|
-
async function restoreWithBrokenExport(client, file, flags, target) {
|
|
4068
|
+
async function restoreWithBrokenExport(client, serverId, file, flags, target) {
|
|
3677
4069
|
try {
|
|
3678
4070
|
await client.getServerConfigurationXml();
|
|
3679
4071
|
fail("the server can export its configuration; run restore without --export-broken, which shows a preview and saves an undo backup first");
|
|
@@ -3683,7 +4075,6 @@ async function restoreWithBrokenExport(client, file, flags, target) {
|
|
|
3683
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`);
|
|
3684
4076
|
}
|
|
3685
4077
|
}
|
|
3686
|
-
const serverId = await client.getServerId();
|
|
3687
4078
|
const dir = backupDirOf(flags);
|
|
3688
4079
|
const chosen = await chooseBackup(dir, file, serverId, target);
|
|
3689
4080
|
const text = await readFile6(chosen, "utf8");
|
|
@@ -3692,7 +4083,7 @@ async function restoreWithBrokenExport(client, file, flags, target) {
|
|
|
3692
4083
|
if (unsafe) fail(`${chosen} holds ${unsafe}`);
|
|
3693
4084
|
const origin = await originOf(dir, chosen);
|
|
3694
4085
|
if (!origin && !flags.force) {
|
|
3695
|
-
fail(`${chosen} is not in ${
|
|
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`);
|
|
3696
4087
|
}
|
|
3697
4088
|
if (origin && origin.serverId !== serverId && !flags.force) {
|
|
3698
4089
|
fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
|
|
@@ -3724,13 +4115,13 @@ The server cannot export its configuration, so there is no preview, no undo back
|
|
|
3724
4115
|
addBackupDirFlags(addConnectionFlags(
|
|
3725
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)
|
|
3726
4117
|
)).action(async (file, flags) => {
|
|
3727
|
-
const cfg = resolveClientConfig(flags);
|
|
3728
|
-
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
3729
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);
|
|
3730
4121
|
const dir = backupDirOf(flags);
|
|
3731
|
-
await withClient(
|
|
4122
|
+
await withClient(conn, async (client, serverId) => {
|
|
3732
4123
|
if (flags.exportBroken) {
|
|
3733
|
-
await restoreWithBrokenExport(client, file, flags, target);
|
|
4124
|
+
await restoreWithBrokenExport(client, serverId, file, flags, target);
|
|
3734
4125
|
return;
|
|
3735
4126
|
}
|
|
3736
4127
|
let currentText;
|
|
@@ -3740,7 +4131,6 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
3740
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`);
|
|
3741
4132
|
}
|
|
3742
4133
|
const current = parseBackup(currentText, "the server configuration");
|
|
3743
|
-
const serverId = await client.getServerId();
|
|
3744
4134
|
const chosen = await chooseBackup(dir, file, serverId, target);
|
|
3745
4135
|
const text = await readFile6(chosen, "utf8");
|
|
3746
4136
|
const backup = parseBackup(text, chosen);
|
|
@@ -3756,7 +4146,7 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
3756
4146
|
if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
|
|
3757
4147
|
fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
|
|
3758
4148
|
}
|
|
3759
|
-
process.stderr.write(`warning: ${chosen} is not in ${
|
|
4149
|
+
process.stderr.write(`warning: ${chosen} is not in ${path9.join(dir, MANIFEST)}, so which server it came from cannot be checked
|
|
3760
4150
|
`);
|
|
3761
4151
|
}
|
|
3762
4152
|
const [bv, sv] = [backup["@_version"], current["@_version"]];
|
|
@@ -3790,10 +4180,10 @@ to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeplo
|
|
|
3790
4180
|
if (!sameServerConfig(parseBackup(freshText, "the server configuration"), current)) {
|
|
3791
4181
|
fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
|
|
3792
4182
|
}
|
|
3793
|
-
const undo = await saveServerBackup(client, freshText, flags, chosen);
|
|
3794
|
-
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)})
|
|
3795
4185
|
`);
|
|
3796
|
-
printUndoLimits(flags);
|
|
4186
|
+
printUndoLimits(conn, flags);
|
|
3797
4187
|
const afterBackup = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
|
|
3798
4188
|
if (!sameServerConfig(parseBackup(freshText, "the server configuration"), afterBackup)) {
|
|
3799
4189
|
fail("the server changed during the undo backup; nothing was restored. Run it again to review the new state");
|
|
@@ -3815,11 +4205,19 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3815
4205
|
})
|
|
3816
4206
|
))).action(async (dir, flags) => {
|
|
3817
4207
|
errorExitCode = 2;
|
|
3818
|
-
const root =
|
|
4208
|
+
const root = path9.resolve(dir);
|
|
3819
4209
|
assertTree(root);
|
|
3820
|
-
const
|
|
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 });
|
|
3821
4219
|
const tree = await engine.implode({ root });
|
|
3822
|
-
const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(
|
|
4220
|
+
const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFile));
|
|
3823
4221
|
const messages = [
|
|
3824
4222
|
...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
|
|
3825
4223
|
...notes,
|
|
@@ -3838,17 +4236,17 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3838
4236
|
if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
|
|
3839
4237
|
if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
|
|
3840
4238
|
`);
|
|
3841
|
-
const tmp = await mkdtemp(
|
|
4239
|
+
const tmp = await mkdtemp(path9.join(tmpdir(), "channelvault-diff-"));
|
|
3842
4240
|
try {
|
|
3843
|
-
await engine.explode(treeView.config, { root:
|
|
3844
|
-
await engine.explode(serverView.config, { root:
|
|
3845
|
-
await
|
|
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"));
|
|
3846
4244
|
const chunks = [];
|
|
3847
4245
|
for (const d of MANAGED_DIRS) {
|
|
3848
|
-
const local =
|
|
3849
|
-
const server =
|
|
4246
|
+
const local = existsSync8(path9.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
|
|
4247
|
+
const server = existsSync8(path9.join(tmp, "server", d)) ? `server/${d}` : ".empty";
|
|
3850
4248
|
if (local === ".empty" && server === ".empty") continue;
|
|
3851
|
-
const result =
|
|
4249
|
+
const result = spawnSync2(
|
|
3852
4250
|
"git",
|
|
3853
4251
|
["-c", "core.autocrlf=false", "diff", "--no-index", "--no-color", "--ignore-cr-at-eol", local, server],
|
|
3854
4252
|
{ encoding: "utf8", cwd: tmp }
|
|
@@ -3868,8 +4266,8 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3868
4266
|
const clean = out === "" && secretDrift.length === 0;
|
|
3869
4267
|
if (!clean) process.exitCode = 1;
|
|
3870
4268
|
if (flags.json) {
|
|
3871
|
-
const files = await changedFiles(
|
|
3872
|
-
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 });
|
|
3873
4271
|
} else if (clean) {
|
|
3874
4272
|
process.stdout.write("no differences \u2014 working tree matches the server.\n");
|
|
3875
4273
|
} else {
|
|
@@ -3889,27 +4287,29 @@ async function changedFiles(treeDir, serverDir) {
|
|
|
3889
4287
|
const files = [];
|
|
3890
4288
|
for (const p of local) {
|
|
3891
4289
|
if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
|
|
3892
|
-
else if (await readFile6(
|
|
4290
|
+
else if (await readFile6(path9.join(treeDir, p), "utf8") !== await readFile6(path9.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
|
|
3893
4291
|
}
|
|
3894
4292
|
const localSet = new Set(local);
|
|
3895
4293
|
for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
|
|
3896
4294
|
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
3897
4295
|
}
|
|
3898
4296
|
addJsonFlag(addEnvFlag(
|
|
3899
|
-
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")
|
|
3900
4298
|
)).action(async (dir, flags) => {
|
|
3901
|
-
const root =
|
|
4299
|
+
const root = path9.resolve(dir);
|
|
3902
4300
|
assertTree(root);
|
|
3903
4301
|
const config = await engine.implode({ root });
|
|
3904
4302
|
const s = summarize(config);
|
|
3905
|
-
const
|
|
3906
|
-
const
|
|
4303
|
+
const meta = await readMeta(root);
|
|
4304
|
+
const connection = await offlineConnection(meta?.serverId);
|
|
3907
4305
|
if (flags.json) {
|
|
3908
4306
|
writeJson2({
|
|
3909
4307
|
root,
|
|
3910
4308
|
source: meta?.source ?? null,
|
|
3911
4309
|
pulledAt: meta?.pulledAt ?? null,
|
|
3912
4310
|
engineVersion: meta?.engineVersion ?? null,
|
|
4311
|
+
serverId: meta?.serverId ?? null,
|
|
4312
|
+
connection,
|
|
3913
4313
|
counts: s,
|
|
3914
4314
|
xmlForbiddenChars: forbiddenXmlChars(config)
|
|
3915
4315
|
});
|
|
@@ -3923,8 +4323,12 @@ addJsonFlag(addEnvFlag(
|
|
|
3923
4323
|
process.stdout.write(`pulled: ${meta.pulledAt}
|
|
3924
4324
|
`);
|
|
3925
4325
|
process.stdout.write(`engine: ${meta.engineVersion ?? "unknown"}
|
|
4326
|
+
`);
|
|
4327
|
+
if (meta.serverId) process.stdout.write(`server: installation ${meta.serverId}
|
|
3926
4328
|
`);
|
|
3927
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
|
+
`);
|
|
3928
4332
|
process.stdout.write(
|
|
3929
4333
|
`channels: ${s.channels}
|
|
3930
4334
|
channel groups: ${s.channelGroups}
|
|
@@ -3933,36 +4337,252 @@ code templates: ${s.codeTemplates}
|
|
|
3933
4337
|
`
|
|
3934
4338
|
);
|
|
3935
4339
|
});
|
|
3936
|
-
|
|
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
|
+
}
|
|
3937
4540
|
program.hook("preAction", async (_program, command) => {
|
|
3938
4541
|
const name = command.name();
|
|
3939
|
-
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;
|
|
3940
4543
|
if (name === "diff") errorExitCode = 2;
|
|
3941
|
-
const root =
|
|
3942
|
-
|
|
3943
|
-
await
|
|
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()));
|
|
3944
4550
|
});
|
|
3945
|
-
|
|
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) => {
|
|
3946
4568
|
if (err instanceof CommanderError) return;
|
|
3947
|
-
process.stderr.write(`error: ${scrub(
|
|
4569
|
+
process.stderr.write(`error: ${scrub(describeError(err))}
|
|
3948
4570
|
`);
|
|
3949
4571
|
const code = err?.code;
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
}
|
|
3955
|
-
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) {
|
|
3956
4576
|
process.stderr.write(`${scrub(err.stack ?? "")}
|
|
3957
4577
|
`);
|
|
3958
4578
|
}
|
|
3959
4579
|
process.exitCode = errorExitCode;
|
|
3960
4580
|
}).finally(async () => {
|
|
3961
|
-
|
|
4581
|
+
for (const unlock of unlocks.reverse()) {
|
|
3962
4582
|
try {
|
|
3963
4583
|
await unlock();
|
|
3964
4584
|
} catch (err) {
|
|
3965
|
-
process.stderr.write(`error: could not release
|
|
4585
|
+
process.stderr.write(`error: could not release a lock: ${scrub(err instanceof Error ? err.message : String(err))}
|
|
3966
4586
|
`);
|
|
3967
4587
|
process.exitCode = errorExitCode;
|
|
3968
4588
|
}
|