@botiverse/stamp-cli 0.3.3 → 0.3.4

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.
@@ -1,4 +1,4 @@
1
- import { AgentError } from "./errors.mjs";
1
+ import { AgentError } from "../errors.mjs";
2
2
 
3
3
  const consolidatedStatuses = new Set(["OPEN", "DRAFT", "MERGING", "MERGED", "CLOSED"]);
4
4
  const ciStatuses = new Set(["passing", "failing", "pending", "none"]);
@@ -11,7 +11,7 @@ const reviewStates = new Set([
11
11
  const terminalPassConclusions = new Set(["success", "neutral", "skipped"]);
12
12
  const pendingCheckStates = new Set(["", "expected", "in_progress", "pending", "queued", "requested", "waiting"]);
13
13
 
14
- function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
14
+ export function takeNamedFlag(args, long, short, usageCode = "usagePrRead") {
15
15
  const matches = [];
16
16
  for (let i = 0; i < args.length; i++) {
17
17
  if (args[i] === `--${long}` || (short && args[i] === `-${short}`)) {
@@ -77,7 +77,7 @@ function targetFromURL(value) {
77
77
  * Parse `stamp pr list` args (task #397 slice 1 + #345 CLI lane).
78
78
  *
79
79
  * Optional, opt-in pagination — the wire adds `?limit=` and an OPAQUE cursor to
80
- * the SAME `/v1/pr-inbox` path (never a new path):
80
+ * the SAME `/v1/inbox/pull-requests` path (never a new path):
81
81
  * --limit <n> 1..200 page size
82
82
  * --cursor <s> an opaque server token, passed through VERBATIM (never parsed,
83
83
  * never cached, never reused across identities: it is bound to
@@ -108,7 +108,11 @@ export function parsePRListArgs(input) {
108
108
  params.set("cursor", cursor);
109
109
  }
110
110
  const query = params.toString();
111
- const path = query === "" ? "/v1/pr-inbox" : `/v1/pr-inbox?${query}`;
111
+ // task #413: the SSOT is /v1/inbox/pull-requests; the server keeps
112
+ // /v1/pr-inbox as a Deprecation alias for one version cycle. The CLI targets
113
+ // the SSOT (one build point).
114
+ const base = "/v1/inbox/pull-requests";
115
+ const path = query === "" ? base : `${base}?${query}`;
112
116
  return { path, sections };
113
117
  }
114
118
 
@@ -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,96 @@
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
+ // `stamp repo clone` must not ask a human to export GIT_SSH_COMMAND: after
6
+ // `stamp key enroll` the CLI already knows which key it enrolled and the
7
+ // gateway already publishes its host key over HTTPS
8
+ // (/.well-known/ssh-known-hosts, task #463). So the clone carries both: the
9
+ // private key as `-i`, and the published line as the ONLY trusted host key
10
+ // (StrictHostKeyChecking=yes + IdentitiesOnly=yes), which is a pin, not TOFU.
11
+
12
+ // defaultIdentityPath is where `stamp key enroll` looks for the public key; the
13
+ // private half is the same path without `.pub`.
14
+ export function defaultIdentityPath(env) {
15
+ return join(homedir(), ".ssh", "id_ed25519");
16
+ }
17
+
18
+ export function resolveIdentityPath(env, flagValue) {
19
+ const fromFlag = String(flagValue ?? "").trim();
20
+ if (fromFlag) return fromFlag;
21
+ const fromEnv = String(env?.STAMP_SSH_IDENTITY ?? "").trim();
22
+ return fromEnv || defaultIdentityPath(env);
23
+ }
24
+
25
+ // defaultKnownHostsPath is one stable file for every Stamp instance (a
26
+ // known_hosts file holds many lines); lines are merged per host pattern below.
27
+ export function resolveKnownHostsPath(env, flagValue) {
28
+ const fromFlag = String(flagValue ?? "").trim();
29
+ if (fromFlag) return fromFlag;
30
+ const fromEnv = String(env?.STAMP_KNOWN_HOSTS ?? "").trim();
31
+ return fromEnv || join(homedir(), ".stamp", "known_hosts");
32
+ }
33
+
34
+ function shellQuote(value) {
35
+ const s = String(value);
36
+ if (s === "" || /[^A-Za-z0-9._@%+,:=\/-]/.test(s)) {
37
+ return `'${s.replaceAll("'", `'\\''`)}'`;
38
+ }
39
+ return s;
40
+ }
41
+
42
+ // sshCommandFor is the value git needs (GIT_SSH_COMMAND / core.sshCommand). It
43
+ // names the identity and the pinned host key file explicitly, and never falls
44
+ // back to ~/.ssh/known_hosts or to the agent's other identities.
45
+ export function sshCommandFor({ identityPath, knownHostsPath }) {
46
+ return [
47
+ "ssh",
48
+ "-i", shellQuote(identityPath),
49
+ "-o", "IdentitiesOnly=yes",
50
+ "-o", `UserKnownHostsFile=${shellQuote(knownHostsPath)}`,
51
+ "-o", "StrictHostKeyChecking=yes",
52
+ ].join(" ");
53
+ }
54
+
55
+ 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)$/;
56
+ const KNOWN_HOSTS_PATTERN = /^(\[[^\]:]+]:\d{1,5}|[A-Za-z0-9][A-Za-z0-9.-]*)$/;
57
+
58
+ // parseKnownHostsLine accepts exactly the one-line c2sp form the gateway
59
+ // publishes and rejects anything else: pinning a malformed line would either
60
+ // fail every connection or silently trust the wrong pattern.
61
+ export function parseKnownHostsLine(text) {
62
+ const line = String(text ?? "").trim();
63
+ if (!line || line.includes("\n")) return null;
64
+ const [pattern, keyType, base64] = line.split(/\s+/);
65
+ if (!pattern || !keyType || !base64) return null;
66
+ if (!KNOWN_HOSTS_PATTERN.test(pattern) || !KNOWN_HOSTS_KEY_TYPE.test(keyType)) return null;
67
+ if (!/^[A-Za-z0-9+/]+={0,3}$/.test(base64) || base64.length < 40) return null;
68
+ return { pattern, line };
69
+ }
70
+
71
+ // writePinnedKnownHosts merges one line into the known_hosts file, replacing any
72
+ // earlier line for the same pattern so a rotated host key is superseded rather
73
+ // than left to collide (two lines for one pattern make ssh refuse the host).
74
+ export function writePinnedKnownHosts(path, pattern, line) {
75
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
76
+ const kept = existing
77
+ .split("\n")
78
+ .filter((l) => l.trim() !== "" && l.trim().split(/\s+/)[0] !== pattern);
79
+ kept.push(line);
80
+ mkdirSync(dirname(path), { recursive: true });
81
+ writeFileSync(path, `${kept.join("\n")}\n`, { mode: 0o600 });
82
+ chmodSync(path, 0o600);
83
+ }
84
+
85
+ // fetchPublishedKnownHosts reads the host key from the instance itself over
86
+ // HTTPS — a channel independent of the SSH connection — so the pin is not
87
+ // first-use. "Not available here" (404) is reported, never substituted with a
88
+ // keyscan of the very connection we are about to trust.
89
+ export async function fetchPublishedKnownHosts({ apiBase, fetchImpl = fetch }) {
90
+ const res = await fetchImpl(`${apiBase}/.well-known/ssh-known-hosts`, { headers: { accept: "text/plain" } });
91
+ const text = await res.text().catch(() => "");
92
+ if (!res.ok) return { ok: false, status: res.status };
93
+ const parsed = parseKnownHostsLine(text);
94
+ if (!parsed) return { ok: false, invalid: true };
95
+ return { ok: true, pattern: parsed.pattern, line: parsed.line };
96
+ }
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.4",
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",