omp-config-crypt 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/bin/omp-sync.js +23 -0
- package/index.js +153 -20
- package/package.json +1 -1
- package/src/preflight.js +231 -0
package/README.md
CHANGED
|
@@ -99,8 +99,16 @@ Configuration exports include the installed `omp-config-crypt` source (excluding
|
|
|
99
99
|
/config-pull https://… [--dry-run] [--force]
|
|
100
100
|
/config-rollback
|
|
101
101
|
/config-upgrade [--check]
|
|
102
|
+
/config-doctor [gist:<id> | https://…]
|
|
102
103
|
```
|
|
103
104
|
|
|
105
|
+
`/config-pull` (and `omp-sync pull`) runs a preflight before downloading: corrupt sync
|
|
106
|
+
metadata is healed in place, an outdated self version is upgraded via npm (restart omp to
|
|
107
|
+
activate), and plugin dependencies missing after the plan are auto-installed and the plan
|
|
108
|
+
recomputed once. Unfixable findings (missing npm, unreachable/wrong target) fail with exact
|
|
109
|
+
next-step commands. `/config-doctor` (or `omp-sync doctor [gist:<id>|https://url]`) runs the
|
|
110
|
+
same checks standalone; exit code 1 when any check fails.
|
|
111
|
+
|
|
104
112
|
### Provider control menu
|
|
105
113
|
|
|
106
114
|
Run `/provider` in an interactive OMP session for the native keyboard menu (↑↓ / Enter / Esc).
|
package/bin/omp-sync.js
CHANGED
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
inventoryResources,
|
|
41
41
|
readSyncState,
|
|
42
42
|
formatSyncReport,
|
|
43
|
+
runPreflight,
|
|
43
44
|
} from "../index.js";
|
|
44
45
|
function printHelp() {
|
|
45
46
|
console.log(`
|
|
@@ -62,6 +63,8 @@ Commands:
|
|
|
62
63
|
conflicts by taking remote or local side; default:
|
|
63
64
|
report conflicts and abort)
|
|
64
65
|
rollback Revert the most recent config restore from its backup
|
|
66
|
+
doctor [target] Preflight env/config checks with self-healing
|
|
67
|
+
(optional gist:<id> or https://url target)
|
|
65
68
|
rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
|
|
66
69
|
maint / gc [--force] Run automatic storage maintenance, WAL checkpoint & GC
|
|
67
70
|
cron [install|status|rm] Manage OS-level scheduled crontab maintenance job
|
|
@@ -376,6 +379,11 @@ async function main() {
|
|
|
376
379
|
if (res.adoptedNamespace) {
|
|
377
380
|
console.log(`[pull] Adopted remote namespace ${res.adoptedNamespace} (--force); prior policy/state saved as .bak`);
|
|
378
381
|
}
|
|
382
|
+
if (Array.isArray(res.preflight) && res.preflight.length > 0) {
|
|
383
|
+
const tally = { pass: 0, fixed: 0, warn: 0 };
|
|
384
|
+
for (const c of res.preflight) tally[c.status] = (tally[c.status] || 0) + 1;
|
|
385
|
+
console.log(`[pull] preflight: ${tally.pass} pass, ${tally.fixed} fixed, ${tally.warn} warn`);
|
|
386
|
+
}
|
|
379
387
|
if (Array.isArray(res.healed) && res.healed.length > 0) {
|
|
380
388
|
console.log(`[pull] Self-healed: ${res.healed.join("; ")}`);
|
|
381
389
|
}
|
|
@@ -424,6 +432,16 @@ async function main() {
|
|
|
424
432
|
break;
|
|
425
433
|
}
|
|
426
434
|
|
|
435
|
+
case "doctor": {
|
|
436
|
+
const target = options.target ? parseSpec(options.target) : null;
|
|
437
|
+
const pf = await runPreflight({ root, target, token: options.token ?? null });
|
|
438
|
+
for (const c of pf.checks) {
|
|
439
|
+
console.log(`[${c.status.toUpperCase()}] ${c.id}: ${c.detail}`);
|
|
440
|
+
}
|
|
441
|
+
if (!pf.ok) process.exitCode = 1;
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
|
|
427
445
|
case "rehydrate": {
|
|
428
446
|
const res = rehydratePlugins(root, { dryRun: options.dryRun });
|
|
429
447
|
console.log(
|
|
@@ -742,6 +760,11 @@ async function main() {
|
|
|
742
760
|
process.exit(1);
|
|
743
761
|
}
|
|
744
762
|
} catch (err) {
|
|
763
|
+
if (Array.isArray(err?.checks)) {
|
|
764
|
+
for (const c of err.checks) {
|
|
765
|
+
console.error(` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
745
768
|
console.error(`[error] ${err.stack || err.message || err}`);
|
|
746
769
|
process.exit(1);
|
|
747
770
|
}
|
package/index.js
CHANGED
|
@@ -8,11 +8,13 @@ import { gzipSync, gunzipSync } from "node:zlib";
|
|
|
8
8
|
import fs from "node:fs";
|
|
9
9
|
import os from "node:os";
|
|
10
10
|
import path from "node:path";
|
|
11
|
+
import { execFileSync } from "node:child_process";
|
|
11
12
|
import {
|
|
12
13
|
rehydratePlugins,
|
|
13
14
|
getPluginLinks,
|
|
14
15
|
savePluginLinks,
|
|
15
16
|
detectMissingPlugins,
|
|
17
|
+
resolveNpmCommand,
|
|
16
18
|
} from "./src/rehydrator.js";
|
|
17
19
|
|
|
18
20
|
export {
|
|
@@ -20,6 +22,18 @@ export {
|
|
|
20
22
|
getPluginLinks,
|
|
21
23
|
savePluginLinks,
|
|
22
24
|
detectMissingPlugins,
|
|
25
|
+
resolveNpmCommand,
|
|
26
|
+
};
|
|
27
|
+
import {
|
|
28
|
+
runPreflight,
|
|
29
|
+
probeGistAccess,
|
|
30
|
+
probeHttpAccess,
|
|
31
|
+
} from "./src/preflight.js";
|
|
32
|
+
|
|
33
|
+
export {
|
|
34
|
+
runPreflight,
|
|
35
|
+
probeGistAccess,
|
|
36
|
+
probeHttpAccess,
|
|
23
37
|
};
|
|
24
38
|
import {
|
|
25
39
|
probeProvider,
|
|
@@ -341,6 +355,43 @@ export function adaptArchive(blob, pass) {
|
|
|
341
355
|
};
|
|
342
356
|
}
|
|
343
357
|
|
|
358
|
+
/**
|
|
359
|
+
* Installs the missing or mismatched plugin dependencies a sync plan blocked on.
|
|
360
|
+
* Versions come from the plan action value when present (internal/hand-built plans);
|
|
361
|
+
* public plans sanitize action values away, so the snapshot payload is consulted as
|
|
362
|
+
* fallback. Skipped entries keep their blocked state and surface as apply errors.
|
|
363
|
+
*/
|
|
364
|
+
export function fixPluginPrerequisites(plan, root, { install, payload = null } = {}) {
|
|
365
|
+
const npmCmd = resolveNpmCommand();
|
|
366
|
+
const doInstall = install ?? ((name, version) => {
|
|
367
|
+
execFileSync(
|
|
368
|
+
npmCmd.file,
|
|
369
|
+
["install", "--prefix", path.join(ompHome(root), "plugins"), `${name}@${version}`],
|
|
370
|
+
{ stdio: "pipe", shell: npmCmd.shell },
|
|
371
|
+
);
|
|
372
|
+
});
|
|
373
|
+
const payloadVersions = new Map((payload?.resources || []).map((resource) => [resource.id, resource.value]));
|
|
374
|
+
const fixed = [];
|
|
375
|
+
const skipped = [];
|
|
376
|
+
for (const action of plan.actions || []) {
|
|
377
|
+
if (action.action !== "blocked" || !String(action.id || "").startsWith("plugin:")) continue;
|
|
378
|
+
if (action.reason !== "plugin-not-installed" && action.reason !== "plugin-version-mismatch") continue;
|
|
379
|
+
const name = action.id.slice("plugin:".length);
|
|
380
|
+
const version = action.value?.version ?? payloadVersions.get(action.id)?.version ?? null;
|
|
381
|
+
if (!version) {
|
|
382
|
+
skipped.push(name);
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
try {
|
|
386
|
+
doInstall(name, version);
|
|
387
|
+
} catch (err) {
|
|
388
|
+
throw new Error(`plugin dependency install failed for ${name}@${version}: ${err.message}`);
|
|
389
|
+
}
|
|
390
|
+
fixed.push(`${name}@${version}`);
|
|
391
|
+
}
|
|
392
|
+
return { fixed, skipped };
|
|
393
|
+
}
|
|
394
|
+
|
|
344
395
|
/**
|
|
345
396
|
* Restores an encrypted archive buffer into the config tree with 3-way merge planning and journaled transaction.
|
|
346
397
|
*/
|
|
@@ -364,7 +415,15 @@ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
|
|
|
364
415
|
}
|
|
365
416
|
|
|
366
417
|
const dryRun = Boolean(options.dryRun);
|
|
367
|
-
|
|
418
|
+
let plan = planSync(effectivePayload, root, { strategy: options.strategy });
|
|
419
|
+
|
|
420
|
+
// Self-healing: install plugin dependencies the plan blocked on, then replan once
|
|
421
|
+
// (the install mutates the plugins tree, so the original plan is stale). Remaining
|
|
422
|
+
// blocked actions still fail the apply.
|
|
423
|
+
if (!dryRun && plan.prerequisites.length > 0 && options.autoFixPlugins !== false) {
|
|
424
|
+
const fx = fixPluginPrerequisites(plan, root, { install: options.installFn, payload: effectivePayload });
|
|
425
|
+
if (fx.fixed.length > 0) plan = planSync(effectivePayload, root, { strategy: options.strategy });
|
|
426
|
+
}
|
|
368
427
|
|
|
369
428
|
if (dryRun) {
|
|
370
429
|
return {
|
|
@@ -705,14 +764,37 @@ export function restoreRemoteArchive(blob, pass, root = configRoot(), options =
|
|
|
705
764
|
};
|
|
706
765
|
}
|
|
707
766
|
|
|
767
|
+
/**
|
|
768
|
+
* Runs the pull preflight before any download; throws a preflight-failed error
|
|
769
|
+
* carrying the full checks list when a fail-status check blocks the pull.
|
|
770
|
+
*/
|
|
771
|
+
async function gatePullPreflight(root, target, token, options = {}) {
|
|
772
|
+
if (options.preflight === false) return [];
|
|
773
|
+
const pf = await runPreflight({ root, target, token, dryRun: Boolean(options.dryRun) });
|
|
774
|
+
if (!pf.ok) {
|
|
775
|
+
const err = new Error(
|
|
776
|
+
`preflight failed:\n${pf.checks
|
|
777
|
+
.filter((check) => check.status === "fail")
|
|
778
|
+
.map((check) => ` [FAIL] ${check.id}: ${check.detail}`)
|
|
779
|
+
.join("\n")}`,
|
|
780
|
+
);
|
|
781
|
+
err.checks = pf.checks;
|
|
782
|
+
throw err;
|
|
783
|
+
}
|
|
784
|
+
return pf.checks;
|
|
785
|
+
}
|
|
786
|
+
|
|
708
787
|
/** Pull the archive from a secret gist. */
|
|
709
788
|
export async function pullGist(id, pass, root = configRoot(), token = envToken(), options = {}) {
|
|
710
789
|
if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
|
|
790
|
+
const preflightChecks = await gatePullPreflight(root, { kind: "gist", id }, token, options);
|
|
711
791
|
const data = await gh(token, `/gists/${id}`);
|
|
712
792
|
const content = data?.files?.[GIST_FILE]?.content;
|
|
713
793
|
if (!content) throw new Error(`gist ${id} has no ${GIST_FILE}`);
|
|
714
794
|
const blob = Buffer.from(content, "base64");
|
|
715
|
-
|
|
795
|
+
const result = restoreRemoteArchive(blob, pass, root, options);
|
|
796
|
+
result.preflight = preflightChecks;
|
|
797
|
+
return result;
|
|
716
798
|
}
|
|
717
799
|
|
|
718
800
|
/** Push to any endpoint accepting PUT (presigned S3, WebDAV, custom). */
|
|
@@ -740,33 +822,41 @@ export async function pushHttp(url, pass, root = configRoot(), token = envToken(
|
|
|
740
822
|
|
|
741
823
|
/** Pull from any endpoint serving the archive. */
|
|
742
824
|
export async function pullHttp(url, pass, root = configRoot(), token = envToken(), options = {}) {
|
|
825
|
+
const preflightChecks = await gatePullPreflight(root, { kind: "http", url }, token, options);
|
|
743
826
|
const res = await fetchWithRetry(url, {
|
|
744
827
|
signal: AbortSignal.timeout(30_000),
|
|
745
828
|
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
746
829
|
});
|
|
747
830
|
if (!res.ok) throw new Error(`GET ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
748
831
|
const blob = Buffer.from(await res.arrayBuffer());
|
|
749
|
-
|
|
832
|
+
const result = restoreRemoteArchive(blob, pass, root, options);
|
|
833
|
+
result.preflight = preflightChecks;
|
|
834
|
+
return result;
|
|
750
835
|
}
|
|
751
836
|
|
|
752
837
|
export function parseSpec(spec) {
|
|
753
|
-
const s = spec.trim();
|
|
754
|
-
if (s.startsWith("gist:")) return { kind: "gist", id: s.slice(5) || "new" };
|
|
755
|
-
if (/^https
|
|
838
|
+
const s = String(spec || "").trim();
|
|
839
|
+
if (s.startsWith("gist:")) return { kind: "gist", id: s.slice(5).split(/\s+/)[0] || "new" };
|
|
840
|
+
if (/^https?:\/\/\S+$/.test(s)) return { kind: "http", url: s };
|
|
756
841
|
throw new Error("expected gist:<id|new> or an https URL");
|
|
757
842
|
}
|
|
758
843
|
|
|
759
844
|
export function extractDryRun(str) {
|
|
760
845
|
const raw = String(str || "").trim();
|
|
761
|
-
if (!raw) return { dryRun: false, clean: "" };
|
|
762
|
-
const
|
|
763
|
-
const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+)/g;
|
|
846
|
+
if (!raw) return { dryRun: false, force: false, strategy: null, clean: "" };
|
|
847
|
+
const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^"\\]*)*)'|(\S+)/g;
|
|
764
848
|
let match;
|
|
765
849
|
let dryRun = false;
|
|
766
850
|
let force = false;
|
|
851
|
+
let strategy = null;
|
|
767
852
|
const kept = [];
|
|
853
|
+
const tokens = [];
|
|
768
854
|
while ((match = re.exec(raw))) {
|
|
769
855
|
const token = match[1] !== undefined ? match[1] : match[2] !== undefined ? match[2] : match[3];
|
|
856
|
+
tokens.push(token);
|
|
857
|
+
}
|
|
858
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
859
|
+
const token = tokens[i];
|
|
770
860
|
if (token === "--dry-run" || token === "-d") {
|
|
771
861
|
dryRun = true;
|
|
772
862
|
continue;
|
|
@@ -775,11 +865,24 @@ export function extractDryRun(str) {
|
|
|
775
865
|
force = true;
|
|
776
866
|
continue;
|
|
777
867
|
}
|
|
868
|
+
if (token === "--strategy") {
|
|
869
|
+
const value = tokens[++i];
|
|
870
|
+
if (value === undefined || value.startsWith("-")) {
|
|
871
|
+
throw new Error("--strategy requires a value: prefer-remote | prefer-local");
|
|
872
|
+
}
|
|
873
|
+
strategy = value;
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
if (token.startsWith("--strategy=")) {
|
|
877
|
+
strategy = token.slice(11);
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
if (token.startsWith("-") && token !== "-") {
|
|
881
|
+
throw new Error(`unknown flag: ${token}`);
|
|
882
|
+
}
|
|
778
883
|
kept.push(token);
|
|
779
884
|
}
|
|
780
|
-
|
|
781
|
-
if (force) result.force = true;
|
|
782
|
-
return result;
|
|
885
|
+
return { dryRun, force, strategy, clean: kept.join(" ") };
|
|
783
886
|
}
|
|
784
887
|
|
|
785
888
|
export function formatSyncReport(result = {}) {
|
|
@@ -1017,14 +1120,14 @@ export default function (pi) {
|
|
|
1017
1120
|
pi.registerCommand("config-import", {
|
|
1018
1121
|
description: "Decrypt and restore an omp config archive (--dry-run to preview)",
|
|
1019
1122
|
handler: async (args, ctx) => {
|
|
1020
|
-
const { dryRun, clean: src } = extractDryRun(args || "");
|
|
1123
|
+
const { dryRun, strategy, clean: src } = extractDryRun(args || "");
|
|
1021
1124
|
if (!src) {
|
|
1022
|
-
ctx.ui.notify("usage: /config-import <file.enc> [--dry-run]", "error");
|
|
1125
|
+
ctx.ui.notify("usage: /config-import <file.enc> [--dry-run] [--strategy prefer-remote|prefer-local]", "error");
|
|
1023
1126
|
return;
|
|
1024
1127
|
}
|
|
1025
1128
|
try {
|
|
1026
1129
|
const pass = await askPass(ctx, "Import passphrase");
|
|
1027
|
-
const r = importEncrypted(src, pass, configRoot(), { dryRun });
|
|
1130
|
+
const r = importEncrypted(src, pass, configRoot(), { dryRun, strategy });
|
|
1028
1131
|
if (r.adaptedFile) {
|
|
1029
1132
|
ctx.ui.notify(`[import] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
|
|
1030
1133
|
}
|
|
@@ -1076,9 +1179,9 @@ export default function (pi) {
|
|
|
1076
1179
|
const sel = await selectPublicResources(ctx, root);
|
|
1077
1180
|
if (sel === null) return;
|
|
1078
1181
|
}
|
|
1079
|
-
const { dryRun, force, clean: spec } = extractDryRun(args || "");
|
|
1182
|
+
const { dryRun, force, strategy, clean: spec } = extractDryRun(args || "");
|
|
1080
1183
|
if (!spec) {
|
|
1081
|
-
ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force]", "error");
|
|
1184
|
+
ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force] [--strategy prefer-remote|prefer-local]", "error");
|
|
1082
1185
|
return;
|
|
1083
1186
|
}
|
|
1084
1187
|
try {
|
|
@@ -1086,8 +1189,14 @@ export default function (pi) {
|
|
|
1086
1189
|
const pass = await askPass(ctx, "Pull passphrase");
|
|
1087
1190
|
const token = await askToken(ctx, "Cloud token", target.kind === "gist");
|
|
1088
1191
|
const r = target.kind === "gist"
|
|
1089
|
-
? await pullGist(target.id, pass, configRoot(), token, { dryRun, force })
|
|
1090
|
-
: await pullHttp(target.url, pass, configRoot(), token, { dryRun, force });
|
|
1192
|
+
? await pullGist(target.id, pass, configRoot(), token, { dryRun, force, strategy })
|
|
1193
|
+
: await pullHttp(target.url, pass, configRoot(), token, { dryRun, force, strategy });
|
|
1194
|
+
if (Array.isArray(r.preflight) && r.preflight.length > 0) {
|
|
1195
|
+
ctx.ui.notify(
|
|
1196
|
+
"[pull] preflight:\n" + r.preflight.map((c) => ` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`).join("\n"),
|
|
1197
|
+
"info",
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1091
1200
|
if (r.adoptedNamespace) {
|
|
1092
1201
|
ctx.ui.notify(`[pull] adopted remote namespace ${r.adoptedNamespace}; prior policy/state saved as .bak`, "info");
|
|
1093
1202
|
}
|
|
@@ -1104,7 +1213,10 @@ export default function (pi) {
|
|
|
1104
1213
|
}
|
|
1105
1214
|
} catch (error) {
|
|
1106
1215
|
const report = error?.plan ? `\n${formatSyncReport(error.plan)}` : "";
|
|
1107
|
-
|
|
1216
|
+
const checkLines = Array.isArray(error?.checks)
|
|
1217
|
+
? `\n${error.checks.map((c) => ` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`).join("\n")}`
|
|
1218
|
+
: "";
|
|
1219
|
+
ctx.ui.notify(`config-pull failed: ${error?.message ?? error}${report}${checkLines}`, "error");
|
|
1108
1220
|
}
|
|
1109
1221
|
},
|
|
1110
1222
|
});
|
|
@@ -1136,6 +1248,27 @@ export default function (pi) {
|
|
|
1136
1248
|
},
|
|
1137
1249
|
});
|
|
1138
1250
|
|
|
1251
|
+
pi.registerCommand("config-doctor", {
|
|
1252
|
+
description: "Preflight environment/config checks with self-healing (optional gist:<id> or https target)",
|
|
1253
|
+
handler: async (args, ctx) => {
|
|
1254
|
+
try {
|
|
1255
|
+
const spec = String(args || "").trim();
|
|
1256
|
+
let target = null;
|
|
1257
|
+
let token = envToken();
|
|
1258
|
+
if (spec) {
|
|
1259
|
+
target = parseSpec(spec);
|
|
1260
|
+
const asked = await askToken(ctx, "Cloud token", target.kind === "gist");
|
|
1261
|
+
if (asked) token = asked;
|
|
1262
|
+
}
|
|
1263
|
+
const pf = await runPreflight({ root: configRoot(), target, token });
|
|
1264
|
+
const lines = pf.checks.map((c) => ` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`).join("\n");
|
|
1265
|
+
ctx.ui.notify(`[doctor] ${pf.ok ? "all checks passed" : "checks failed"}\n${lines}`, pf.ok ? "info" : "error");
|
|
1266
|
+
} catch (error) {
|
|
1267
|
+
ctx.ui.notify(`config-doctor failed: ${error?.message ?? error}`, "error");
|
|
1268
|
+
}
|
|
1269
|
+
},
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1139
1272
|
pi.registerCommand("provider", {
|
|
1140
1273
|
description: "Provider control menu · ls | add | edit <name> | test <name> | rm <name>",
|
|
1141
1274
|
getArgumentCompletions: prefix => providerCompletions(prefix, configRoot()),
|
package/package.json
CHANGED
package/src/preflight.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pull lifecycle preflight: environment and configuration checks with self-healing.
|
|
3
|
+
* Machine-fixable problems (corrupt sync metadata, outdated self version) are repaired
|
|
4
|
+
* in place; unfixable ones report the exact next command. Every check accepts injected
|
|
5
|
+
* dependencies (fetchImpl / upgradeFn) so the test suite stays fully offline.
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { readSyncPolicy } from "./sync-policy.js";
|
|
10
|
+
import { readSyncState, healSyncMetadata } from "./sync-plan.js";
|
|
11
|
+
import { resolveNpmCommand } from "./rehydrator.js";
|
|
12
|
+
import { runUpgrade } from "./maintenance.js";
|
|
13
|
+
|
|
14
|
+
const GIST_API = "https://api.github.com/gists/";
|
|
15
|
+
const PROBE_TIMEOUT_MS = 30_000;
|
|
16
|
+
|
|
17
|
+
function selfPackage() {
|
|
18
|
+
return JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function nodeEngineFloor() {
|
|
22
|
+
const match = /^>=\s*(\d+)/.exec(String(selfPackage().engines?.node || ""));
|
|
23
|
+
return match ? Number(match[1]) : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Availability check without spawning a process: npm must exist on PATH because
|
|
28
|
+
* plugin dependency installs and self-upgrades both shell out through it.
|
|
29
|
+
*/
|
|
30
|
+
function npmOnPath(npmCmd) {
|
|
31
|
+
const dirs = String(process.env.PATH || process.env.Path || "").split(path.delimiter).filter(Boolean);
|
|
32
|
+
for (const dir of dirs) {
|
|
33
|
+
try {
|
|
34
|
+
fs.accessSync(path.join(dir, npmCmd.file), fs.constants.X_OK);
|
|
35
|
+
return true;
|
|
36
|
+
} catch { /* keep scanning */ }
|
|
37
|
+
}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function metadataCorrupt(root) {
|
|
42
|
+
try {
|
|
43
|
+
readSyncPolicy(root);
|
|
44
|
+
} catch {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
readSyncState(root);
|
|
49
|
+
} catch {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Probes gist readability with the same headers the pull transport uses.
|
|
57
|
+
* HEAD is not supported by the gists endpoint, so this is a GET; it does not
|
|
58
|
+
* read or parse the body.
|
|
59
|
+
*/
|
|
60
|
+
export async function probeGistAccess(id, token, fetchImpl = fetch) {
|
|
61
|
+
try {
|
|
62
|
+
const res = await fetchImpl(`${GIST_API}${encodeURIComponent(id)}`, {
|
|
63
|
+
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
|
|
64
|
+
headers: {
|
|
65
|
+
accept: "application/vnd.github+json",
|
|
66
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
if (res.status === 401 || res.status === 403) {
|
|
70
|
+
return {
|
|
71
|
+
ok: false,
|
|
72
|
+
status: res.status,
|
|
73
|
+
message: `token unauthorized (${res.status}): ensure OMP_CFG_CLOUD_TOKEN has 'gist' scope and belongs to the gist owner`,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (res.status === 404) {
|
|
77
|
+
return {
|
|
78
|
+
ok: false,
|
|
79
|
+
status: res.status,
|
|
80
|
+
message: "gist not found (404): wrong id, or this token cannot see the gist",
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (res.ok) return { ok: true, status: res.status, message: "gist accessible" };
|
|
84
|
+
return { ok: false, status: res.status, message: `GitHub API ${res.status} while probing the gist` };
|
|
85
|
+
} catch (err) {
|
|
86
|
+
return { ok: false, status: null, message: `api.github.com unreachable: ${err.message}` };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Probes a plain HTTP(S) target serving the archive.
|
|
92
|
+
*/
|
|
93
|
+
export async function probeHttpAccess(url, fetchImpl = fetch) {
|
|
94
|
+
try {
|
|
95
|
+
const res = await fetchImpl(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
|
96
|
+
const ok = res.status >= 200 && res.status < 400;
|
|
97
|
+
return {
|
|
98
|
+
ok,
|
|
99
|
+
status: res.status,
|
|
100
|
+
message: ok ? `target reachable (HTTP ${res.status})` : `HTTP ${res.status} from target`,
|
|
101
|
+
};
|
|
102
|
+
} catch (err) {
|
|
103
|
+
return { ok: false, status: null, message: `target unreachable: ${err.message}` };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Runs the ordered preflight checklist for a pull (or a standalone doctor run).
|
|
109
|
+
* Returns `{ ok, checks }` where ok is true unless any check reports "fail";
|
|
110
|
+
* "fixed" marks issues repaired in place, "warn" marks non-blocking findings.
|
|
111
|
+
*/
|
|
112
|
+
export async function runPreflight({
|
|
113
|
+
root,
|
|
114
|
+
target = null,
|
|
115
|
+
token = null,
|
|
116
|
+
dryRun = false,
|
|
117
|
+
fetchImpl = null,
|
|
118
|
+
upgradeFn = runUpgrade,
|
|
119
|
+
} = {}) {
|
|
120
|
+
const checks = [];
|
|
121
|
+
const doFetch = fetchImpl || fetch;
|
|
122
|
+
|
|
123
|
+
// metadata: sync policy/state must be readable; heal in place unless dry-run.
|
|
124
|
+
try {
|
|
125
|
+
if (metadataCorrupt(root)) {
|
|
126
|
+
if (dryRun) {
|
|
127
|
+
checks.push({ id: "metadata", status: "warn", detail: "corrupt; would heal on apply" });
|
|
128
|
+
} else {
|
|
129
|
+
const healed = healSyncMetadata(root).healed;
|
|
130
|
+
if (healed.length > 0) {
|
|
131
|
+
checks.push({ id: "metadata", status: "fixed", detail: healed.join("; ") });
|
|
132
|
+
} else {
|
|
133
|
+
checks.push({ id: "metadata", status: "pass", detail: "policy and state readable" });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
checks.push({ id: "metadata", status: "pass", detail: "policy and state readable" });
|
|
138
|
+
}
|
|
139
|
+
} catch (err) {
|
|
140
|
+
checks.push({ id: "metadata", status: "fail", detail: `sync metadata not repairable: ${err.message}` });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// node-engine: informational gate against package.json engines (warn only).
|
|
144
|
+
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
145
|
+
const floor = nodeEngineFloor();
|
|
146
|
+
if (floor !== null && nodeMajor < floor) {
|
|
147
|
+
checks.push({
|
|
148
|
+
id: "node-engine",
|
|
149
|
+
status: "warn",
|
|
150
|
+
detail: `node ${process.versions.node} is below engines.node >=${floor}; upgrade when possible`,
|
|
151
|
+
});
|
|
152
|
+
} else {
|
|
153
|
+
checks.push({ id: "node-engine", status: "pass", detail: `node ${process.versions.node}` });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// npm-cli: without npm neither plugin installs nor self-upgrade can run.
|
|
157
|
+
const npmCmd = resolveNpmCommand();
|
|
158
|
+
const npmOk = npmOnPath(npmCmd);
|
|
159
|
+
if (npmOk) {
|
|
160
|
+
checks.push({ id: "npm-cli", status: "pass", detail: npmCmd.file });
|
|
161
|
+
} else {
|
|
162
|
+
checks.push({
|
|
163
|
+
id: "npm-cli",
|
|
164
|
+
status: "fail",
|
|
165
|
+
detail: `${npmCmd.file} not found on PATH; plugin install and self-upgrade unavailable`,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// registry + self-version: compare against npm latest; upgrade in place when possible.
|
|
170
|
+
let upgradePlan = null;
|
|
171
|
+
try {
|
|
172
|
+
upgradePlan = await upgradeFn({ check: true });
|
|
173
|
+
} catch (err) {
|
|
174
|
+
checks.push({ id: "registry", status: "warn", detail: `registry check failed: ${err.message}` });
|
|
175
|
+
}
|
|
176
|
+
if (upgradePlan && upgradePlan.latest != null) {
|
|
177
|
+
checks.push({ id: "registry", status: "pass", detail: `local ${upgradePlan.local} / latest ${upgradePlan.latest}` });
|
|
178
|
+
if (upgradePlan.action === "upgrade" && npmOk) {
|
|
179
|
+
try {
|
|
180
|
+
const done = await upgradeFn({});
|
|
181
|
+
if (done.action === "upgraded") {
|
|
182
|
+
checks.push({
|
|
183
|
+
id: "self-version",
|
|
184
|
+
status: "fixed",
|
|
185
|
+
detail: `upgraded ${upgradePlan.local} -> ${upgradePlan.latest}; restart omp to activate`,
|
|
186
|
+
});
|
|
187
|
+
} else {
|
|
188
|
+
checks.push({
|
|
189
|
+
id: "self-version",
|
|
190
|
+
status: "warn",
|
|
191
|
+
detail: `upgrade not completed (${done.action}${done.reason ? `: ${done.reason}` : ""}); continue with ${upgradePlan.local}`,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
} catch (err) {
|
|
195
|
+
checks.push({
|
|
196
|
+
id: "self-version",
|
|
197
|
+
status: "warn",
|
|
198
|
+
detail: `automatic upgrade failed: ${err.message}; continue with ${upgradePlan.local}`,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
} else if (upgradePlan.action === "upgrade") {
|
|
202
|
+
checks.push({
|
|
203
|
+
id: "self-version",
|
|
204
|
+
status: "warn",
|
|
205
|
+
detail: `upgrade available (${upgradePlan.local} -> ${upgradePlan.latest}) but npm is unavailable`,
|
|
206
|
+
});
|
|
207
|
+
} else if (upgradePlan.action === "manual") {
|
|
208
|
+
checks.push({ id: "self-version", status: "warn", detail: upgradePlan.reason || "manual upgrade required" });
|
|
209
|
+
} else {
|
|
210
|
+
checks.push({ id: "self-version", status: "pass", detail: `local ${upgradePlan.local} is up to date` });
|
|
211
|
+
}
|
|
212
|
+
} else if (upgradePlan) {
|
|
213
|
+
checks.push({ id: "registry", status: "warn", detail: "registry unreachable" });
|
|
214
|
+
checks.push({ id: "self-version", status: "warn", detail: "cannot compare versions while the registry is unreachable" });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// remote-access: probe the pull target before spending the real download.
|
|
218
|
+
if (target?.kind === "gist") {
|
|
219
|
+
const probe = await probeGistAccess(target.id, token, doFetch);
|
|
220
|
+
checks.push(probe.ok
|
|
221
|
+
? { id: "remote-access", status: "pass", detail: probe.message }
|
|
222
|
+
: { id: "remote-access", status: "fail", detail: probe.message });
|
|
223
|
+
} else if (target?.kind === "http") {
|
|
224
|
+
const probe = await probeHttpAccess(target.url, doFetch);
|
|
225
|
+
checks.push(probe.ok
|
|
226
|
+
? { id: "remote-access", status: "pass", detail: probe.message }
|
|
227
|
+
: { id: "remote-access", status: "fail", detail: probe.message });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return { ok: checks.every((check) => check.status !== "fail"), checks };
|
|
231
|
+
}
|