@botiverse/stamp-cli 0.3.14 → 0.4.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/lib/repo/ssh.mjs DELETED
@@ -1,326 +0,0 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { dirname, join, resolve } from "node:path";
4
- import { spawnSync } from "node:child_process";
5
-
6
- // `stamp repo clone` must not ask a human to export GIT_SSH_COMMAND: after
7
- // `stamp key enroll` the CLI already knows which key it enrolled and the
8
- // gateway already publishes its host key over HTTPS
9
- // (/.well-known/ssh-known-hosts, task #463). So the clone carries both: the
10
- // private key as `-i`, and the published line as the ONLY trusted host key
11
- // (StrictHostKeyChecking=yes + IdentitiesOnly=yes), which is a pin, not TOFU.
12
-
13
- // defaultIdentityPath is where `stamp key enroll` looks for the public key; the
14
- // private half is the same path without `.pub`.
15
- // An agent's default key is its own (artin 09-27), in its state directory,
16
- // never the ~/.ssh/id_ed25519 every agent on a machine user shares; a human
17
- // keeps the conventional path.
18
- export function defaultIdentityPath(env) {
19
- const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
20
- return agentDir ? join(agentDir, "ssh", "id_ed25519") : join(homedir(), ".ssh", "id_ed25519");
21
- }
22
-
23
- // resolveIdentity picks the private key in this order and says which source
24
- // won: an explicit --identity, the STAMP_SSH_IDENTITY override, the key
25
- // recorded by `stamp key enroll` for this instance (task #514), the default
26
- // path. No source scans a directory.
27
- export function resolveIdentity(env, flagValue, recorded) {
28
- const fromFlag = String(flagValue ?? "").trim();
29
- if (fromFlag) return { identityPath: fromFlag, source: "flag" };
30
- const fromEnv = String(env?.STAMP_SSH_IDENTITY ?? "").trim();
31
- if (fromEnv) return { identityPath: fromEnv, source: "env" };
32
- const fromRecord = String(recorded?.identityPath ?? "").trim();
33
- if (fromRecord) return { identityPath: fromRecord, source: "enrolled" };
34
- return { identityPath: defaultIdentityPath(env), source: "default" };
35
- }
36
-
37
- export function resolveIdentityPath(env, flagValue, recorded) {
38
- return resolveIdentity(env, flagValue, recorded).identityPath;
39
- }
40
-
41
- // defaultKnownHostsPath is one stable file for every Stamp instance (a
42
- // known_hosts file holds many lines); lines are merged per host pattern below.
43
- export function resolveKnownHostsPath(env, flagValue) {
44
- const fromFlag = String(flagValue ?? "").trim();
45
- if (fromFlag) return fromFlag;
46
- const fromEnv = String(env?.STAMP_KNOWN_HOSTS ?? "").trim();
47
- if (fromEnv) return fromEnv;
48
- const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
49
- return agentDir ? join(agentDir, "known_hosts") : join(homedir(), ".stamp", "known_hosts");
50
- }
51
-
52
- function shellQuote(value) {
53
- const s = String(value);
54
- if (s === "" || /[^A-Za-z0-9._@%+,:=\/-]/.test(s)) {
55
- return `'${s.replaceAll("'", `'\\''`)}'`;
56
- }
57
- return s;
58
- }
59
-
60
- // sshCommandFor is the value git needs (GIT_SSH_COMMAND / core.sshCommand). It
61
- // names the identity and the pinned host key file explicitly, and never falls
62
- // back to ~/.ssh/known_hosts or to the agent's other identities.
63
- export function sshCommandFor({ identityPath, knownHostsPath }) {
64
- return [
65
- "ssh",
66
- "-i", shellQuote(identityPath),
67
- "-o", "IdentitiesOnly=yes",
68
- "-o", `UserKnownHostsFile=${shellQuote(knownHostsPath)}`,
69
- "-o", "StrictHostKeyChecking=yes",
70
- ].join(" ");
71
- }
72
-
73
- // parseStampSshCommand is the inverse of sshCommandFor: it reads back the
74
- // identity and known_hosts paths from a core.sshCommand Stamp wrote, undoing
75
- // shellQuote ('…' runs with '\'' for a quote). Anything that is not that shape
76
- // — another program, a double quote, no `-i` or no UserKnownHostsFile= —
77
- // returns null: the caller only speaks about commands Stamp itself wrote.
78
- export function parseStampSshCommand(command) {
79
- const tokens = shellWords(String(command ?? "").trim());
80
- if (!tokens || tokens[0] !== "ssh") return null;
81
- let identityPath = null;
82
- let knownHostsPath = null;
83
- for (let i = 1; i < tokens.length; i++) {
84
- if (tokens[i] === "-i" && i + 1 < tokens.length) identityPath = tokens[++i];
85
- else if (tokens[i] === "-o" && i + 1 < tokens.length) {
86
- const option = tokens[++i];
87
- if (option.startsWith("UserKnownHostsFile=")) knownHostsPath = option.slice("UserKnownHostsFile=".length);
88
- }
89
- }
90
- if (!identityPath || !knownHostsPath) return null;
91
- return { identityPath, knownHostsPath };
92
- }
93
-
94
- // shellWords splits the subset of sh syntax shellQuote produces: bare words,
95
- // single-quoted runs and backslash escapes outside quotes. Anything else sh
96
- // would treat specially returns null rather than a guess.
97
- function shellWords(text) {
98
- const words = [];
99
- let word = null;
100
- for (let i = 0; i < text.length; i++) {
101
- const c = text[i];
102
- if (c === " " || c === "\t") {
103
- if (word !== null) words.push(word);
104
- word = null;
105
- } else if (c === "'") {
106
- const end = text.indexOf("'", i + 1);
107
- if (end < 0) return null;
108
- word = (word ?? "") + text.slice(i + 1, end);
109
- i = end;
110
- } else if (c === "\\") {
111
- if (i + 1 >= text.length) return null;
112
- word = (word ?? "") + text[++i];
113
- } else if (/["`$;&|<>()\n]/.test(c)) {
114
- return null;
115
- } else {
116
- word = (word ?? "") + c;
117
- }
118
- }
119
- if (word !== null) words.push(word);
120
- return words;
121
- }
122
-
123
- // staleStampSshPath answers, for the checkout the CLI is standing in, "does
124
- // its Stamp-written core.sshCommand name a file this machine does not have?"
125
- // (a checkout moved from another machine keeps the old paths, and nothing
126
- // notices until `git push` fails with an opaque ssh error). It returns the
127
- // first missing path, or null.
128
- //
129
- // Cost: outside a git work tree nothing runs at all (the `.git` lookup is a
130
- // few stat calls); inside one it is exactly one `git config` call. Every
131
- // failure is silence: this is a hint, never a reason for a command to fail.
132
- export function staleStampSshPath({ cwd, env, execImpl = defaultProbeExec, exists = existsSync }) {
133
- try {
134
- const top = gitWorkTreeTop(cwd, env);
135
- if (!top) return null;
136
- const got = execImpl("git", ["config", "--local", "--get", "core.sshCommand"], cwd);
137
- if (got.status !== 0) return null;
138
- const command = got.stdout.trim();
139
- if (!/^ssh\s/.test(command) || !/(^|\s)-i\s/.test(command) || !command.includes("UserKnownHostsFile=")) return null;
140
- const parsed = parseStampSshCommand(command);
141
- if (!parsed) return null;
142
- for (const path of [parsed.identityPath, parsed.knownHostsPath]) {
143
- const absolute = path.startsWith("~/") ? join(homedir(), path.slice(2)) : resolve(top, path);
144
- if (!exists(absolute)) return path;
145
- }
146
- return null;
147
- } catch {
148
- return null;
149
- }
150
- }
151
-
152
- // gitWorkTreeTop finds the enclosing work tree without a subprocess: the
153
- // nearest directory holding a `.git` entry (a directory, or the file a linked
154
- // worktree or submodule uses). GIT_DIR in the environment also counts.
155
- function gitWorkTreeTop(cwd, env) {
156
- if (String(env?.GIT_DIR ?? "").trim()) return resolve(cwd);
157
- let dir = resolve(cwd);
158
- for (;;) {
159
- if (existsSync(join(dir, ".git"))) return dir;
160
- const parent = dirname(dir);
161
- if (parent === dir) return null;
162
- dir = parent;
163
- }
164
- }
165
-
166
- const KNOWN_HOSTS_KEY_TYPE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)$/;
167
- const KNOWN_HOSTS_PATTERN = /^(\[[^\]:]+]:\d{1,5}|[A-Za-z0-9][A-Za-z0-9.-]*)$/;
168
-
169
- // parseKnownHostsLine accepts exactly the one-line c2sp form the gateway
170
- // publishes and rejects anything else: pinning a malformed line would either
171
- // fail every connection or silently trust the wrong pattern.
172
- export function parseKnownHostsLine(text) {
173
- const line = String(text ?? "").trim();
174
- if (!line || line.includes("\n")) return null;
175
- const [pattern, keyType, base64] = line.split(/\s+/);
176
- if (!pattern || !keyType || !base64) return null;
177
- if (!KNOWN_HOSTS_PATTERN.test(pattern) || !KNOWN_HOSTS_KEY_TYPE.test(keyType)) return null;
178
- if (!/^[A-Za-z0-9+/]+={0,3}$/.test(base64) || base64.length < 40) return null;
179
- return { pattern, line };
180
- }
181
-
182
- // writePinnedKnownHosts merges one line into the known_hosts file, replacing any
183
- // earlier line for the same pattern so a rotated host key is superseded rather
184
- // than left to collide (two lines for one pattern make ssh refuse the host).
185
- export function writePinnedKnownHosts(path, pattern, line) {
186
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
187
- const kept = existing
188
- .split("\n")
189
- .filter((l) => l.trim() !== "" && l.trim().split(/\s+/)[0] !== pattern);
190
- kept.push(line);
191
- mkdirSync(dirname(path), { recursive: true });
192
- writeFileSync(path, `${kept.join("\n")}\n`, { mode: 0o600 });
193
- chmodSync(path, 0o600);
194
- }
195
-
196
- // fetchPublishedKnownHosts reads the host key from the instance itself over
197
- // HTTPS — a channel independent of the SSH connection — so the pin is not
198
- // first-use. "Not available here" (404) is reported, never substituted with a
199
- // keyscan of the very connection we are about to trust.
200
- export async function fetchPublishedKnownHosts({ apiBase, fetchImpl = fetch }) {
201
- const res = await fetchImpl(`${apiBase}/.well-known/ssh-known-hosts`, { headers: { accept: "text/plain" } });
202
- const text = await res.text().catch(() => "");
203
- if (!res.ok) return { ok: false, status: res.status };
204
- const parsed = parseKnownHostsLine(text);
205
- if (!parsed) return { ok: false, invalid: true };
206
- return { ok: true, pattern: parsed.pattern, line: parsed.line };
207
- }
208
-
209
- // ---------------------------------------------------------------------------
210
- // Does the repo the agent pushes from actually read the file we just wrote?
211
- //
212
- // `known-hosts refresh` writes Stamp's canonical path, but git uses whatever
213
- // core.sshCommand — or ssh's own config — names. The two can differ silently,
214
- // so the command could report success, print the right fingerprint, and leave
215
- // the file git consults untouched (#595). That failure surfaces only on
216
- // rotation day, and it surfaces as "push refused" to someone who was just told
217
- // the refresh worked — which is the moment people disable host key checking.
218
- //
219
- // The effective path is NOT derived by parsing core.sshCommand. Re-implementing
220
- // ssh's option parsing diverges from ssh itself on `-oFoo=` without a space,
221
- // `-F`, an unexpanded `~`, and repeated `-o`. The repo's own ssh program is
222
- // asked with `-G` instead, which reports the value ssh would use.
223
-
224
- // endpointFor turns the published known_hosts pattern into the host and port to
225
- // ask ssh about, so the probe targets the same endpoint the pin covers.
226
- export function endpointFor(pattern) {
227
- const bracketed = /^\[([^\]:]+)]:(\d{1,5})$/.exec(String(pattern ?? ""));
228
- if (bracketed) return { host: bracketed[1], port: Number(bracketed[2]) };
229
- const bare = String(pattern ?? "").trim();
230
- return bare ? { host: bare, port: 22 } : null;
231
- }
232
-
233
- // userKnownHostsFilesIn reads the one `userknownhostsfile` line out of `ssh -G`
234
- // output. The value may name several files (the default is `known_hosts` plus
235
- // `known_hosts2`), and a single path may itself contain spaces, so the raw
236
- // value is kept alongside the whitespace split rather than resolved to one.
237
- export function userKnownHostsFilesIn(sshGOutput) {
238
- for (const line of String(sshGOutput ?? "").split("\n")) {
239
- const m = /^userknownhostsfile\s+(.*)$/i.exec(line.trim());
240
- if (m) return { raw: m[1].trim(), candidates: m[1].trim().split(/\s+/).filter(Boolean) };
241
- }
242
- return null;
243
- }
244
-
245
- // canonicalPath names a file the same way regardless of how it was spelled.
246
- // resolve() alone is not enough: it makes a path absolute but does not follow
247
- // symlinks, so on macOS the written `/tmp/x` and ssh's `/private/tmp/x` are one
248
- // file under two names and compared unequal, which told a correctly configured
249
- // repo it was misconfigured. Symlinked home directories and bind-mounted
250
- // checkouts do the same thing off macOS.
251
- //
252
- // A path that cannot be canonicalised keeps its merely-absolute form. Only the
253
- // value ssh reports can be in that state — the file this command wrote exists
254
- // by the time the comparison runs — and a name that resolves to nothing cannot
255
- // be the file we just wrote, so the fallback decides nothing on its own.
256
- function canonicalPath(path) {
257
- const absolute = resolve(path);
258
- try {
259
- return realpathSync(absolute);
260
- } catch {
261
- return absolute;
262
- }
263
- }
264
-
265
- // knownHostsIsUsedBy answers "would ssh read the file we wrote?". A path that
266
- // contains spaces is ambiguous against a value naming several files, so both
267
- // readings are accepted. The ambiguity is resolved towards agreement on
268
- // purpose: a false "your repo is misconfigured" is worse than staying quiet,
269
- // because it sends a correctly configured agent looking for something to
270
- // change, and the handiest change is StrictHostKeyChecking=no.
271
- export function knownHostsIsUsedBy(effective, writtenPath) {
272
- const want = canonicalPath(writtenPath);
273
- if (canonicalPath(effective.raw) === want) return true;
274
- return effective.candidates.some((candidate) => canonicalPath(candidate) === want);
275
- }
276
-
277
- function defaultProbeExec(command, args, cwd) {
278
- const res = spawnSync(command, args, { cwd, encoding: "utf8", timeout: 10_000 });
279
- return { status: res.status, stdout: res.stdout ?? "" };
280
- }
281
-
282
- // probeRepoKnownHosts reports which known_hosts the repo at `cwd` would use.
283
- //
284
- // Every failure — not a repo, no git, ssh missing, a core.sshCommand that will
285
- // not run — returns `known: false` and the caller stays silent. This check
286
- // exists to keep people from disabling host key checking; it must never become
287
- // a reason to start changing a working setup.
288
- //
289
- // The probe runs the repo's own core.sshCommand. That is the same string
290
- // `git push` already executes here, so it adds no exposure for the repo the
291
- // agent is standing in — but it is why this must never accept a repository
292
- // path as an argument: running a stranger's configuration is a different act.
293
- //
294
- // ACCEPTED LIMIT, not an oversight (飞牛, reviewing #595): this is a
295
- // configuration-hygiene check, not a tamper-evident one.
296
- // it answers: which file this repo's configuration SAYS it reads
297
- // it cannot answer: which file this repo actually reads — the configuration
298
- // can lie, and `ssh -G` output is produced by that very
299
- // configuration
300
- // So "refresh reported nothing" means the configuration is aligned; it does not
301
- // prove the client is using the pinned file. The stronger check — connecting
302
- // once with the file just written — is deliberately not done here, because a
303
- // command that fails on an unreachable network sends people to
304
- // StrictHostKeyChecking=no. Keep the two claims separate wherever this is
305
- // described; an accepted limit that is not written down gets read as a
306
- // guarantee it never made.
307
- export function probeRepoKnownHosts({ cwd, pattern, execImpl = defaultProbeExec }) {
308
- const endpoint = endpointFor(pattern);
309
- if (!endpoint) return { known: false };
310
- const inside = execImpl("git", ["rev-parse", "--is-inside-work-tree"], cwd);
311
- if (inside.status !== 0 || inside.stdout.trim() !== "true") return { known: false, inRepo: false };
312
-
313
- const configured = execImpl("git", ["config", "--get", "core.sshCommand"], cwd);
314
- // `--get` exits non-zero with empty output when the key is unset. That is the
315
- // signal itself, not an error: such a repo connects through ssh's own config
316
- // or a per-invocation GIT_SSH_COMMAND.
317
- const sshCommand = configured.status === 0 ? configured.stdout.trim() : "";
318
- const probe = execImpl("/bin/sh", [
319
- "-c",
320
- `${sshCommand || "ssh"} -G -p ${endpoint.port} ${endpoint.host}`,
321
- ], cwd);
322
- if (probe.status !== 0) return { known: false, inRepo: true, configured: sshCommand !== "" };
323
- const effective = userKnownHostsFilesIn(probe.stdout);
324
- if (!effective) return { known: false, inRepo: true, configured: sshCommand !== "" };
325
- return { known: true, inRepo: true, configured: sshCommand !== "", effective };
326
- }
@@ -1,50 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
4
-
5
- // The gateway names the current CLI on every answer (Stamp-Cli-Latest; artin
6
- // 09-27: agents ran long-outdated CLIs and nothing told them). The CLI says
7
- // so on stderr at most once a day, recorded in the agent's own directory
8
- // (or ~/.stamp for a person). A CLI below Stamp-Cli-Minimum is refused by the
9
- // gateway itself (CLI_TOO_OLD).
10
-
11
- export function versionLess(a, b) {
12
- const parse = (v) => {
13
- const core = String(v ?? "").trim().replace(/^v/, "").split("-")[0];
14
- const parts = core.split(".").map((p) => (/^\d+$/.test(p) ? Number(p) : NaN));
15
- return parts.length && parts.every(Number.isFinite) ? parts : null;
16
- };
17
- const pa = parse(a), pb = parse(b);
18
- if (!pa || !pb) return false;
19
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
20
- const x = pa[i] ?? 0, y = pb[i] ?? 0;
21
- if (x !== y) return x < y;
22
- }
23
- return false;
24
- }
25
-
26
- export function updateCheckPath(env) {
27
- const agentDir = String(env?.STAMP_AGENT_STATE_DIR ?? "").trim();
28
- return agentDir ? join(agentDir, "update-check.json") : join(homedir(), ".stamp", "update-check.json");
29
- }
30
-
31
- const DAY_MS = 24 * 60 * 60 * 1000;
32
-
33
- // makeUpdateNotice returns the onVersions callback: it warns once per day
34
- // (per latest version) when a newer CLI exists.
35
- export function makeUpdateNotice({ current, env, warn, now = () => Date.now() }) {
36
- let done = false;
37
- return (latest) => {
38
- if (done || !latest || !versionLess(current, latest)) return;
39
- done = true;
40
- const path = updateCheckPath(env);
41
- let last = {};
42
- try { last = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}; } catch { last = {}; }
43
- if (last.latest === latest && now() - Number(last.at ?? 0) < DAY_MS) return;
44
- warn(latest);
45
- try {
46
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
47
- writeFileSync(path, `${JSON.stringify({ latest, at: now() })}\n`, { mode: 0o600 });
48
- } catch { /* a notice that cannot be recorded is shown again tomorrow */ }
49
- };
50
- }