@botiverse/stamp-cli 0.3.3 → 0.3.7

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.
@@ -0,0 +1,82 @@
1
+ import { AgentError } from "../errors.mjs";
2
+ import { parsePRTargetArgs, prDetailPath, takeNamedFlag } from "./read.mjs";
3
+
4
+ const shaRE = /^[0-9a-f]{40}$/;
5
+ const methods = new Set(["", "merge", "squash", "rebase"]);
6
+
7
+ function requireSHA(value, usageCode) {
8
+ if (typeof value !== "string" || !shaRE.test(value)) throw new AgentError(usageCode);
9
+ return value;
10
+ }
11
+
12
+ function parseWriteTarget(input, usageCode) {
13
+ const args = [...input];
14
+ const head = takeNamedFlag(args, "head", undefined, usageCode);
15
+ const base = takeNamedFlag(args, "base", undefined, usageCode);
16
+ const body = takeNamedFlag(args, "body", "b", usageCode);
17
+ const methodRaw = takeNamedFlag(args, "method", undefined, usageCode);
18
+ const target = parsePRTargetArgs(args, usageCode);
19
+ const expectedHead = requireSHA(head, usageCode);
20
+ const expectedBase = requireSHA(base, usageCode);
21
+ const mergeMethod = methodRaw === undefined ? "" : String(methodRaw).toLowerCase();
22
+ if (!methods.has(mergeMethod)) throw new AgentError(usageCode);
23
+ if (body !== undefined && !body.trim()) throw new AgentError(usageCode);
24
+ return { target, expectedHead, expectedBase, body, mergeMethod };
25
+ }
26
+
27
+ export function parsePRApproveArgs(input) {
28
+ const parsed = parseWriteTarget(input, "usagePrApprove");
29
+ if (parsed.mergeMethod) throw new AgentError("usagePrApprove");
30
+ return {
31
+ target: parsed.target,
32
+ path: `${prDetailPath(parsed.target)}/approve`,
33
+ method: "POST",
34
+ body: {
35
+ expectedHead: parsed.expectedHead,
36
+ expectedBase: parsed.expectedBase,
37
+ ...(parsed.body !== undefined ? { body: parsed.body } : {}),
38
+ },
39
+ };
40
+ }
41
+
42
+ export function parsePRMergeArgs(input) {
43
+ const parsed = parseWriteTarget(input, "usagePrMerge");
44
+ if (parsed.body !== undefined) throw new AgentError("usagePrMerge");
45
+ return {
46
+ target: parsed.target,
47
+ path: `${prDetailPath(parsed.target)}/merge`,
48
+ method: "PUT",
49
+ body: {
50
+ expectedHead: parsed.expectedHead,
51
+ expectedBase: parsed.expectedBase,
52
+ ...(parsed.mergeMethod ? { mergeMethod: parsed.mergeMethod } : {}),
53
+ },
54
+ };
55
+ }
56
+
57
+ function requireObject(value, code) {
58
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new AgentError(code);
59
+ return value;
60
+ }
61
+
62
+ export function validatePRApproveResult(result, target) {
63
+ const expectedRepo = `${target.owner}/${target.repo}`;
64
+ const d = requireObject(result, "prApproveOutcomeUnknown");
65
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
66
+ && d.number === target.number
67
+ && shaRE.test(d.approvedHead) && shaRE.test(d.approvedBase)
68
+ && typeof d.reviewerLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.reviewerLogin);
69
+ if (!valid) throw new AgentError("prApproveOutcomeUnknown");
70
+ return d;
71
+ }
72
+
73
+ export function validatePRMergeResult(result, target) {
74
+ const expectedRepo = `${target.owner}/${target.repo}`;
75
+ const d = requireObject(result, "prMergeOutcomeUnknown");
76
+ const valid = typeof d.repository === "string" && d.repository.toLowerCase() === expectedRepo.toLowerCase()
77
+ && d.number === target.number && d.merged === true
78
+ && shaRE.test(d.mergeSha) && shaRE.test(d.mergedHead) && shaRE.test(d.mergedBase)
79
+ && typeof d.actorLogin === "string" && /^[A-Za-z0-9-]+$/.test(d.actorLogin);
80
+ if (!valid) throw new AgentError("prMergeOutcomeUnknown");
81
+ return d;
82
+ }
@@ -58,3 +58,18 @@ export function runGitClone({ url, directory, gitFlags, env, spawnImpl = spawn }
58
58
  child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
59
59
  });
