@bom0792/herdgate 0.9.36 → 0.9.38
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/.agents/skills/herdr/SKILL.md +100 -0
- package/DESIGN.md +28 -0
- package/README.md +55 -1
- package/package.json +2 -1
- package/plugin/herdr-plugin.toml +17 -0
- package/plugin/server/attachments.mjs +184 -0
- package/plugin/server/e2e.mjs +27 -0
- package/plugin/server/git-safe.mjs +126 -0
- package/plugin/server/index.mjs +317 -5
- package/plugin/server/mobile-tui-core.mjs +701 -41
- package/plugin/server/mobile-tui-stream.mjs +262 -3
- package/plugin/server/pi-receipt-gc.mjs +183 -0
- package/plugin/server/pi-receipt-search.mjs +217 -0
- package/plugin/server/pi-receipts.mjs +125 -13
- package/plugin/server/pi-transcript.mjs +217 -0
- package/plugin/server/pi-usage.mjs +84 -0
- package/plugin/server/pi-wake.mjs +319 -0
- package/plugin/server/pi-worker.d.mts +7 -0
- package/plugin/server/pi-worker.mjs +45 -4
- package/plugin/server/port-attr.mjs +172 -0
- package/plugin/server/sysmon.mjs +212 -0
- package/plugin/server/wake-event.mjs +255 -0
- package/src/agent/index.ts +4 -2
- package/src/agent/qr.ts +70 -0
- package/src/cloud/gateway.ts +5 -1
- package/src/cloud/sshd.ts +5 -8
- package/src/host/main.ts +14 -1
- package/src/web/app.css +379 -0
- package/src/web/app.js +1557 -5
- package/src/web/e2e.js +29 -2
- package/src/web/index.html +1 -0
- package/windows/npm-update.mjs +261 -11
- package/windows/update-policy.mjs +98 -0
package/src/web/e2e.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* herdgate E2E payloads — Noise_XX over the opaque payload channel.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* drift). Everything
|
|
4
|
+
* One canonical implementation, two runtimes: this file is copied verbatim to
|
|
5
|
+
* `src/web/e2e.js` for the PWA (a test asserts the two never drift). Everything
|
|
6
6
|
* runs on WebCrypto (`globalThis.crypto.subtle` — Node ≥ 20 exposes the same
|
|
7
7
|
* object globally), so the plugin and the browser execute identical logic.
|
|
8
8
|
*
|
|
@@ -22,6 +22,21 @@ export const NOISE_NAME = "Noise_XX_P256_AESGCM_SHA256";
|
|
|
22
22
|
export const KEY_LEN = 32;
|
|
23
23
|
export const PUB_LEN = 65; // uncompressed P-256 point: 0x04 ‖ X ‖ Y
|
|
24
24
|
|
|
25
|
+
/** Session lifetime (Paseo lesson: handshake lifetime). A transport key that lives
|
|
26
|
+
* forever erodes forward secrecy — compromising it exposes the WHOLE session since
|
|
27
|
+
* the handshake. Rotation fences exposure to the slice since the last handshake.
|
|
28
|
+
* Bounds: messages per direction (far under nonce exhaustion at 2^32) or wall time,
|
|
29
|
+
* whichever comes first. The device initiates; the host's `e2e.init` handler swaps
|
|
30
|
+
* the session in place, so rotation is just a fresh handshake. */
|
|
31
|
+
export const REKEY_AFTER_MESSAGES = 2 ** 24;
|
|
32
|
+
export const REKEY_AFTER_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
/** True when a READY channel has reached either lifetime bound. */
|
|
35
|
+
export function needsRekey(ch, now = Date.now()) {
|
|
36
|
+
if (!ch?.ready()) return false;
|
|
37
|
+
return ch.usage() >= REKEY_AFTER_MESSAGES || now - ch.handshakeAt >= REKEY_AFTER_MS;
|
|
38
|
+
}
|
|
39
|
+
|
|
25
40
|
// ---- byte helpers (kept dependency-free; typed arrays only) ----------------
|
|
26
41
|
|
|
27
42
|
export function b64e(u8) {
|
|
@@ -189,6 +204,7 @@ export class DeviceChannel {
|
|
|
189
204
|
sendCs = null;
|
|
190
205
|
recvCs = null;
|
|
191
206
|
hostFingerprint = null;
|
|
207
|
+
handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
|
|
192
208
|
constructor(self) {
|
|
193
209
|
this.#self = self;
|
|
194
210
|
}
|
|
@@ -218,12 +234,17 @@ export class DeviceChannel {
|
|
|
218
234
|
const [c1, c2] = await this.#hs.split();
|
|
219
235
|
this.sendCs = c1; // device → host
|
|
220
236
|
this.recvCs = c2; // host → device
|
|
237
|
+
this.handshakeAt = Date.now();
|
|
221
238
|
this.#e = null;
|
|
222
239
|
return { c: b64e(c) };
|
|
223
240
|
}
|
|
224
241
|
ready() {
|
|
225
242
|
return Boolean(this.sendCs && this.recvCs);
|
|
226
243
|
}
|
|
244
|
+
/** Messages carried under the current keys (max of both directions). */
|
|
245
|
+
usage() {
|
|
246
|
+
return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
|
|
247
|
+
}
|
|
227
248
|
async send(obj) {
|
|
228
249
|
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
229
250
|
return { op: "e2e", n, c: b64e(ct) };
|
|
@@ -241,6 +262,7 @@ export class HostChannel {
|
|
|
241
262
|
sendCs = null;
|
|
242
263
|
recvCs = null;
|
|
243
264
|
deviceFingerprint = null;
|
|
265
|
+
handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
|
|
244
266
|
constructor(self) {
|
|
245
267
|
this.#self = self;
|
|
246
268
|
}
|
|
@@ -266,11 +288,16 @@ export class HostChannel {
|
|
|
266
288
|
const [c1, c2] = await this.#hs.split();
|
|
267
289
|
this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
|
|
268
290
|
this.sendCs = c2; // host → device
|
|
291
|
+
this.handshakeAt = Date.now();
|
|
269
292
|
this.#e = null;
|
|
270
293
|
}
|
|
271
294
|
ready() {
|
|
272
295
|
return Boolean(this.sendCs && this.recvCs);
|
|
273
296
|
}
|
|
297
|
+
/** Messages carried under the current keys (max of both directions). */
|
|
298
|
+
usage() {
|
|
299
|
+
return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
|
|
300
|
+
}
|
|
274
301
|
async send(obj) {
|
|
275
302
|
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
276
303
|
return { op: "e2e", n, c: b64e(ct) };
|
package/src/web/index.html
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
<header id="bar">
|
|
19
19
|
<strong>herdgate</strong>
|
|
20
20
|
<span id="status" class="pill" role="status" aria-live="polite">offline</span>
|
|
21
|
+
<button id="cmdk-open" type="button" title="Jump — ⌘K / Ctrl-K">⌘K / Ctrl-K</button>
|
|
21
22
|
<button id="menu" type="button" aria-label="Settings">⋯</button>
|
|
22
23
|
</header>
|
|
23
24
|
|
package/windows/npm-update.mjs
CHANGED
|
@@ -1,16 +1,48 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
// npm staging helper + safe self-updater for the Herdgate per-user CLI.
|
|
2
|
+
//
|
|
3
|
+
// withLatest(run) keeps its original contract for the existing callers
|
|
4
|
+
// (windows/cli.mjs "update" and bin/herdgate.mjs "update"): stage the latest
|
|
5
|
+
// @bom0792/herdgate release with the npm bundled beside the same Node, without
|
|
6
|
+
// running install hooks, and hand the staged package directory to run().
|
|
7
|
+
//
|
|
8
|
+
// Run directly (node npm-update.mjs) this module is the safe updater, applying
|
|
9
|
+
// the lessons from herdr-updater:
|
|
10
|
+
// - before ANY change the installed/latest relation is computed with
|
|
11
|
+
// ./update-policy.mjs; "unknown" (unparsable versions) is an error state
|
|
12
|
+
// that exits 1 — it is never treated as "current" and never updated past;
|
|
13
|
+
// - the default policy is "notify": print installed/latest/relation/plan,
|
|
14
|
+
// run no install and write no file except the append-only history
|
|
15
|
+
// "checked" line;
|
|
16
|
+
// - HERDGATE_UPDATE_POLICY=auto may only apply when the installed version is
|
|
17
|
+
// strictly "behind" (npm source), or when the installed commit is an
|
|
18
|
+
// ancestor of the upstream ref found via git merge-base --is-ancestor (git
|
|
19
|
+
// source); same/ahead/diverged/pinned/linked states are held with a reason;
|
|
20
|
+
// - every real apply appends an "updated" history line (from -> to) and keeps
|
|
21
|
+
// the previous install behaviour (staged npm install with --ignore-scripts,
|
|
22
|
+
// then the staged Windows CLI performs the switch).
|
|
23
|
+
import { spawnSync } from "node:child_process";
|
|
24
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import { dirname, join, resolve } from "node:path";
|
|
27
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
28
|
+
import { appendHistory, policyFromEnv, relation } from "./update-policy.mjs";
|
|
6
29
|
|
|
7
|
-
|
|
30
|
+
const PACKAGE = "@bom0792/herdgate";
|
|
31
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
32
|
+
|
|
33
|
+
/** npm-cli.js shipped beside the current Node, if any (same candidates as before). */
|
|
34
|
+
function bundledNpmCli() {
|
|
8
35
|
const nodeDir = dirname(process.execPath);
|
|
9
|
-
|
|
10
|
-
join(nodeDir,
|
|
11
|
-
...(process.platform ===
|
|
12
|
-
...(nodeDir ===
|
|
13
|
-
].find(existsSync);
|
|
36
|
+
return [
|
|
37
|
+
join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js"),
|
|
38
|
+
...(process.platform === "win32" ? [] : [join(nodeDir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")]),
|
|
39
|
+
...(nodeDir === "/usr/bin" ? ["/usr/share/nodejs/npm/bin/npm-cli.js"] : []),
|
|
40
|
+
].find(existsSync) ?? null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Fetch the npm release using npm bundled with the same Node, without running install hooks.
|
|
44
|
+
export function withLatest(run) {
|
|
45
|
+
const npm = bundledNpmCli();
|
|
14
46
|
if (!npm) throw new Error('npm was not found beside Node; use a Node 22+ distribution with npm');
|
|
15
47
|
const work = mkdtempSync(join(tmpdir(), 'herdgate-update-'));
|
|
16
48
|
try {
|
|
@@ -24,3 +56,221 @@ export function withLatest(run) {
|
|
|
24
56
|
rmSync(work, { recursive: true, force: true, maxRetries: 3 });
|
|
25
57
|
}
|
|
26
58
|
}
|
|
59
|
+
|
|
60
|
+
// ---- safe updater (direct run) ----
|
|
61
|
+
|
|
62
|
+
/** Run npm, preferring an npm from PATH (where tests stub it); the bundled npm-cli.js is the fallback. */
|
|
63
|
+
function npmRun(args, { timeout = 120_000 } = {}) {
|
|
64
|
+
if (process.platform === "win32") {
|
|
65
|
+
const command = ["npm", ...args]
|
|
66
|
+
.map((arg) => (/[ \t"^&|<>()!]/.test(arg) ? `"${arg.replaceAll('"', '""')}"` : arg))
|
|
67
|
+
.join(" ");
|
|
68
|
+
return spawnSync(command, { encoding: "utf8", shell: true, windowsHide: true, timeout });
|
|
69
|
+
}
|
|
70
|
+
const fromPath = spawnSync("npm", args, { encoding: "utf8", shell: false, windowsHide: true, timeout });
|
|
71
|
+
if (!fromPath.error || fromPath.error.code !== "ENOENT") return fromPath;
|
|
72
|
+
const bundled = bundledNpmCli();
|
|
73
|
+
return bundled
|
|
74
|
+
? spawnSync(process.execPath, [bundled, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout })
|
|
75
|
+
: fromPath;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Latest published version, or null when npm cannot answer. */
|
|
79
|
+
function npmLatestVersion(pkg) {
|
|
80
|
+
const result = npmRun(["view", pkg, "version"], { timeout: 30_000 });
|
|
81
|
+
if (result.error || result.status !== 0) return null;
|
|
82
|
+
const version = (result.stdout ?? "").trim().split("\n").pop()?.trim();
|
|
83
|
+
return version || null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Version of the package this module was shipped in, or null (never guessed). */
|
|
87
|
+
function installedPackageVersion() {
|
|
88
|
+
try {
|
|
89
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
|
90
|
+
return typeof pkg.version === "string" ? pkg.version : null;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Stage the latest release exactly like withLatest, but through the resolved npm. */
|
|
97
|
+
function stageLatest() {
|
|
98
|
+
const work = mkdtempSync(join(tmpdir(), "herdgate-update-"));
|
|
99
|
+
try {
|
|
100
|
+
const result = npmRun(["install", "--prefix", work, "--global=false", "--no-save", "--package-lock=false",
|
|
101
|
+
"--ignore-scripts", "--no-audit", "--no-fund", "--prefer-online", `${PACKAGE}@latest`]);
|
|
102
|
+
if (result.error) throw result.error;
|
|
103
|
+
if (result.status !== 0) throw new Error(`could not download ${PACKAGE} from npm; nothing was changed`);
|
|
104
|
+
return work;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
rmSync(work, { recursive: true, force: true, maxRetries: 3 });
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---- git source ----
|
|
112
|
+
|
|
113
|
+
function git(checkout, args) {
|
|
114
|
+
return spawnSync("git", ["-C", checkout, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout: 30_000 });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function gitText(checkout, args) {
|
|
118
|
+
const result = git(checkout, args);
|
|
119
|
+
return result.status === 0 ? result.stdout.trim() : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Classify a checkout: behind/ahead/same by ancestry, pinned (detached HEAD) or linked (no upstream). */
|
|
123
|
+
function gitRelation(checkout) {
|
|
124
|
+
const head = gitText(checkout, ["rev-parse", "HEAD"]);
|
|
125
|
+
if (!head) return { relation: "unknown", head: null, upstream: null, upstreamSha: null };
|
|
126
|
+
const branch = gitText(checkout, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
127
|
+
const detached = !branch || branch === "HEAD";
|
|
128
|
+
const upstream = detached ? null : gitText(checkout, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
|
|
129
|
+
const upstreamSha = upstream ? gitText(checkout, ["rev-parse", upstream]) : null;
|
|
130
|
+
if (!upstream || !upstreamSha) {
|
|
131
|
+
return { relation: detached ? "pinned" : "linked", head, upstream, upstreamSha: null };
|
|
132
|
+
}
|
|
133
|
+
if (head === upstreamSha) return { relation: "same", head, upstream, upstreamSha };
|
|
134
|
+
// Only an installed ref that is an ancestor of upstream may be fast-forwarded.
|
|
135
|
+
if (git(checkout, ["merge-base", "--is-ancestor", head, upstreamSha]).status === 0) {
|
|
136
|
+
return { relation: "behind", head, upstream, upstreamSha };
|
|
137
|
+
}
|
|
138
|
+
if (git(checkout, ["merge-base", "--is-ancestor", upstreamSha, head]).status === 0) {
|
|
139
|
+
return { relation: "ahead", head, upstream, upstreamSha };
|
|
140
|
+
}
|
|
141
|
+
return { relation: "diverged", head, upstream, upstreamSha };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Nearest enclosing git work tree, or null (an npm-installed package has none). */
|
|
145
|
+
function findCheckout(start) {
|
|
146
|
+
for (let dir = resolve(start);;) {
|
|
147
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
148
|
+
const parent = dirname(dir);
|
|
149
|
+
if (parent === dir) return null;
|
|
150
|
+
dir = parent;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---- reporting and policies ----
|
|
155
|
+
|
|
156
|
+
function fail(message) {
|
|
157
|
+
console.error(`herdgate update: ${message}`);
|
|
158
|
+
process.exitCode = 1;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Append one history line; on failure report and stop (return null). */
|
|
162
|
+
function record(stateDir, entry) {
|
|
163
|
+
try {
|
|
164
|
+
return appendHistory(stateDir, entry);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
fail(`could not append the update history: ${error instanceof Error ? error.message : String(error)}`);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function updateFromNpm(policy, stateDir, env) {
|
|
172
|
+
const pkg = env.HERDGATE_UPDATE_PACKAGE || PACKAGE;
|
|
173
|
+
const installed = env.HERDGATE_UPDATE_INSTALLED || installedPackageVersion();
|
|
174
|
+
const latest = env.HERDGATE_UPDATE_LATEST || npmLatestVersion(pkg);
|
|
175
|
+
const rel = relation(installed, latest);
|
|
176
|
+
console.log(`source: npm package ${pkg}`);
|
|
177
|
+
console.log(`policy: ${policy}`);
|
|
178
|
+
console.log(`installed: ${installed ?? "<unknown>"}`);
|
|
179
|
+
console.log(`latest: ${latest ?? "<unknown>"}`);
|
|
180
|
+
console.log(`relation: ${rel}`);
|
|
181
|
+
if (rel === "unknown") {
|
|
182
|
+
return fail(`cannot compare installed "${installed ?? ""}" with latest "${latest ?? ""}": unparsable version — refusing to guess or update`);
|
|
183
|
+
}
|
|
184
|
+
if (policy === "notify") {
|
|
185
|
+
console.log(rel === "behind"
|
|
186
|
+
? `plan: stage ${pkg}@${latest} with npm --ignore-scripts and switch the per-user CLI; set HERDGATE_UPDATE_POLICY=auto to apply`
|
|
187
|
+
: `plan: nothing to apply (relation ${rel})`);
|
|
188
|
+
if (!record(stateDir, { from: installed, to: latest, relation: rel, action: "checked" })) return;
|
|
189
|
+
console.log(`history: ${join(stateDir, "update-history.jsonl")} (append-only)`);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (rel !== "behind") {
|
|
193
|
+
console.log("held — applying would be a downgrade/no-op");
|
|
194
|
+
record(stateDir, { from: installed, to: latest, relation: rel, action: "held" });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
let work;
|
|
198
|
+
try {
|
|
199
|
+
work = stageLatest();
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return fail(error instanceof Error ? error.message : String(error));
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
if (!record(stateDir, { from: installed, to: latest, relation: rel, action: "updated" })) return;
|
|
205
|
+
console.log(`updated: ${installed} -> ${latest}`);
|
|
206
|
+
// Keep the previous apply behaviour: the staged Windows CLI switches the publisher.
|
|
207
|
+
const stagedCli = join(work, "node_modules", "@bom0792", "herdgate", "bin", "herdgate.mjs");
|
|
208
|
+
if (process.platform === "win32" && existsSync(stagedCli)) {
|
|
209
|
+
const switched = spawnSync(process.execPath, [stagedCli, "tui", "update"], { stdio: "inherit", shell: false, windowsHide: true, timeout: 120_000 });
|
|
210
|
+
if (switched.error) throw switched.error;
|
|
211
|
+
if (switched.status) process.exitCode = switched.status;
|
|
212
|
+
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
215
|
+
} finally {
|
|
216
|
+
rmSync(work, { recursive: true, force: true, maxRetries: 3 });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function updateFromGit(policy, stateDir, checkout) {
|
|
221
|
+
const rel = gitRelation(checkout);
|
|
222
|
+
console.log(`source: git checkout ${checkout}`);
|
|
223
|
+
console.log(`policy: ${policy}`);
|
|
224
|
+
console.log(`installed: ${rel.head ?? "<unknown>"}${rel.head ? " (HEAD)" : ""}`);
|
|
225
|
+
console.log(`upstream: ${rel.upstream ? `${rel.upstream}${rel.upstreamSha ? ` (${rel.upstreamSha})` : ""}` : "<none>"}`);
|
|
226
|
+
console.log(`relation: ${rel.relation}`);
|
|
227
|
+
if (rel.relation === "unknown") {
|
|
228
|
+
return fail(`cannot determine the state of the git checkout at ${checkout} — refusing to guess or update`);
|
|
229
|
+
}
|
|
230
|
+
if (policy === "notify") {
|
|
231
|
+
console.log(rel.relation === "behind"
|
|
232
|
+
? `plan: fast-forward HEAD to ${rel.upstream} (${rel.upstreamSha}); set HERDGATE_UPDATE_POLICY=auto to apply`
|
|
233
|
+
: `plan: nothing to apply (relation ${rel.relation})`);
|
|
234
|
+
if (!record(stateDir, { from: rel.head, to: rel.upstreamSha, relation: rel.relation, action: "checked" })) return;
|
|
235
|
+
console.log(`history: ${join(stateDir, "update-history.jsonl")} (append-only)`);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (rel.relation !== "behind") {
|
|
239
|
+
const reason = rel.relation === "ahead" ? "applying would be a downgrade/no-op"
|
|
240
|
+
: rel.relation === "same" ? "applying would be a no-op"
|
|
241
|
+
: rel.relation === "diverged" ? "the checkout diverged from upstream; only a fast-forward is safe"
|
|
242
|
+
: rel.relation === "pinned" ? "the checkout is pinned to a detached ref"
|
|
243
|
+
: "the branch has no upstream to fast-forward to";
|
|
244
|
+
console.log(`held — ${reason}`);
|
|
245
|
+
record(stateDir, { from: rel.head, to: rel.upstreamSha, relation: rel.relation, action: "held" });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const merged = git(checkout, ["merge", "--ff-only", rel.upstreamSha]);
|
|
249
|
+
if (merged.error || merged.status !== 0) {
|
|
250
|
+
return fail(`fast-forwarding to ${rel.upstream} failed; the checkout was not changed${merged.stderr ? `: ${merged.stderr.trim()}` : ""}`);
|
|
251
|
+
}
|
|
252
|
+
const applied = gitText(checkout, ["rev-parse", "HEAD"]) ?? rel.upstreamSha;
|
|
253
|
+
if (!record(stateDir, { from: rel.head, to: applied, relation: "behind", action: "updated" })) return;
|
|
254
|
+
console.log(`updated: ${rel.head} -> ${applied}`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function main() {
|
|
258
|
+
const env = process.env;
|
|
259
|
+
const policy = policyFromEnv(env);
|
|
260
|
+
const stateDir = env.HERDGATE_UPDATE_STATE_DIR || (env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Herdgate", "cli") : null);
|
|
261
|
+
if (!stateDir) {
|
|
262
|
+
return fail("nowhere to record the update history; set HERDGATE_UPDATE_STATE_DIR (or LOCALAPPDATA)");
|
|
263
|
+
}
|
|
264
|
+
const checkout = env.HERDGATE_UPDATE_CHECKOUT || findCheckout(here);
|
|
265
|
+
return checkout ? updateFromGit(policy, stateDir, checkout) : updateFromNpm(policy, stateDir, env);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Only act when executed directly; importing callers keep using withLatest unchanged.
|
|
269
|
+
const executedDirectly = (() => {
|
|
270
|
+
try {
|
|
271
|
+
return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
})();
|
|
276
|
+
if (executedDirectly) main();
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Safe update policy primitives shared by the Herdgate updaters.
|
|
2
|
+
//
|
|
3
|
+
// Lessons baked in from herdr-updater:
|
|
4
|
+
// - never guess a version: anything that does not parse as strict semver is
|
|
5
|
+
// null, and a failed comparison is the ERROR state "unknown" — it is never
|
|
6
|
+
// silently treated as "current" or "up to date";
|
|
7
|
+
// - order only by semver precedence (0.10.0 > 0.9.0 > 0.9.0-rc.1), never by
|
|
8
|
+
// string or numeric inequality;
|
|
9
|
+
// - update decisions are recorded in an append-only JSONL history.
|
|
10
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
11
|
+
import { hostname } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
export const HISTORY_FILE = "update-history.jsonl";
|
|
15
|
+
|
|
16
|
+
// Official semver grammar; build metadata is allowed but ignored for precedence.
|
|
17
|
+
const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
|
|
18
|
+
const NUMERIC = /^\d+$/;
|
|
19
|
+
|
|
20
|
+
/** Parse a strict semver string into precedence parts; anything else is null (never a guess). */
|
|
21
|
+
export function parseVersion(value) {
|
|
22
|
+
if (typeof value !== "string") return null;
|
|
23
|
+
const match = VERSION.exec(value.trim());
|
|
24
|
+
if (!match) return null;
|
|
25
|
+
return {
|
|
26
|
+
major: Number(match[1]),
|
|
27
|
+
minor: Number(match[2]),
|
|
28
|
+
patch: Number(match[3]),
|
|
29
|
+
prerelease: match[4] ? match[4].split(".") : [],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Compare two versions by semver precedence: -1 | 0 | 1, or null when either side does not parse. */
|
|
34
|
+
export function compareVersions(a, b) {
|
|
35
|
+
const left = parseVersion(a);
|
|
36
|
+
const right = parseVersion(b);
|
|
37
|
+
if (!left || !right) return null;
|
|
38
|
+
for (const part of ["major", "minor", "patch"]) {
|
|
39
|
+
if (left[part] !== right[part]) return left[part] < right[part] ? -1 : 1;
|
|
40
|
+
}
|
|
41
|
+
const ra = left.prerelease;
|
|
42
|
+
const rb = right.prerelease;
|
|
43
|
+
if (!ra.length || !rb.length) {
|
|
44
|
+
if (ra.length === rb.length) return 0;
|
|
45
|
+
// A prerelease sorts below the plain release: 0.9.0 > 0.9.0-rc.1.
|
|
46
|
+
return ra.length ? -1 : 1;
|
|
47
|
+
}
|
|
48
|
+
const shared = Math.min(ra.length, rb.length);
|
|
49
|
+
for (let i = 0; i < shared; i++) {
|
|
50
|
+
const x = ra[i];
|
|
51
|
+
const y = rb[i];
|
|
52
|
+
const xn = NUMERIC.test(x);
|
|
53
|
+
const yn = NUMERIC.test(y);
|
|
54
|
+
if (xn && yn) {
|
|
55
|
+
const order = Number(x) - Number(y);
|
|
56
|
+
if (order) return order < 0 ? -1 : 1;
|
|
57
|
+
} else if (xn !== yn) {
|
|
58
|
+
// Numeric identifiers sort below alphanumeric ones.
|
|
59
|
+
return xn ? -1 : 1;
|
|
60
|
+
} else if (x !== y) {
|
|
61
|
+
return x < y ? -1 : 1;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (ra.length === rb.length) return 0;
|
|
65
|
+
// A larger set of pre-release fields has higher precedence: alpha < alpha.1.
|
|
66
|
+
return ra.length < rb.length ? -1 : 1;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** installed vs latest: same | behind | ahead, or unknown (parse failed — an error state, not "current"). */
|
|
70
|
+
export function relation(installed, latest) {
|
|
71
|
+
const order = compareVersions(installed, latest);
|
|
72
|
+
if (order === null) return "unknown";
|
|
73
|
+
return order < 0 ? "behind" : order > 0 ? "ahead" : "same";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** HERDGATE_UPDATE_POLICY: only the exact value "auto" opts in; anything else fails closed to notify. */
|
|
77
|
+
export function policyFromEnv(env) {
|
|
78
|
+
return env && env.HERDGATE_UPDATE_POLICY === "auto" ? "auto" : "notify";
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Append one decision record as JSONL; the file is only ever appended to, never rewritten. */
|
|
82
|
+
export function appendHistory(stateDir, record) {
|
|
83
|
+
if (!stateDir || typeof stateDir !== "string") throw new TypeError("appendHistory requires a state directory");
|
|
84
|
+
if (!record || typeof record !== "object") throw new TypeError("appendHistory requires a record");
|
|
85
|
+
mkdirSync(stateDir, { recursive: true });
|
|
86
|
+
const entry = {
|
|
87
|
+
at: typeof record.at === "string" && record.at ? record.at : new Date().toISOString(),
|
|
88
|
+
from: record.from ?? null,
|
|
89
|
+
to: record.to ?? null,
|
|
90
|
+
relation: record.relation ?? null,
|
|
91
|
+
action: record.action ?? null,
|
|
92
|
+
};
|
|
93
|
+
const host = record.host ?? hostname();
|
|
94
|
+
if (host) entry.host = host;
|
|
95
|
+
// Flag "a" positions at the end and never truncates an existing history.
|
|
96
|
+
appendFileSync(join(stateDir, HISTORY_FILE), JSON.stringify(entry) + "\n", { flag: "a" });
|
|
97
|
+
return entry;
|
|
98
|
+
}
|