@osd-project/osd-cli 0.0.0-stage → 0.8.3
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/LICENSE +202 -0
- package/README.md +585 -2
- package/THIRD_PARTY_NOTICES.md +96 -0
- package/dist/auth-store.d.ts +38 -0
- package/dist/auth-store.js +239 -0
- package/dist/brand-catalog.d.ts +65 -0
- package/dist/brand-catalog.js +175 -0
- package/dist/connect-gate.d.ts +31 -0
- package/dist/connect-gate.js +82 -0
- package/dist/contracts.d.ts +61 -0
- package/dist/contracts.js +145 -0
- package/dist/exit-codes.d.ts +32 -0
- package/dist/exit-codes.js +40 -0
- package/dist/format.d.ts +71 -0
- package/dist/format.js +99 -0
- package/dist/generated/schemas.d.ts +2 -0
- package/dist/generated/schemas.js +1781 -0
- package/dist/guarded-fetch.d.ts +28 -0
- package/dist/guarded-fetch.js +252 -0
- package/dist/help.d.ts +27 -0
- package/dist/help.js +32 -0
- package/dist/http-fetch.d.ts +1 -0
- package/dist/http-fetch.js +17 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +821 -0
- package/dist/logout.d.ts +16 -0
- package/dist/logout.js +82 -0
- package/dist/mcp-auth.d.ts +70 -0
- package/dist/mcp-auth.js +603 -0
- package/dist/mcp-card.d.ts +23 -0
- package/dist/mcp-card.js +18 -0
- package/dist/mcp-client.d.ts +77 -0
- package/dist/mcp-client.js +193 -0
- package/dist/net-guard.d.ts +66 -0
- package/dist/net-guard.js +152 -0
- package/dist/proxy-config.d.ts +51 -0
- package/dist/proxy-config.js +147 -0
- package/dist/request.d.ts +32 -0
- package/dist/request.js +62 -0
- package/dist/resolve-endpoint.d.ts +62 -0
- package/dist/resolve-endpoint.js +172 -0
- package/dist/search.d.ts +39 -0
- package/dist/search.js +69 -0
- package/dist/skill.d.ts +155 -0
- package/dist/skill.js +320 -0
- package/dist/updates.d.ts +101 -0
- package/dist/updates.js +541 -0
- package/dist/verify.d.ts +92 -0
- package/dist/verify.js +379 -0
- package/package.json +55 -3
- package/skill/osd/SKILL.md +400 -0
- package/skill/osd/references/connect-mcp.md +48 -0
package/dist/updates.js
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-update for the installed CLI.
|
|
3
|
+
*
|
|
4
|
+
* On startup the parent reads a 24h cache and, when it is stale, spawns a
|
|
5
|
+
* detached child (`osd __refresh-update-cache --apply`) and moves on -- it
|
|
6
|
+
* never waits on the network or touches stdout. The child queries npm (reusing
|
|
7
|
+
* the user's ~/.npmrc auth), records the result and, when allowed, installs
|
|
8
|
+
* the update:
|
|
9
|
+
*
|
|
10
|
+
* - any newer version under the followed dist-tag (no soak window yet);
|
|
11
|
+
* - `npm deprecate` on the installed version moves it to `latest`, even
|
|
12
|
+
* backwards -- that is the kill switch;
|
|
13
|
+
* - serialized by a lockfile and re-checked under the lock;
|
|
14
|
+
* - installed into a staging prefix, verified there by running the new
|
|
15
|
+
* `osd --version`, then swapped in with two renames, so the live copy is
|
|
16
|
+
* never half-written.
|
|
17
|
+
*
|
|
18
|
+
* The next run prints "osd auto-updated ..." once on stderr. Only global npm
|
|
19
|
+
* installs on Linux/macOS are touched; other platforms are not. Opt-outs:
|
|
20
|
+
* `OSD_NO_AUTO_UPDATE` (check + notice only), `OSD_NO_UPDATE_CHECK` or `CI`
|
|
21
|
+
* (everything). `OSD_UPDATE_TAG` follows another dist-tag.
|
|
22
|
+
*/
|
|
23
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
24
|
+
import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
25
|
+
import { createRequire } from "node:module";
|
|
26
|
+
import os from "node:os";
|
|
27
|
+
import path from "node:path";
|
|
28
|
+
import { fileURLToPath } from "node:url";
|
|
29
|
+
export const PACKAGE_NAME = "@osd-project/osd-cli";
|
|
30
|
+
export const REFRESH_COMMAND = "__refresh-update-cache";
|
|
31
|
+
export const CHECK_TTL_MS = 24 * 60 * 60 * 1000;
|
|
32
|
+
const REFRESH_TIMEOUT_MS = 15_000;
|
|
33
|
+
const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
|
|
34
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
35
|
+
export const CLI_VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
36
|
+
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
37
|
+
export function compareVersions(a, b) {
|
|
38
|
+
const ma = SEMVER_RE.exec(a);
|
|
39
|
+
const mb = SEMVER_RE.exec(b);
|
|
40
|
+
if (!ma || !mb)
|
|
41
|
+
return null;
|
|
42
|
+
for (let i = 1; i <= 3; i++) {
|
|
43
|
+
const diff = Number(ma[i]) - Number(mb[i]);
|
|
44
|
+
if (diff !== 0)
|
|
45
|
+
return diff;
|
|
46
|
+
}
|
|
47
|
+
const pa = ma[4];
|
|
48
|
+
const pb = mb[4];
|
|
49
|
+
if (pa === pb)
|
|
50
|
+
return 0;
|
|
51
|
+
if (pa === undefined)
|
|
52
|
+
return 1; // release > prerelease of the same core
|
|
53
|
+
if (pb === undefined)
|
|
54
|
+
return -1;
|
|
55
|
+
return comparePrerelease(pa, pb);
|
|
56
|
+
}
|
|
57
|
+
function comparePrerelease(a, b) {
|
|
58
|
+
const ia = a.split(".");
|
|
59
|
+
const ib = b.split(".");
|
|
60
|
+
for (let i = 0; i < Math.max(ia.length, ib.length); i++) {
|
|
61
|
+
if (ia[i] === undefined)
|
|
62
|
+
return -1;
|
|
63
|
+
if (ib[i] === undefined)
|
|
64
|
+
return 1;
|
|
65
|
+
const na = /^\d+$/.test(ia[i]) ? Number(ia[i]) : null;
|
|
66
|
+
const nb = /^\d+$/.test(ib[i]) ? Number(ib[i]) : null;
|
|
67
|
+
if (na !== null && nb !== null) {
|
|
68
|
+
if (na !== nb)
|
|
69
|
+
return na - nb;
|
|
70
|
+
}
|
|
71
|
+
else if (na !== null) {
|
|
72
|
+
return -1;
|
|
73
|
+
}
|
|
74
|
+
else if (nb !== null) {
|
|
75
|
+
return 1;
|
|
76
|
+
}
|
|
77
|
+
else if (ia[i] !== ib[i]) {
|
|
78
|
+
return ia[i] < ib[i] ? -1 : 1;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
/** Strictly newer only, so a stale dist-tag can never suggest a downgrade. */
|
|
84
|
+
export function isNewer(latest, current) {
|
|
85
|
+
if (!latest)
|
|
86
|
+
return false;
|
|
87
|
+
const cmp = compareVersions(latest, current);
|
|
88
|
+
return cmp !== null && cmp > 0;
|
|
89
|
+
}
|
|
90
|
+
function isPrerelease(version) {
|
|
91
|
+
return SEMVER_RE.exec(version)?.[4] !== undefined;
|
|
92
|
+
}
|
|
93
|
+
export function packageRoot(moduleUrl = import.meta.url) {
|
|
94
|
+
const file = fileURLToPath(moduleUrl);
|
|
95
|
+
let resolved = file;
|
|
96
|
+
try {
|
|
97
|
+
resolved = realpathSync(file);
|
|
98
|
+
}
|
|
99
|
+
catch { }
|
|
100
|
+
return path.dirname(path.dirname(resolved)); // <root>/dist/updates.js -> <root>
|
|
101
|
+
}
|
|
102
|
+
/** Pure path check (no subprocess) so it's free on every startup. Workspace builds and `pnpm link` return false. */
|
|
103
|
+
export function isPackageInstall(root = packageRoot()) {
|
|
104
|
+
const parts = root.split("/");
|
|
105
|
+
const n = parts.length;
|
|
106
|
+
return n >= 3 && parts[n - 3] === "node_modules" && parts[n - 2] === "@osd-project" && parts[n - 1] === "osd-cli";
|
|
107
|
+
}
|
|
108
|
+
/** Prefer the npm next to the running node, so nvm/fnm users hit the prefix `osd` is installed in. */
|
|
109
|
+
export function npmCommand() {
|
|
110
|
+
const override = process.env.OSD_NPM;
|
|
111
|
+
if (override)
|
|
112
|
+
return override;
|
|
113
|
+
const sibling = path.join(path.dirname(process.execPath), "npm");
|
|
114
|
+
return existsSync(sibling) ? sibling : "npm";
|
|
115
|
+
}
|
|
116
|
+
export function runNpm(args, timeoutMs) {
|
|
117
|
+
const result = spawnSync(npmCommand(), args, {
|
|
118
|
+
encoding: "utf8",
|
|
119
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
120
|
+
timeout: timeoutMs,
|
|
121
|
+
env: npmEnv(),
|
|
122
|
+
});
|
|
123
|
+
return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "", error: result.error };
|
|
124
|
+
}
|
|
125
|
+
export function npmEnv() {
|
|
126
|
+
return { ...process.env, npm_config_update_notifier: "false", npm_config_fund: "false", npm_config_audit: "false" };
|
|
127
|
+
}
|
|
128
|
+
export function distTag(env = process.env) {
|
|
129
|
+
const tag = env.OSD_UPDATE_TAG;
|
|
130
|
+
return tag && /^[A-Za-z][A-Za-z0-9._-]*$/.test(tag) ? tag : "latest";
|
|
131
|
+
}
|
|
132
|
+
/** Parse `npm view <pkg> dist-tags --json`. */
|
|
133
|
+
export function parseRegistryView(stdout, tag) {
|
|
134
|
+
let parsed;
|
|
135
|
+
try {
|
|
136
|
+
parsed = JSON.parse(stdout.trim());
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return { error: "npm view returned non-JSON output" };
|
|
140
|
+
}
|
|
141
|
+
const latest = parsed?.[tag];
|
|
142
|
+
if (typeof latest !== "string" || !SEMVER_RE.test(latest)) {
|
|
143
|
+
return { error: `npm view returned no usable version for dist-tag "${tag}"` };
|
|
144
|
+
}
|
|
145
|
+
return { latest };
|
|
146
|
+
}
|
|
147
|
+
/** `npm view <pkg>@<v> deprecated --json` prints a JSON string when deprecated, nothing otherwise. */
|
|
148
|
+
export function parseDeprecated(stdout) {
|
|
149
|
+
const text = stdout.trim();
|
|
150
|
+
if (!text)
|
|
151
|
+
return null;
|
|
152
|
+
try {
|
|
153
|
+
const value = JSON.parse(text);
|
|
154
|
+
return typeof value === "string" && value ? value : null;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function firstLine(result) {
|
|
161
|
+
return result.stderr.trim().split("\n").find((line) => line.trim()) ?? `exit ${result.status}`;
|
|
162
|
+
}
|
|
163
|
+
export function fetchRegistryState(timeoutMs = REFRESH_TIMEOUT_MS, run = runNpm) {
|
|
164
|
+
const view = run(["view", PACKAGE_NAME, "dist-tags", "--json"], timeoutMs);
|
|
165
|
+
if (view.error)
|
|
166
|
+
return { ok: false, error: view.error.message };
|
|
167
|
+
if (view.status !== 0)
|
|
168
|
+
return { ok: false, error: `npm view failed: ${firstLine(view)}` };
|
|
169
|
+
const parsed = parseRegistryView(view.stdout, distTag());
|
|
170
|
+
if ("error" in parsed)
|
|
171
|
+
return { ok: false, error: parsed.error };
|
|
172
|
+
// Best-effort: a failed deprecation lookup just means "not deprecated".
|
|
173
|
+
const dep = run(["view", `${PACKAGE_NAME}@${CLI_VERSION}`, "deprecated", "--json"], timeoutMs);
|
|
174
|
+
const installedDeprecated = !dep.error && dep.status === 0 ? parseDeprecated(dep.stdout) : null;
|
|
175
|
+
return { ok: true, state: { ...parsed, installedDeprecated } };
|
|
176
|
+
}
|
|
177
|
+
export function configDir() {
|
|
178
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
179
|
+
const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(process.env.HOME || os.homedir(), ".config");
|
|
180
|
+
return path.join(base, "osd");
|
|
181
|
+
}
|
|
182
|
+
export function cachePath() {
|
|
183
|
+
return path.join(configDir(), "update-check.json");
|
|
184
|
+
}
|
|
185
|
+
export function readCache() {
|
|
186
|
+
try {
|
|
187
|
+
const data = JSON.parse(readFileSync(cachePath(), "utf8"));
|
|
188
|
+
if (typeof data.checkedAt !== "string" || typeof data.installedVersion !== "string")
|
|
189
|
+
return null;
|
|
190
|
+
const applied = data.autoApplied;
|
|
191
|
+
return {
|
|
192
|
+
checkedAt: data.checkedAt,
|
|
193
|
+
installedVersion: data.installedVersion,
|
|
194
|
+
latestVersion: typeof data.latestVersion === "string" ? data.latestVersion : null,
|
|
195
|
+
distTag: typeof data.distTag === "string" ? data.distTag : "latest",
|
|
196
|
+
...(typeof data.lastError === "string" ? { lastError: data.lastError } : {}),
|
|
197
|
+
...(typeof data.global === "boolean" ? { global: data.global } : {}),
|
|
198
|
+
...(applied && typeof applied.from === "string" && typeof applied.to === "string"
|
|
199
|
+
? { autoApplied: { from: applied.from, to: applied.to } }
|
|
200
|
+
: {}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
export function writeCache(cache) {
|
|
208
|
+
const file = cachePath();
|
|
209
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
210
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
211
|
+
writeFileSync(tmp, `${JSON.stringify({ ...cache, distTag: distTag() }, null, 2)}\n`, { mode: 0o600 });
|
|
212
|
+
renameSync(tmp, file);
|
|
213
|
+
}
|
|
214
|
+
export function isStale(cache, currentVersion, now = Date.now(), tag = distTag()) {
|
|
215
|
+
if (!cache)
|
|
216
|
+
return true;
|
|
217
|
+
if (cache.installedVersion !== currentVersion || (cache.distTag ?? "latest") !== tag)
|
|
218
|
+
return true;
|
|
219
|
+
const checked = Date.parse(cache.checkedAt);
|
|
220
|
+
if (Number.isNaN(checked))
|
|
221
|
+
return true;
|
|
222
|
+
return now - checked > CHECK_TTL_MS || checked > now + 60_000;
|
|
223
|
+
}
|
|
224
|
+
/** Only the platforms the staged swap has been tested on. */
|
|
225
|
+
export function updatesSupported(platform = process.platform) {
|
|
226
|
+
return platform === "linux" || platform === "darwin";
|
|
227
|
+
}
|
|
228
|
+
export function checksDisabled(env = process.env) {
|
|
229
|
+
return !updatesSupported() || Boolean(env.OSD_NO_UPDATE_CHECK || env.CI);
|
|
230
|
+
}
|
|
231
|
+
export function autoUpdateDisabled(env = process.env) {
|
|
232
|
+
return Boolean(env.OSD_NO_AUTO_UPDATE);
|
|
233
|
+
}
|
|
234
|
+
export function decideAutoApply(state, current, tag = "latest") {
|
|
235
|
+
if (state.installedDeprecated) {
|
|
236
|
+
return compareVersions(state.latest, current) === 0
|
|
237
|
+
? { apply: false, reason: "installed version is deprecated but is also the latest" }
|
|
238
|
+
: { apply: true, version: state.latest, reason: "rollback" };
|
|
239
|
+
}
|
|
240
|
+
if (!isNewer(state.latest, current))
|
|
241
|
+
return { apply: false, reason: "up to date" };
|
|
242
|
+
if (tag === "latest" && isPrerelease(state.latest))
|
|
243
|
+
return { apply: false, reason: "prerelease on latest" };
|
|
244
|
+
return { apply: true, version: state.latest, reason: "update" };
|
|
245
|
+
}
|
|
246
|
+
export function formatNotice(current, latest) {
|
|
247
|
+
return (`osd: update available ${current} -> ${latest}. Run \`osd update\` to upgrade now ` +
|
|
248
|
+
"(set OSD_NO_UPDATE_CHECK=1 to silence).");
|
|
249
|
+
}
|
|
250
|
+
export function cachedNotice(currentVersion = CLI_VERSION) {
|
|
251
|
+
try {
|
|
252
|
+
const cache = readCache();
|
|
253
|
+
if (!cache || cache.global !== true || cache.distTag !== distTag() || !isNewer(cache.latestVersion, currentVersion)) {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
return formatNotice(currentVersion, cache.latestVersion);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** A cached result only carries over if it was for this version and dist-tag. */
|
|
263
|
+
function sameCheck(cache) {
|
|
264
|
+
return cache !== null && cache.installedVersion === CLI_VERSION && cache.distTag === distTag();
|
|
265
|
+
}
|
|
266
|
+
/** "osd auto-updated ..." once, on the first run of the new version. */
|
|
267
|
+
function takeAutoAppliedNotice() {
|
|
268
|
+
const cache = readCache();
|
|
269
|
+
if (!cache?.autoApplied || cache.autoApplied.to !== CLI_VERSION)
|
|
270
|
+
return null;
|
|
271
|
+
const { from, to } = cache.autoApplied;
|
|
272
|
+
const { autoApplied: _, ...rest } = cache;
|
|
273
|
+
writeCache(rest);
|
|
274
|
+
return `osd: auto-updated ${from} -> ${to} (set OSD_NO_AUTO_UPDATE=1 to opt out).`;
|
|
275
|
+
}
|
|
276
|
+
export function notifyAndRefresh(scriptPath = process.argv[1] ?? "") {
|
|
277
|
+
try {
|
|
278
|
+
if (checksDisabled() || !isPackageInstall())
|
|
279
|
+
return;
|
|
280
|
+
process.once("exit", () => {
|
|
281
|
+
try {
|
|
282
|
+
const lines = [takeAutoAppliedNotice(), cachedNotice()].filter(Boolean);
|
|
283
|
+
if (lines.length)
|
|
284
|
+
process.stderr.write(`\n${lines.join("\n")}\n`);
|
|
285
|
+
}
|
|
286
|
+
catch { }
|
|
287
|
+
});
|
|
288
|
+
const cache = readCache();
|
|
289
|
+
if (isStale(cache, CLI_VERSION)) {
|
|
290
|
+
// Pre-stamp so back-to-back runs don't each spawn a refresher.
|
|
291
|
+
writeCache({
|
|
292
|
+
checkedAt: new Date().toISOString(),
|
|
293
|
+
installedVersion: CLI_VERSION,
|
|
294
|
+
latestVersion: sameCheck(cache) ? cache.latestVersion : null,
|
|
295
|
+
...(sameCheck(cache) && cache.global !== undefined ? { global: cache.global } : {}),
|
|
296
|
+
});
|
|
297
|
+
spawnRefresher(scriptPath, !autoUpdateDisabled());
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
catch { }
|
|
301
|
+
}
|
|
302
|
+
function spawnRefresher(scriptPath, apply) {
|
|
303
|
+
if (!scriptPath)
|
|
304
|
+
return;
|
|
305
|
+
const child = spawn(process.execPath, [scriptPath, REFRESH_COMMAND, ...(apply ? ["--apply"] : [])], {
|
|
306
|
+
detached: true,
|
|
307
|
+
stdio: "ignore",
|
|
308
|
+
env: process.env,
|
|
309
|
+
});
|
|
310
|
+
child.on("error", () => { });
|
|
311
|
+
child.unref();
|
|
312
|
+
}
|
|
313
|
+
/** Body of the detached refresher. Never throws. */
|
|
314
|
+
export function refreshCacheNow(options = {}) {
|
|
315
|
+
try {
|
|
316
|
+
// Only global installs get notices and updates; anything else is recorded and left alone.
|
|
317
|
+
const root = packageRoot();
|
|
318
|
+
const globalRoot = npmGlobalRoot();
|
|
319
|
+
if (!globalRoot || !isInGlobalRoot(root, globalRoot)) {
|
|
320
|
+
writeCache({ checkedAt: new Date().toISOString(), installedVersion: CLI_VERSION, latestVersion: null, global: false });
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const previous = readCache();
|
|
324
|
+
const result = (options.lookup ?? (() => fetchRegistryState()))();
|
|
325
|
+
const base = {
|
|
326
|
+
checkedAt: new Date().toISOString(),
|
|
327
|
+
installedVersion: CLI_VERSION,
|
|
328
|
+
latestVersion: result.ok ? result.state.latest : sameCheck(previous) ? previous.latestVersion : null,
|
|
329
|
+
global: true,
|
|
330
|
+
...(result.ok ? {} : { lastError: result.error }),
|
|
331
|
+
};
|
|
332
|
+
writeCache(base);
|
|
333
|
+
if (!result.ok || !options.apply || autoUpdateDisabled())
|
|
334
|
+
return;
|
|
335
|
+
const decision = decideAutoApply(result.state, CLI_VERSION, distTag());
|
|
336
|
+
if (decision.apply)
|
|
337
|
+
applyUpdate(decision.version, root, globalRoot, base);
|
|
338
|
+
}
|
|
339
|
+
catch { }
|
|
340
|
+
}
|
|
341
|
+
function applyUpdate(target, root, globalRoot, base) {
|
|
342
|
+
for (const dir of [globalRoot, path.dirname(root)]) {
|
|
343
|
+
try {
|
|
344
|
+
accessSync(dir, constants.W_OK);
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
writeCache({ ...base, lastError: `auto-update skipped: ${dir} is not writable` });
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const lock = acquireLock();
|
|
352
|
+
if (lock === null)
|
|
353
|
+
return;
|
|
354
|
+
try {
|
|
355
|
+
// Another process may have updated while we were checking.
|
|
356
|
+
if (installedVersionOnDisk(root) !== CLI_VERSION)
|
|
357
|
+
return;
|
|
358
|
+
removeLeftovers(globalRoot, root);
|
|
359
|
+
const outcome = applyStaged(target, root, globalRoot);
|
|
360
|
+
if (outcome === "fallback") {
|
|
361
|
+
applyInPlace(target, root, base);
|
|
362
|
+
}
|
|
363
|
+
else if (outcome === "ok") {
|
|
364
|
+
writeCache({ ...base, installedVersion: target, autoApplied: { from: CLI_VERSION, to: target } });
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
writeCache({ ...base, lastError: `auto-update to ${target} failed: ${outcome}; ${CLI_VERSION} left in place` });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
releaseLock(lock);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const STAGING_PREFIX = ".osd-cli-staging-";
|
|
375
|
+
const RETIRED_PREFIX = ".osd-cli-old-";
|
|
376
|
+
/** Staging and retired copies left behind by a refresher that was killed mid-update. */
|
|
377
|
+
function removeLeftovers(globalRoot, root) {
|
|
378
|
+
for (const [dir, prefix] of [
|
|
379
|
+
[globalRoot, STAGING_PREFIX],
|
|
380
|
+
[path.dirname(root), RETIRED_PREFIX],
|
|
381
|
+
]) {
|
|
382
|
+
try {
|
|
383
|
+
for (const name of readdirSync(dir)) {
|
|
384
|
+
if (name.startsWith(prefix))
|
|
385
|
+
rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
catch { }
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Install into a staging prefix next to the live copy, verify it there, then
|
|
393
|
+
* swap it in with two renames. The live install is never half-written, so a
|
|
394
|
+
* command starting mid-update -- or a refresher killed mid-install -- still
|
|
395
|
+
* sees a complete version. Returns "ok", "fallback" (the bin list changed, so
|
|
396
|
+
* npm has to relink), or a failure reason.
|
|
397
|
+
*/
|
|
398
|
+
function applyStaged(target, root, globalRoot) {
|
|
399
|
+
const staging = path.join(globalRoot, `${STAGING_PREFIX}${process.pid}`);
|
|
400
|
+
const retired = path.join(path.dirname(root), `${RETIRED_PREFIX}${process.pid}`);
|
|
401
|
+
try {
|
|
402
|
+
const install = runNpm(["install", "-g", "--prefix", staging, `${PACKAGE_NAME}@${target}`], INSTALL_TIMEOUT_MS);
|
|
403
|
+
if (install.error || install.status !== 0) {
|
|
404
|
+
return `npm install failed (${install.error?.message ?? firstLine(install)})`;
|
|
405
|
+
}
|
|
406
|
+
const staged = path.join(staging, "lib", "node_modules", "@osd-project", "osd-cli");
|
|
407
|
+
if (!verifyInstall(staged, target))
|
|
408
|
+
return "the new version failed verification";
|
|
409
|
+
if (binNames(staged) !== binNames(root))
|
|
410
|
+
return "fallback";
|
|
411
|
+
renameSync(root, retired);
|
|
412
|
+
try {
|
|
413
|
+
renameSync(staged, root);
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
renameSync(retired, root);
|
|
417
|
+
return `swap failed (${error.message})`;
|
|
418
|
+
}
|
|
419
|
+
return "ok";
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
return `staged install failed (${error.message})`;
|
|
423
|
+
}
|
|
424
|
+
finally {
|
|
425
|
+
rmSync(staging, { recursive: true, force: true });
|
|
426
|
+
rmSync(retired, { recursive: true, force: true });
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function binNames(root) {
|
|
430
|
+
try {
|
|
431
|
+
const bin = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).bin;
|
|
432
|
+
return typeof bin === "object" && bin !== null ? Object.keys(bin).sort().join(",") : String(bin ?? "");
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return "";
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/** Plain `npm install -g` over the live copy; only used when npm must relink bins. */
|
|
439
|
+
function applyInPlace(target, root, base) {
|
|
440
|
+
const install = installVersion(target, { quiet: true, timeoutMs: INSTALL_TIMEOUT_MS });
|
|
441
|
+
if (install.ok && verifyInstall(root, target)) {
|
|
442
|
+
writeCache({ ...base, installedVersion: target, autoApplied: { from: CLI_VERSION, to: target } });
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const why = install.ok ? "the new version failed verification" : `npm install failed (${install.error ?? `exit ${install.status}`})`;
|
|
446
|
+
// npm refusing up front (e.g. min-release-age) leaves the old install intact; only restore if it was touched.
|
|
447
|
+
const intact = installedVersionOnDisk(root) === CLI_VERSION && verifyInstall(root, CLI_VERSION);
|
|
448
|
+
const outcome = intact
|
|
449
|
+
? `${CLI_VERSION} left in place`
|
|
450
|
+
: installVersion(CLI_VERSION, { quiet: true, timeoutMs: INSTALL_TIMEOUT_MS }).ok
|
|
451
|
+
? `restored ${CLI_VERSION}`
|
|
452
|
+
: "restore also failed";
|
|
453
|
+
writeCache({ ...base, lastError: `auto-update to ${target} failed: ${why}; ${outcome}` });
|
|
454
|
+
}
|
|
455
|
+
export function lockPath() {
|
|
456
|
+
return path.join(configDir(), "update.lock");
|
|
457
|
+
}
|
|
458
|
+
/** Exclusive create; a lock older than 15 minutes is treated as abandoned. Returns the fd, or null if held. */
|
|
459
|
+
export function acquireLock(now = Date.now()) {
|
|
460
|
+
const file = lockPath();
|
|
461
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
462
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
463
|
+
try {
|
|
464
|
+
const fd = openSync(file, "wx", 0o600);
|
|
465
|
+
writeFileSync(fd, `${process.pid}\n`);
|
|
466
|
+
return fd;
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
if (error.code !== "EEXIST")
|
|
470
|
+
return null;
|
|
471
|
+
try {
|
|
472
|
+
if (now - statSync(file).mtimeMs < LOCK_STALE_MS)
|
|
473
|
+
return null;
|
|
474
|
+
unlinkSync(file);
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
export function releaseLock(fd) {
|
|
484
|
+
try {
|
|
485
|
+
closeSync(fd);
|
|
486
|
+
}
|
|
487
|
+
catch { }
|
|
488
|
+
try {
|
|
489
|
+
unlinkSync(lockPath());
|
|
490
|
+
}
|
|
491
|
+
catch { }
|
|
492
|
+
}
|
|
493
|
+
export function installedVersionOnDisk(root) {
|
|
494
|
+
try {
|
|
495
|
+
return JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version ?? null;
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Run the freshly installed CLI; it must start and report the expected version. */
|
|
502
|
+
export function verifyInstall(root, expected) {
|
|
503
|
+
const result = spawnSync(process.execPath, [path.join(root, "dist", "index.js"), "--version"], {
|
|
504
|
+
encoding: "utf8",
|
|
505
|
+
timeout: REFRESH_TIMEOUT_MS,
|
|
506
|
+
env: { ...process.env, OSD_NO_UPDATE_CHECK: "1" },
|
|
507
|
+
});
|
|
508
|
+
return result.status === 0 && result.stdout.trim() === expected;
|
|
509
|
+
}
|
|
510
|
+
export function npmGlobalRoot(run = runNpm) {
|
|
511
|
+
const result = run(["root", "-g"], REFRESH_TIMEOUT_MS);
|
|
512
|
+
if (result.error || result.status !== 0)
|
|
513
|
+
return null;
|
|
514
|
+
const root = result.stdout.trim();
|
|
515
|
+
return root || null;
|
|
516
|
+
}
|
|
517
|
+
function realpathOrSelf(p) {
|
|
518
|
+
try {
|
|
519
|
+
return realpathSync(p);
|
|
520
|
+
}
|
|
521
|
+
catch {
|
|
522
|
+
return p;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
export function isInGlobalRoot(root, globalRoot) {
|
|
526
|
+
const pkg = realpathOrSelf(root);
|
|
527
|
+
const glob = realpathOrSelf(globalRoot);
|
|
528
|
+
const rel = path.relative(glob, pkg);
|
|
529
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
530
|
+
}
|
|
531
|
+
/** Interactive installs stream npm's output to stderr so stdout stays clean; background ones discard it. */
|
|
532
|
+
export function installVersion(version, opts = {}) {
|
|
533
|
+
const result = spawnSync(npmCommand(), ["install", "-g", `${PACKAGE_NAME}@${version}`], {
|
|
534
|
+
stdio: opts.quiet ? "ignore" : ["ignore", 2, 2],
|
|
535
|
+
timeout: opts.timeoutMs,
|
|
536
|
+
env: npmEnv(),
|
|
537
|
+
});
|
|
538
|
+
if (result.error)
|
|
539
|
+
return { ok: false, status: null, error: result.error.message };
|
|
540
|
+
return { ok: result.status === 0, status: result.status };
|
|
541
|
+
}
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type LookupFn } from "./brand-catalog.js";
|
|
2
|
+
import { ExitCode } from "./exit-codes.js";
|
|
3
|
+
import type { SearchResultItem } from "./format.js";
|
|
4
|
+
/**
|
|
5
|
+
* Structural verification: a registry candidate is brand-endorsed iff
|
|
6
|
+
* it exactly matches one entry in the brand domain's own published catalog.
|
|
7
|
+
*
|
|
8
|
+
* The match is structural only. A "verified" verdict means the bytes agree,
|
|
9
|
+
* not that any signature or identity claim was checked (there is no
|
|
10
|
+
* cryptographic validation in v1).
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Marks the missing side of a field present on only one side of a diff.
|
|
14
|
+
* A unique symbol so no real JSON value can collide with it; rendered as the
|
|
15
|
+
* string "ABSENT" at output boundaries via renderDiffValue.
|
|
16
|
+
*/
|
|
17
|
+
export declare const ABSENT: unique symbol;
|
|
18
|
+
export type AbsentMarker = typeof ABSENT;
|
|
19
|
+
/** Maps the ABSENT sentinel to its wire string for human/--json output. */
|
|
20
|
+
export declare function renderDiffValue(value: unknown): unknown;
|
|
21
|
+
export interface DiffEntry {
|
|
22
|
+
path: string;
|
|
23
|
+
registryValue: unknown | AbsentMarker;
|
|
24
|
+
brandValue: unknown | AbsentMarker;
|
|
25
|
+
}
|
|
26
|
+
export type VerifyOutcome = {
|
|
27
|
+
kind: "verified";
|
|
28
|
+
catalogUrl: string;
|
|
29
|
+
} | {
|
|
30
|
+
kind: "mismatch";
|
|
31
|
+
catalogUrl: string;
|
|
32
|
+
diff: DiffEntry[];
|
|
33
|
+
} | {
|
|
34
|
+
kind: "noMatch";
|
|
35
|
+
catalogUrl: string;
|
|
36
|
+
} | {
|
|
37
|
+
kind: "unreachable";
|
|
38
|
+
message: string;
|
|
39
|
+
catalogUrl?: string;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "invalidCandidate";
|
|
42
|
+
message: string;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "malformedCatalog";
|
|
45
|
+
message: string;
|
|
46
|
+
} | {
|
|
47
|
+
kind: "unsupportedContractVersion";
|
|
48
|
+
contractVersion: string;
|
|
49
|
+
} | {
|
|
50
|
+
kind: "schemasMissing";
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Field-level structural diff between a registry candidate and a brand
|
|
54
|
+
* catalog entry. An empty diff means the entries match. Only the
|
|
55
|
+
* registry side is stripped of resolver annotations, and only for keys the
|
|
56
|
+
* brand entry does not itself carry (see ANNOTATION_KEYS). Arrays compare as
|
|
57
|
+
* multisets; objects compare key-order-free; no string normalization of any
|
|
58
|
+
* kind (a trailing slash is a mismatch).
|
|
59
|
+
*/
|
|
60
|
+
export declare function compareEntries(registryEntry: unknown, brandEntry: unknown): DiffEntry[];
|
|
61
|
+
export interface RunVerifyOptions {
|
|
62
|
+
/** A single catalog entry object (e.g. one item from `osd search --json`). */
|
|
63
|
+
candidate: unknown;
|
|
64
|
+
contractVersion: string;
|
|
65
|
+
/** Test seam: DNS resolution cannot be stubbed via vi.stubGlobal. */
|
|
66
|
+
lookup?: LookupFn;
|
|
67
|
+
}
|
|
68
|
+
/** Extracts the selected contract version's authoritative brand-domain field. */
|
|
69
|
+
export declare function extractBrandDomain(candidate: unknown, contractVersion: string): unknown;
|
|
70
|
+
/**
|
|
71
|
+
* Verifies one candidate against its brand domain's published catalog.
|
|
72
|
+
* Makes no trust decision: the outcome says whether the brand's own domain
|
|
73
|
+
* endorses the candidate structurally; what to do with that is the caller's.
|
|
74
|
+
*/
|
|
75
|
+
export declare function runVerify(options: RunVerifyOptions): Promise<VerifyOutcome>;
|
|
76
|
+
/**
|
|
77
|
+
* Annotates every search result with a `verification` object (attached to the
|
|
78
|
+
* result data itself, so both human and --json output carry it). Fetches one
|
|
79
|
+
* catalog per distinct (normalized) brandDomain, in parallel, and parses it
|
|
80
|
+
* once per domain. Never throws; the search command maps the worst verdict
|
|
81
|
+
* onto its exit code via exitCodeForVerification.
|
|
82
|
+
*/
|
|
83
|
+
export declare function verifySearchResults(results: SearchResultItem[], contractVersion: string, options?: {
|
|
84
|
+
lookup?: LookupFn;
|
|
85
|
+
}): Promise<void>;
|
|
86
|
+
/**
|
|
87
|
+
* Maps per-result verification annotations to the `search --verify` exit
|
|
88
|
+
* code: the worst verdict wins -- mismatch (6, definitive conflict) over
|
|
89
|
+
* no_match (5) over the inconclusive-or-broken verdicts unreachable, invalid
|
|
90
|
+
* and malformed (1). No results, or all verified, stays Success.
|
|
91
|
+
*/
|
|
92
|
+
export declare function exitCodeForVerification(results: SearchResultItem[]): ExitCode;
|