60
60
  }
61
+
62
+ // runGitConfig pins the enrolled identity in the cloned repository itself, so
63
+ // every later `git push`/`git fetch` from that checkout uses the same key and
64
+ // the same pinned host key without any GIT_SSH_COMMAND export.
65
+ export function runGitSetSSHCommand({ directory, sshCommand, spawnImpl = spawn }) {
66
+ return new Promise((resolve) => {
67
+ const child = spawnImpl("git", ["-C", directory, "config", "--local", "core.sshCommand", sshCommand], {
68
+ stdio: ["ignore", "ignore", "pipe"],
69
+ });
70
+ let stderr = "";
71
+ child.stderr?.on("data", (b) => { stderr += b; });
72
+ child.on("error", () => resolve({ ok: false }));
73
+ child.on("close", (code) => resolve({ ok: code === 0, stderr }));
74
+ });
75
+ }
@@ -0,0 +1,43 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ // Task #514 (ka-grok): "key enroll 用过哪把钥,clone 就用那把" — the key `stamp
6
+ // key enroll` enrolled is the key `stamp repo clone` uses, recorded at enroll
7
+ // time and read back at clone time, per instance origin. The CLI never scans
8
+ // ~/.ssh or guesses paths: a record is written only from what the operator
9
+ // pointed enroll at, and a missing record falls through to the documented
10
+ // default path, whose absence is reported (not searched around).
11
+
12
+ export function identitiesPath(env) {
13
+ const fromEnv = String(env?.STAMP_IDENTITIES ?? "").trim();
14
+ return fromEnv || join(homedir(), ".stamp", "identities.json");
15
+ }
16
+
17
+ function readAll(path) {
18
+ if (!existsSync(path)) return {};
19
+ let parsed;
20
+ try { parsed = JSON.parse(readFileSync(path, "utf8")); } catch { return {}; }
21
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
22
+ }
23
+
24
+ // readRecordedIdentity returns the enrollment record for one origin, or null.
25
+ // A corrupt or foreign-shaped file is "no record", never an exception: the
26
+ // record is a convenience over an explicit flag, not a gate.
27
+ export function readRecordedIdentity(env, origin) {
28
+ const record = readAll(identitiesPath(env))[String(origin ?? "")];
29
+ if (!record || typeof record !== "object" || typeof record.identityPath !== "string" || !record.identityPath) return null;
30
+ return record;
31
+ }
32
+
33
+ // recordIdentity merges one origin's record into the file (0600: it names a
34
+ // private key path and a key id, not a secret, but it is the operator's).
35
+ export function recordIdentity(env, origin, record) {
36
+ const path = identitiesPath(env);
37
+ const all = readAll(path);
38
+ all[String(origin)] = record;
39
+ mkdirSync(dirname(path), { recursive: true });
40
+ writeFileSync(path, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
41
+ chmodSync(path, 0o600);
42
+ return path;
43
+ }
@@ -0,0 +1,227 @@
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
+ export function defaultIdentityPath(env) {
16
+ return join(homedir(), ".ssh", "id_ed25519");
17
+ }
18
+
19
+ // resolveIdentity picks the private key in this order and says which source
20
+ // won: an explicit --identity, the STAMP_SSH_IDENTITY override, the key
21
+ // recorded by `stamp key enroll` for this instance (task #514), the default
22
+ // path. No source scans a directory.
23
+ export function resolveIdentity(env, flagValue, recorded) {
24
+ const fromFlag = String(flagValue ?? "").trim();
25
+ if (fromFlag) return { identityPath: fromFlag, source: "flag" };
26
+ const fromEnv = String(env?.STAMP_SSH_IDENTITY ?? "").trim();
27
+ if (fromEnv) return { identityPath: fromEnv, source: "env" };
28
+ const fromRecord = String(recorded?.identityPath ?? "").trim();
29
+ if (fromRecord) return { identityPath: fromRecord, source: "enrolled" };
30
+ return { identityPath: defaultIdentityPath(env), source: "default" };
31
+ }
32
+
33
+ export function resolveIdentityPath(env, flagValue, recorded) {
34
+ return resolveIdentity(env, flagValue, recorded).identityPath;
35
+ }
36
+
37
+ // defaultKnownHostsPath is one stable file for every Stamp instance (a
38
+ // known_hosts file holds many lines); lines are merged per host pattern below.
39
+ export function resolveKnownHostsPath(env, flagValue) {
40
+ const fromFlag = String(flagValue ?? "").trim();
41
+ if (fromFlag) return fromFlag;
42
+ const fromEnv = String(env?.STAMP_KNOWN_HOSTS ?? "").trim();
43
+ return fromEnv || join(homedir(), ".stamp", "known_hosts");
44
+ }
45
+
46
+ function shellQuote(value) {
47
+ const s = String(value);
48
+ if (s === "" || /[^A-Za-z0-9._@%+,:=\/-]/.test(s)) {
49
+ return `'${s.replaceAll("'", `'\\''`)}'`;
50
+ }
51
+ return s;
52
+ }
53
+
54
+ // sshCommandFor is the value git needs (GIT_SSH_COMMAND / core.sshCommand). It
55
+ // names the identity and the pinned host key file explicitly, and never falls
56
+ // back to ~/.ssh/known_hosts or to the agent's other identities.
57
+ export function sshCommandFor({ identityPath, knownHostsPath }) {
58
+ return [
59
+ "ssh",
60
+ "-i", shellQuote(identityPath),
61
+ "-o", "IdentitiesOnly=yes",
62
+ "-o", `UserKnownHostsFile=${shellQuote(knownHostsPath)}`,
63
+ "-o", "StrictHostKeyChecking=yes",
64
+ ].join(" ");
65
+ }
66
+
67
+ 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)$/;
68
+ const KNOWN_HOSTS_PATTERN = /^(\[[^\]:]+]:\d{1,5}|[A-Za-z0-9][A-Za-z0-9.-]*)$/;
69
+
70
+ // parseKnownHostsLine accepts exactly the one-line c2sp form the gateway
71
+ // publishes and rejects anything else: pinning a malformed line would either
72
+ // fail every connection or silently trust the wrong pattern.
73
+ export function parseKnownHostsLine(text) {
74
+ const line = String(text ?? "").trim();
75
+ if (!line || line.includes("\n")) return null;
76
+ const [pattern, keyType, base64] = line.split(/\s+/);
77
+ if (!pattern || !keyType || !base64) return null;
78
+ if (!KNOWN_HOSTS_PATTERN.test(pattern) || !KNOWN_HOSTS_KEY_TYPE.test(keyType)) return null;
79
+ if (!/^[A-Za-z0-9+/]+={0,3}$/.test(base64) || base64.length < 40) return null;
80
+ return { pattern, line };
81
+ }
82
+
83
+ // writePinnedKnownHosts merges one line into the known_hosts file, replacing any
84
+ // earlier line for the same pattern so a rotated host key is superseded rather
85
+ // than left to collide (two lines for one pattern make ssh refuse the host).
86
+ export function writePinnedKnownHosts(path, pattern, line) {
87
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
88
+ const kept = existing
89
+ .split("\n")
90
+ .filter((l) => l.trim() !== "" && l.trim().split(/\s+/)[0] !== pattern);
91
+ kept.push(line);
92
+ mkdirSync(dirname(path), { recursive: true });
93
+ writeFileSync(path, `${kept.join("\n")}\n`, { mode: 0o600 });
94
+ chmodSync(path, 0o600);
95
+ }
96
+
97
+ // fetchPublishedKnownHosts reads the host key from the instance itself over
98
+ // HTTPS — a channel independent of the SSH connection — so the pin is not
99
+ // first-use. "Not available here" (404) is reported, never substituted with a
100
+ // keyscan of the very connection we are about to trust.
101
+ export async function fetchPublishedKnownHosts({ apiBase, fetchImpl = fetch }) {
102
+ const res = await fetchImpl(`${apiBase}/.well-known/ssh-known-hosts`, { headers: { accept: "text/plain" } });
103
+ const text = await res.text().catch(() => "");
104
+ if (!res.ok) return { ok: false, status: res.status };
105
+ const parsed = parseKnownHostsLine(text);
106
+ if (!parsed) return { ok: false, invalid: true };
107
+ return { ok: true, pattern: parsed.pattern, line: parsed.line };
108
+ }
109
+
110
+ // ---------------------------------------------------------------------------
111
+ // Does the repo the agent pushes from actually read the file we just wrote?
112
+ //
113
+ // `known-hosts refresh` writes Stamp's canonical path, but git uses whatever
114
+ // core.sshCommand — or ssh's own config — names. The two can differ silently,
115
+ // so the command could report success, print the right fingerprint, and leave
116
+ // the file git consults untouched (#595). That failure surfaces only on
117
+ // rotation day, and it surfaces as "push refused" to someone who was just told
118
+ // the refresh worked — which is the moment people disable host key checking.
119
+ //
120
+ // The effective path is NOT derived by parsing core.sshCommand. Re-implementing
121
+ // ssh's option parsing diverges from ssh itself on `-oFoo=` without a space,
122
+ // `-F`, an unexpanded `~`, and repeated `-o`. The repo's own ssh program is
123
+ // asked with `-G` instead, which reports the value ssh would use.
124
+
125
+ // endpointFor turns the published known_hosts pattern into the host and port to
126
+ // ask ssh about, so the probe targets the same endpoint the pin covers.
127
+ export function endpointFor(pattern) {
128
+ const bracketed = /^\[([^\]:]+)]:(\d{1,5})$/.exec(String(pattern ?? ""));
129
+ if (bracketed) return { host: bracketed[1], port: Number(bracketed[2]) };
130
+ const bare = String(pattern ?? "").trim();
131
+ return bare ? { host: bare, port: 22 } : null;
132
+ }
133
+
134
+ // userKnownHostsFilesIn reads the one `userknownhostsfile` line out of `ssh -G`
135
+ // output. The value may name several files (the default is `known_hosts` plus
136
+ // `known_hosts2`), and a single path may itself contain spaces, so the raw
137
+ // value is kept alongside the whitespace split rather than resolved to one.
138
+ export function userKnownHostsFilesIn(sshGOutput) {
139
+ for (const line of String(sshGOutput ?? "").split("\n")) {
140
+ const m = /^userknownhostsfile\s+(.*)$/i.exec(line.trim());
141
+ if (m) return { raw: m[1].trim(), candidates: m[1].trim().split(/\s+/).filter(Boolean) };
142
+ }
143
+ return null;
144
+ }
145
+
146
+ // canonicalPath names a file the same way regardless of how it was spelled.
147
+ // resolve() alone is not enough: it makes a path absolute but does not follow
148
+ // symlinks, so on macOS the written `/tmp/x` and ssh's `/private/tmp/x` are one
149
+ // file under two names and compared unequal, which told a correctly configured
150
+ // repo it was misconfigured. Symlinked home directories and bind-mounted
151
+ // checkouts do the same thing off macOS.
152
+ //
153
+ // A path that cannot be canonicalised keeps its merely-absolute form. Only the
154
+ // value ssh reports can be in that state — the file this command wrote exists
155
+ // by the time the comparison runs — and a name that resolves to nothing cannot
156
+ // be the file we just wrote, so the fallback decides nothing on its own.
157
+ function canonicalPath(path) {
158
+ const absolute = resolve(path);
159
+ try {
160
+ return realpathSync(absolute);
161
+ } catch {
162
+ return absolute;
163
+ }
164
+ }
165
+
166
+ // knownHostsIsUsedBy answers "would ssh read the file we wrote?". A path that
167
+ // contains spaces is ambiguous against a value naming several files, so both
168
+ // readings are accepted. The ambiguity is resolved towards agreement on
169
+ // purpose: a false "your repo is misconfigured" is worse than staying quiet,
170
+ // because it sends a correctly configured agent looking for something to
171
+ // change, and the handiest change is StrictHostKeyChecking=no.
172
+ export function knownHostsIsUsedBy(effective, writtenPath) {
173
+ const want = canonicalPath(writtenPath);
174
+ if (canonicalPath(effective.raw) === want) return true;
175
+ return effective.candidates.some((candidate) => canonicalPath(candidate) === want);
176
+ }
177
+
178
+ function defaultProbeExec(command, args, cwd) {
179
+ const res = spawnSync(command, args, { cwd, encoding: "utf8", timeout: 10_000 });
180
+ return { status: res.status, stdout: res.stdout ?? "" };
181
+ }
182
+
183
+ // probeRepoKnownHosts reports which known_hosts the repo at `cwd` would use.
184
+ //
185
+ // Every failure — not a repo, no git, ssh missing, a core.sshCommand that will
186
+ // not run — returns `known: false` and the caller stays silent. This check
187
+ // exists to keep people from disabling host key checking; it must never become
188
+ // a reason to start changing a working setup.
189
+ //
190
+ // The probe runs the repo's own core.sshCommand. That is the same string
191
+ // `git push` already executes here, so it adds no exposure for the repo the
192
+ // agent is standing in — but it is why this must never accept a repository
193
+ // path as an argument: running a stranger's configuration is a different act.
194
+ //
195
+ // ACCEPTED LIMIT, not an oversight (飞牛, reviewing #595): this is a
196
+ // configuration-hygiene check, not a tamper-evident one.
197
+ // it answers: which file this repo's configuration SAYS it reads
198
+ // it cannot answer: which file this repo actually reads — the configuration
199
+ // can lie, and `ssh -G` output is produced by that very
200
+ // configuration
201
+ // So "refresh reported nothing" means the configuration is aligned; it does not
202
+ // prove the client is using the pinned file. The stronger check — connecting
203
+ // once with the file just written — is deliberately not done here, because a
204
+ // command that fails on an unreachable network sends people to
205
+ // StrictHostKeyChecking=no. Keep the two claims separate wherever this is
206
+ // described; an accepted limit that is not written down gets read as a
207
+ // guarantee it never made.
208
+ export function probeRepoKnownHosts({ cwd, pattern, execImpl = defaultProbeExec }) {
209
+ const endpoint = endpointFor(pattern);
210
+ if (!endpoint) return { known: false };
211
+ const inside = execImpl("git", ["rev-parse", "--is-inside-work-tree"], cwd);
212
+ if (inside.status !== 0 || inside.stdout.trim() !== "true") return { known: false, inRepo: false };
213
+
214
+ const configured = execImpl("git", ["config", "--get", "core.sshCommand"], cwd);
215
+ // `--get` exits non-zero with empty output when the key is unset. That is the
216
+ // signal itself, not an error: such a repo connects through ssh's own config
217
+ // or a per-invocation GIT_SSH_COMMAND.
218
+ const sshCommand = configured.status === 0 ? configured.stdout.trim() : "";
219
+ const probe = execImpl("/bin/sh", [
220
+ "-c",
221
+ `${sshCommand || "ssh"} -G -p ${endpoint.port} ${endpoint.host}`,
222
+ ], cwd);
223
+ if (probe.status !== 0) return { known: false, inRepo: true, configured: sshCommand !== "" };
224
+ const effective = userKnownHostsFilesIn(probe.stdout);
225
+ if (!effective) return { known: false, inRepo: true, configured: sshCommand !== "" };
226
+ return { known: true, inRepo: true, configured: sshCommand !== "", effective };
227
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/stamp-cli",
3
- "version": "0.3.3",
3
+ "version": "0.3.7",
4
4
  "description": "CLI for Stamp — Agent Git gateway in the Raft loop (bin stamp; future origin stamp.build)",
5
5
  "license": "MIT",
6
6
  "type": "module",