@botiverse/stamp-cli 0.3.4 → 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.
- package/README.md +9 -2
- package/lib/commands/changelog.mjs +58 -0
- package/lib/commands/key.mjs +38 -1
- package/lib/commands/knownhosts.mjs +144 -0
- package/lib/commands/pr.mjs +32 -1
- package/lib/commands/receipt.mjs +7 -1
- package/lib/commands/repo.mjs +16 -4
- package/lib/locale.mjs +88 -6
- package/lib/main.mjs +5 -1
- package/lib/pr/comment.mjs +8 -3
- package/lib/pr/read.mjs +21 -1
- package/lib/pr/review.mjs +81 -0
- package/lib/repo/identities.mjs +43 -0
- package/lib/repo/ssh.mjs +136 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,8 +37,15 @@ Configuration layering is `environment > executable defaults`: `STAMP_URL` and
|
|
|
37
37
|
service command-line flags today.
|
|
38
38
|
|
|
39
39
|
`repo clone` carries the SSH identity itself (task #475): it uses the key
|
|
40
|
-
`key enroll`
|
|
41
|
-
|
|
40
|
+
`key enroll` enrolled. `key enroll` records the private key next to the public
|
|
41
|
+
key it read (the path without `.pub`), per instance, in `~/.stamp/identities.json`
|
|
42
|
+
(`STAMP_IDENTITIES` to relocate; nothing is recorded for a public key read from
|
|
43
|
+
stdin or one whose private half is not on this machine, and the command says so).
|
|
44
|
+
A bare `repo clone` then uses that record; `--identity FILE` and `STAMP_SSH_IDENTITY`
|
|
45
|
+
still win, and without a record the default `~/.ssh/id_ed25519` applies. The CLI
|
|
46
|
+
never scans `~/.ssh` or guesses paths: a recorded key that is not on this machine
|
|
47
|
+
is named, with `key enroll` here or `--identity` as the ways out (task #514). It
|
|
48
|
+
also pins the host key the instance publishes at `/.well-known/ssh-known-hosts` into
|
|
42
49
|
`~/.stamp/known_hosts` (`--known-hosts FILE` / `STAMP_KNOWN_HOSTS`), then records
|
|
43
50
|
the same command as the clone's `core.sshCommand` so later `git push`/`git fetch`
|
|
44
51
|
inherit it. No `GIT_SSH_COMMAND` export is needed.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { t } from "../locale.mjs";
|
|
2
|
+
|
|
3
|
+
// `stamp changelog [--limit N]`: the gateway's release history (one release
|
|
4
|
+
// per staging-v tag with the pull requests it carried), read from
|
|
5
|
+
// GET /changelog.json. The build block says which image answered; the running
|
|
6
|
+
// release is the one whose tag equals build.version (the same source commit
|
|
7
|
+
// can be cut as two tags, so the SHA cannot tell them apart).
|
|
8
|
+
//
|
|
9
|
+
// Audience: by default only entries whose `audience` includes "agent" (the
|
|
10
|
+
// CLI and the HTTP/SSH surface an agent drives) — artin: the human view and
|
|
11
|
+
// the agent view differ by content. `--all` shows everything; the JSON says
|
|
12
|
+
// which view it is (`view.audience`) so a reader never mistakes a filtered
|
|
13
|
+
// document for the whole history.
|
|
14
|
+
const AUDIENCE = "agent";
|
|
15
|
+
|
|
16
|
+
export function visibleEntries(entries, all) {
|
|
17
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
18
|
+
if (all) return { entries: list, hidden: 0 };
|
|
19
|
+
const kept = list.filter((e) => Array.isArray(e?.audience) && e.audience.includes(AUDIENCE));
|
|
20
|
+
return { entries: kept, hidden: list.length - kept.length };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function run(ctx) {
|
|
24
|
+
let limit = Infinity;
|
|
25
|
+
let all = false;
|
|
26
|
+
const rest = [];
|
|
27
|
+
for (let i = 0; i < ctx.args.length; i++) {
|
|
28
|
+
const arg = ctx.args[i];
|
|
29
|
+
if (arg === "--limit") {
|
|
30
|
+
const value = Number(ctx.args[++i]);
|
|
31
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(t(ctx.locale, "usageChangelog"));
|
|
32
|
+
limit = value;
|
|
33
|
+
} else if (arg === "--all") all = true;
|
|
34
|
+
else rest.push(arg);
|
|
35
|
+
}
|
|
36
|
+
if (rest.length) throw new Error(t(ctx.locale, "usageChangelog"));
|
|
37
|
+
const d = await ctx.api("GET", "/changelog.json");
|
|
38
|
+
const releases = (Array.isArray(d.releases) ? d.releases.slice(0, limit) : []).map((r) => {
|
|
39
|
+
const { entries, hidden } = visibleEntries(r.entries, all);
|
|
40
|
+
return { ...r, entries, hidden };
|
|
41
|
+
});
|
|
42
|
+
ctx.emit({ ...d, view: { audience: all ? "all" : AUDIENCE }, releases }, () => {
|
|
43
|
+
ctx.out(t(ctx.locale, "changelogBuild", { version: d.build?.version ?? "-", commit: String(d.build?.commit ?? "").slice(0, 8) || "-" }));
|
|
44
|
+
ctx.out(t(ctx.locale, all ? "changelogScopeAll" : "changelogScopeAgent"));
|
|
45
|
+
if (!releases.length) { ctx.out(t(ctx.locale, "changelogEmpty")); return; }
|
|
46
|
+
for (const r of releases) {
|
|
47
|
+
const current = r.tag && r.tag === d.build?.version ? ` ${t(ctx.locale, "changelogCurrentMark")}` : "";
|
|
48
|
+
ctx.out(`${r.tag} (${String(r.source ?? "").slice(0, 8)})${current}`);
|
|
49
|
+
if (!r.entries.length) {
|
|
50
|
+
ctx.out(` ${t(ctx.locale, r.hidden ? "changelogNoneForAgents" : "changelogNoEntries", { hidden: r.hidden })}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
for (const e of r.entries) ctx.out(` #${e.number} ${String(e.title ?? "").replace(/\s+/g, " ")}${e.author ? ` (${e.author})` : ""}`);
|
|
54
|
+
if (r.hidden) ctx.out(` ${t(ctx.locale, "changelogHiddenCount", { hidden: r.hidden })}`);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
return ctx.exit(0);
|
|
58
|
+
}
|
package/lib/commands/key.mjs
CHANGED
|
@@ -2,10 +2,29 @@ import { existsSync } from "node:fs";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { t } from "../locale.mjs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
5
6
|
import { takeFlag, readPublicKey } from "../flags.mjs";
|
|
7
|
+
import { recordIdentity } from "../repo/identities.mjs";
|
|
6
8
|
|
|
7
9
|
export async function run(ctx) {
|
|
8
10
|
const sub = ctx.args.shift();
|
|
11
|
+
if (sub === "list") {
|
|
12
|
+
if (ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageKeyList"));
|
|
13
|
+
const d = await ctx.api("GET", "/v1/keys");
|
|
14
|
+
const items = Array.isArray(d?.items) ? d.items : [];
|
|
15
|
+
ctx.emit(d, () => {
|
|
16
|
+
if (items.length === 0) ctx.out(t(ctx.locale, "keyListEmpty"));
|
|
17
|
+
else for (const item of items) ctx.out(`${item.fingerprint}\t${item.keyId}`);
|
|
18
|
+
});
|
|
19
|
+
return ctx.exit(0);
|
|
20
|
+
}
|
|
21
|
+
if (sub === "revoke") {
|
|
22
|
+
const keyId = ctx.args.shift();
|
|
23
|
+
if (!keyId || ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageKeyRevoke"));
|
|
24
|
+
const d = await ctx.api("DELETE", `/v1/keys/${encodeURIComponent(keyId)}`);
|
|
25
|
+
ctx.emit(d, () => ctx.out(t(ctx.locale, "keyRevoked", { keyId: d.keyId ?? keyId })));
|
|
26
|
+
return ctx.exit(0);
|
|
27
|
+
}
|
|
9
28
|
if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
|
|
10
29
|
const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
11
30
|
if (keyPath !== "-" && !existsSync(keyPath)) {
|
|
@@ -16,6 +35,24 @@ export async function run(ctx) {
|
|
|
16
35
|
}
|
|
17
36
|
const publicKey = readPublicKey(keyPath);
|
|
18
37
|
const d = await ctx.api("POST", "/v1/keys", { publicKey });
|
|
19
|
-
|
|
38
|
+
// Task #514: remember which private key this enrollment belongs to, for this
|
|
39
|
+
// instance, so a later `repo clone` uses it without --identity. The private
|
|
40
|
+
// half is the public path without `.pub` — the only derivation, no search.
|
|
41
|
+
// A public key from stdin, or one whose private half is not here, records
|
|
42
|
+
// nothing and says so.
|
|
43
|
+
let identity = null;
|
|
44
|
+
if (keyPath !== "-") {
|
|
45
|
+
const privatePath = resolve(keyPath.replace(/\.pub$/i, ""));
|
|
46
|
+
if (privatePath !== resolve(keyPath) && existsSync(privatePath)) {
|
|
47
|
+
identity = { identityPath: privatePath, fingerprint: d.fingerprint ?? null, keyId: d.keyId ?? null, enrolledAt: new Date().toISOString() };
|
|
48
|
+
recordIdentity(ctx.env, ctx.auth.apiBase, identity);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
ctx.emit({ ...d, identity }, () => {
|
|
52
|
+
ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId }));
|
|
53
|
+
ctx.out(identity
|
|
54
|
+
? t(ctx.locale, "enrolledIdentityRecorded", { path: identity.identityPath })
|
|
55
|
+
: t(ctx.locale, "enrolledIdentityNotRecorded", { path: keyPath === "-" ? "-" : resolve(keyPath.replace(/\.pub$/i, "")) }));
|
|
56
|
+
});
|
|
20
57
|
return ctx.exit(0);
|
|
21
58
|
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { t } from "../locale.mjs";
|
|
3
|
+
import { takeFlag } from "../flags.mjs";
|
|
4
|
+
import {
|
|
5
|
+
fetchPublishedKnownHosts,
|
|
6
|
+
knownHostsIsUsedBy,
|
|
7
|
+
probeRepoKnownHosts,
|
|
8
|
+
resolveIdentityPath,
|
|
9
|
+
resolveKnownHostsPath,
|
|
10
|
+
sshCommandFor,
|
|
11
|
+
writePinnedKnownHosts,
|
|
12
|
+
} from "../repo/ssh.mjs";
|
|
13
|
+
|
|
14
|
+
// The SSH fingerprint of a known_hosts line: base64(sha256(raw key)), which is
|
|
15
|
+
// what `ssh-keygen -lf` prints and what an announcement quotes. Printing it is
|
|
16
|
+
// the point of this command — an operator compares it to the published value
|
|
17
|
+
// rather than reading a base64 blob.
|
|
18
|
+
export function fingerprintOf(line) {
|
|
19
|
+
const base64 = line.trim().split(/\s+/)[2];
|
|
20
|
+
if (!base64) return null;
|
|
21
|
+
return `SHA256:${createHash("sha256").update(Buffer.from(base64, "base64")).digest("base64").replace(/=+$/, "")}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// `known-hosts refresh` exists because rotating the gateway's host key
|
|
25
|
+
// otherwise has no legitimate client-side route: the fetch-and-pin pair lived
|
|
26
|
+
// only inside `repo clone`, so an agent that already had a clone could either
|
|
27
|
+
// clone again or disable host key checking. The second is what people actually
|
|
28
|
+
// do, and after a host key leak it is the worst available outcome (#592).
|
|
29
|
+
//
|
|
30
|
+
// The write only happens after a usable line is in hand, so a failed fetch
|
|
31
|
+
// leaves known_hosts byte-for-byte unchanged: a refresh that damages the file
|
|
32
|
+
// when the network is down would be worse than having no command.
|
|
33
|
+
export async function run(ctx) {
|
|
34
|
+
const sub = ctx.args.shift();
|
|
35
|
+
if (sub !== "refresh") throw new Error(t(ctx.locale, "usageKnownHostsRefresh"));
|
|
36
|
+
const knownHostsFlag = takeFlag(ctx.args, "known-hosts", "");
|
|
37
|
+
if (ctx.args.length !== 0) throw new Error(t(ctx.locale, "usageKnownHostsRefresh"));
|
|
38
|
+
|
|
39
|
+
const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
|
|
40
|
+
const fetchImpl = ctx.opts.fetchImpl ?? fetch;
|
|
41
|
+
const url = `${ctx.auth.apiBase}/.well-known/ssh-known-hosts`;
|
|
42
|
+
const published = await fetchPublishedKnownHosts({ apiBase: ctx.auth.apiBase, fetchImpl });
|
|
43
|
+
if (!published.ok) {
|
|
44
|
+
throw new Error(t(ctx.locale, published.invalid ? "cloneKnownHostsInvalid" : "cloneKnownHostsUnavailable", {
|
|
45
|
+
url,
|
|
46
|
+
status: published.status ?? "?",
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
writePinnedKnownHosts(knownHostsPath, published.pattern, published.line);
|
|
50
|
+
const fingerprint = fingerprintOf(published.line);
|
|
51
|
+
|
|
52
|
+
// Writing the file is not the goal; the goal is that this repo's next push
|
|
53
|
+
// reads it. Those differ silently, and the difference only shows up on
|
|
54
|
+
// rotation day (#595), so the check belongs here rather than in a runbook.
|
|
55
|
+
//
|
|
56
|
+
// An explicit --known-hosts is exempt: it names one file on purpose, often a
|
|
57
|
+
// scratch one, and "this repo does not read it" is then a statement of the
|
|
58
|
+
// obvious that would break scripted use. STAMP_KNOWN_HOSTS is not exempt —
|
|
59
|
+
// that is where an agent says its canonical file lives, so it is exactly the
|
|
60
|
+
// case worth checking.
|
|
61
|
+
const probe = knownHostsFlag
|
|
62
|
+
// Skipped, not unknown-for-lack-of-a-repository. Carrying its own reason
|
|
63
|
+
// matters: the shared `{ known: false }` shape previously fell through to
|
|
64
|
+
// "not inside a git repository", which is a plain falsehood when the user
|
|
65
|
+
// ran this inside one (飞牛, reviewing #610).
|
|
66
|
+
? { known: false, skippedReason: "knownHostsUncheckedExplicitPath" }
|
|
67
|
+
: probeRepoKnownHosts({
|
|
68
|
+
cwd: ctx.opts.cwd ?? process.cwd(),
|
|
69
|
+
pattern: published.pattern,
|
|
70
|
+
execImpl: ctx.opts.sshProbeExec,
|
|
71
|
+
});
|
|
72
|
+
// Three states, not two. Treating "could not answer" as agreement was right
|
|
73
|
+
// about the exit code and wrong about the output: it made an unrunnable probe
|
|
74
|
+
// print exactly what success prints, so a reader who saw no complaint
|
|
75
|
+
// concluded their repository was aligned (#610, found by cross).
|
|
76
|
+
//
|
|
77
|
+
// That matters here more than anywhere: this command exists so nobody has to
|
|
78
|
+
// disable host key checking, and the person who runs it, sees a clean result
|
|
79
|
+
// and believes they are ready is precisely the person who cannot push on
|
|
80
|
+
// rotation day and reaches for StrictHostKeyChecking=no.
|
|
81
|
+
//
|
|
82
|
+
// The exit code still only distinguishes "misaligned" from everything else —
|
|
83
|
+
// that direction is unchanged, because a false failure sends a correctly
|
|
84
|
+
// configured agent looking for something to change.
|
|
85
|
+
const alignment = !probe.known
|
|
86
|
+
? "unknown"
|
|
87
|
+
: knownHostsIsUsedBy(probe.effective, knownHostsPath) ? "aligned" : "elsewhere";
|
|
88
|
+
|
|
89
|
+
ctx.emit({
|
|
90
|
+
path: knownHostsPath,
|
|
91
|
+
pattern: published.pattern,
|
|
92
|
+
fingerprint,
|
|
93
|
+
// Reported per repository, never per machine: one agent can have a
|
|
94
|
+
// configured clone and an unconfigured one side by side.
|
|
95
|
+
repoUsesThisFile: probe.known ? alignment === "aligned" : null,
|
|
96
|
+
repoEffectiveKnownHosts: probe.known ? probe.effective.raw : null,
|
|
97
|
+
}, () => {
|
|
98
|
+
ctx.out(t(ctx.locale, "knownHostsRefreshed", { path: knownHostsPath, pattern: published.pattern, fingerprint }));
|
|
99
|
+
if (alignment === "elsewhere") {
|
|
100
|
+
ctx.err(t(ctx.locale, probe.configured ? "knownHostsRepoElsewhere" : "knownHostsRepoUnconfigured", {
|
|
101
|
+
written: knownHostsPath,
|
|
102
|
+
effective: probe.effective.raw,
|
|
103
|
+
sshCommand: sshCommandFor({
|
|
104
|
+
identityPath: resolveIdentityPath(ctx.env, ""),
|
|
105
|
+
knownHostsPath,
|
|
106
|
+
}),
|
|
107
|
+
}));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (alignment === "unknown") {
|
|
111
|
+
// Says which check did not happen, not just that something is unknown:
|
|
112
|
+
// "could not confirm" with no reason reads as a glitch and gets ignored.
|
|
113
|
+
ctx.out(t(ctx.locale, "knownHostsRepoUnchecked", {
|
|
114
|
+
written: knownHostsPath,
|
|
115
|
+
// Explicit skip first: it is the only case that knows why on its own.
|
|
116
|
+
// The other two are distinguished by whether we got far enough to ask
|
|
117
|
+
// the repository anything at all.
|
|
118
|
+
reason: t(ctx.locale, probe.skippedReason
|
|
119
|
+
?? (probe.inRepo ? "knownHostsUncheckedProbe" : "knownHostsUncheckedNoRepo")),
|
|
120
|
+
}));
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
// Aligned — and the caveat rides here too. It was already written, but only
|
|
124
|
+
// in the unconfigured branch, which is the one branch a correctly set up
|
|
125
|
+
// reader never reaches (#610). Same error as #607: the qualifier existed
|
|
126
|
+
// somewhere other than where the reader stops.
|
|
127
|
+
ctx.out(t(ctx.locale, "knownHostsRepoAligned", { effective: probe.effective.raw }));
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// A repo that reads somewhere else did not get refreshed, whatever the exit
|
|
131
|
+
// code of the write says. Silence here is what lets someone believe they are
|
|
132
|
+
// ready for the rotation.
|
|
133
|
+
//
|
|
134
|
+
// Every other outcome exits 0, including a probe that could not run: this
|
|
135
|
+
// command exists to stop people from disabling host key checking, so telling
|
|
136
|
+
// a correctly configured agent that it has a problem is the worse error. It
|
|
137
|
+
// also cannot see a per-invocation GIT_SSH_COMMAND at all, which the
|
|
138
|
+
// unconfigured message says outright rather than implying coverage.
|
|
139
|
+
// Only "elsewhere" is a failure. "unknown" stays 0 deliberately: the check
|
|
140
|
+
// could not run, and turning that into a non-zero exit would send a correctly
|
|
141
|
+
// configured agent hunting for a problem — the direction this command must
|
|
142
|
+
// never fail in. The distinction now lives in the output instead of vanishing.
|
|
143
|
+
return ctx.exit(alignment === "elsewhere" ? 1 : 0);
|
|
144
|
+
}
|
package/lib/commands/pr.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { ApiError, NetworkError } from "../client.mjs";
|
|
|
3
3
|
import { AgentError, printGatewayError } from "../errors.mjs";
|
|
4
4
|
import { pullRequestInput, pullRequestRecovery } from "../pr/create.mjs";
|
|
5
5
|
import { parsePRCommentArgs, validatePRCommentResult } from "../pr/comment.mjs";
|
|
6
|
+
import { formatPRReview, reviewBrief } from "../pr/review.mjs";
|
|
6
7
|
import { parsePRApproveArgs, parsePRMergeArgs, validatePRApproveResult, validatePRMergeResult } from "../pr/write.mjs";
|
|
7
8
|
import {
|
|
8
9
|
formatPRChecks,
|
|
@@ -129,11 +130,29 @@ export async function run(ctx) {
|
|
|
129
130
|
for (const line of formatPRDetail(d, {
|
|
130
131
|
head: t(locale, "prHeadLabel"),
|
|
131
132
|
checks: t(locale, "prChecksLabel"),
|
|
133
|
+
ciUnreadable: t(locale, "prCIUnreadable"),
|
|
132
134
|
review: t(locale, "prReviewLabel"),
|
|
133
135
|
})) out(line);
|
|
134
136
|
});
|
|
135
137
|
return exit(0);
|
|
136
138
|
}
|
|
139
|
+
if (sub === "review") {
|
|
140
|
+
const target = parsePRTargetArgs(args, "usagePrReview");
|
|
141
|
+
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
142
|
+
const brief = reviewBrief(d);
|
|
143
|
+
emit(brief, () => {
|
|
144
|
+
for (const line of formatPRReview(brief, (key) => t(locale, key))) out(line);
|
|
145
|
+
});
|
|
146
|
+
// Stays exit 0 even when the CI rollup is unreadable, and that is a
|
|
147
|
+
// decision rather than an omission (飞牛 raised it). `pr checks` is a gate
|
|
148
|
+
// answering "is this green?", so it fails closed; `pr review` is a fetch
|
|
149
|
+
// answering "give me the brief", and the fetch succeeded. Failing it here
|
|
150
|
+
// would conflate "I could not build the brief" with "the brief says CI is
|
|
151
|
+
// unknown", and would break callers that use it to obtain a brief at all.
|
|
152
|
+
// The unreadability travels in the brief itself -- printed in the text and
|
|
153
|
+
// carried as `ciUnreadable` in --json, which is purely additive.
|
|
154
|
+
return exit(0);
|
|
155
|
+
}
|
|
137
156
|
if (sub === "diff") {
|
|
138
157
|
const target = parsePRDiffArgs(args);
|
|
139
158
|
const d = validatePRDiff(await api("GET", prDiffPath(target)), target);
|
|
@@ -148,8 +167,20 @@ export async function run(ctx) {
|
|
|
148
167
|
const target = parsePRTargetArgs(args, "usagePrChecks");
|
|
149
168
|
const d = validatePRDetail(await api("GET", prDetailPath(target)), target);
|
|
150
169
|
emit(d.checks, () => {
|
|
170
|
+
// BOUNDARY, deliberately not fixed here: `--json` emits the checks ARRAY,
|
|
171
|
+
// which has nowhere to put "the source was refused" -- an agent parsing
|
|
172
|
+
// stdout sees `[]` for both "no CI" and "could not read CI". Widening it
|
|
173
|
+
// to an object would break every agent that parses an array, which is the
|
|
174
|
+
// same compatibility trap as adding a ciStatus value, so the contract is:
|
|
175
|
+
// **the exit code is authoritative for --json callers, and `pr view
|
|
176
|
+
// --json` carries ciUnreadable if you need the reason.** Said out loud
|
|
177
|
+
// rather than left for the next person to discover (飞牛, cross).
|
|
151
178
|
const lines = formatPRChecks(d);
|
|
152
|
-
|
|
179
|
+
// "No checks reported." is the same lie as CI:none, just where a person
|
|
180
|
+
// reads it rather than in a column. An empty list because the source was
|
|
181
|
+
// refused must not borrow the sentence meant for a repo that has no CI.
|
|
182
|
+
if (d.ciUnreadable) out(t(locale, "prChecksUnreadable"));
|
|
183
|
+
else if (lines.length === 0) out(t(locale, "prChecksEmpty"));
|
|
153
184
|
else for (const line of lines) out(line);
|
|
154
185
|
});
|
|
155
186
|
return exit(prChecksExitCode(d));
|
package/lib/commands/receipt.mjs
CHANGED
|
@@ -5,6 +5,12 @@ export async function run(ctx) {
|
|
|
5
5
|
const id = ctx.args.shift();
|
|
6
6
|
if (sub !== "get" || !id) throw new Error(t(ctx.locale, "usageReceiptGet"));
|
|
7
7
|
const d = await ctx.api("GET", `/v1/receipts/${encodeURIComponent(id)}`);
|
|
8
|
-
ctx.emit(d, () =>
|
|
8
|
+
ctx.emit(d, () => {
|
|
9
|
+
let line = `${d.id} ${d.status} ${d.repository} ${d.targetRef} published=${d.publishedSha ?? "-"}`;
|
|
10
|
+
if (d.publishAttempts) line += ` attempts=${d.publishAttempts}`;
|
|
11
|
+
if (d.nextRetryAt) line += ` nextRetry=${d.nextRetryAt}`;
|
|
12
|
+
ctx.out(line);
|
|
13
|
+
if (d.lastError) ctx.out(` last error: ${d.lastError}`);
|
|
14
|
+
});
|
|
9
15
|
return ctx.exit(0);
|
|
10
16
|
}
|
package/lib/commands/repo.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import { existsSync } from "node:fs";
|
|
|
2
2
|
import { t } from "../locale.mjs";
|
|
3
3
|
import { takeFlag } from "../flags.mjs";
|
|
4
4
|
import { gatewayCloneURL, parseRepoCloneArgs, parseRepository, runGitClone, runGitSetSSHCommand } from "../repo/clone.mjs";
|
|
5
|
-
import { fetchPublishedKnownHosts,
|
|
5
|
+
import { fetchPublishedKnownHosts, resolveIdentity, resolveKnownHostsPath, sshCommandFor, writePinnedKnownHosts } from "../repo/ssh.mjs";
|
|
6
|
+
import { readRecordedIdentity } from "../repo/identities.mjs";
|
|
6
7
|
|
|
7
8
|
export async function run(ctx) {
|
|
8
9
|
if (ctx.args.shift() !== "clone") throw new Error(t(ctx.locale, "usageRepoClone"));
|
|
@@ -18,9 +19,13 @@ export async function run(ctx) {
|
|
|
18
19
|
// The clone carries the enrolled identity and the gateway's published host
|
|
19
20
|
// key itself (task #475): a bare clone must not fail with publickey, and it
|
|
20
21
|
// must not need a hand-exported GIT_SSH_COMMAND.
|
|
21
|
-
const
|
|
22
|
+
const recorded = readRecordedIdentity(ctx.env, ctx.auth.apiBase);
|
|
23
|
+
const { identityPath, source } = resolveIdentity(ctx.env, identityFlag, recorded);
|
|
22
24
|
if (!existsSync(identityPath)) {
|
|
23
|
-
|
|
25
|
+
// The recorded key is not on this machine (or moved): say which record
|
|
26
|
+
// pointed there, so the fix is `key enroll` here or --identity, not a
|
|
27
|
+
// search of ~/.ssh (task #514: never scan).
|
|
28
|
+
throw new Error(t(ctx.locale, source === "enrolled" ? "cloneEnrolledIdentityMissing" : "cloneIdentityMissing", { path: identityPath, origin: ctx.auth.apiBase }));
|
|
24
29
|
}
|
|
25
30
|
const knownHostsPath = resolveKnownHostsPath(ctx.env, knownHostsFlag);
|
|
26
31
|
const fetchImpl = ctx.opts.fetchImpl ?? fetch;
|
|
@@ -54,9 +59,16 @@ export async function run(ctx) {
|
|
|
54
59
|
const directory = parsed.directory ?? repo.name;
|
|
55
60
|
const pinned = await (ctx.opts.gitConfigImpl ?? runGitSetSSHCommand)({ directory, sshCommand });
|
|
56
61
|
ctx.emit(
|
|
57
|
-
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshPinned: pinned.ok },
|
|
62
|
+
{ ok: true, repository: `${repo.owner}/${repo.name}`, url, directory, sshIdentity: identityPath, sshIdentitySource: source, sshPinned: pinned.ok },
|
|
58
63
|
() => {
|
|
59
64
|
ctx.out(t(ctx.locale, "cloned", { repository: `${repo.owner}/${repo.name}`, url }));
|
|
65
|
+
// The commit rules this gateway enforces, stated once up front (task #549):
|
|
66
|
+
// a pusher should not meet them for the first time as a refusal.
|
|
67
|
+
if (me.commitTrailers && (me.commitTrailers.signedOffBy || me.commitTrailers.coauthoredBy)) {
|
|
68
|
+
ctx.out(t(ctx.locale, "cloneCommitTrailers"));
|
|
69
|
+
if (me.commitTrailers.signedOffBy) ctx.out(` ${me.commitTrailers.signedOffBy}`);
|
|
70
|
+
if (me.commitTrailers.coauthoredBy) ctx.out(` ${me.commitTrailers.coauthoredBy}`);
|
|
71
|
+
}
|
|
60
72
|
ctx.out(pinned.ok
|
|
61
73
|
? t(ctx.locale, "cloneIdentityPinned", { directory })
|
|
62
74
|
: t(ctx.locale, "cloneIdentityPinFailed", { directory, command: sshCommand }));
|
package/lib/locale.mjs
CHANGED
|
@@ -2,7 +2,14 @@
|
|
|
2
2
|
export const messages = {
|
|
3
3
|
en: {
|
|
4
4
|
usagePrCreate: "usage: {cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
5
|
-
usagePrRead: "usage: {cli} pr <list|view|diff|checks|comment|approve|merge> [arguments]",
|
|
5
|
+
usagePrRead: "usage: {cli} pr <list|view|review|diff|checks|comment|approve|merge> [arguments]",
|
|
6
|
+
usagePrReview: "usage: {cli} pr review <number|URL> [--repo OWNER/REPO] — the exact head to pin, base, merge-base, checks, and the diff/patch-id commands against the merge-base",
|
|
7
|
+
prReviewExactHead: "Exact head",
|
|
8
|
+
prReviewBase: "Base",
|
|
9
|
+
prReviewMergeBase: "Merge-base",
|
|
10
|
+
prReviewMergeBaseRule: "log, stat, diff and patch-id against the merge-base, never against the current base: the base branch may have advanced since this branch forked, and those commits would show up as the PR's",
|
|
11
|
+
prReviewCommands: "Local review (after cloning through Stamp)",
|
|
12
|
+
prReviewVerdict: "Verdict to post",
|
|
6
13
|
usagePrApprove: "usage: {cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT] (human GitHub identity required)",
|
|
7
14
|
usagePrMerge: "usage: {cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase] (human GitHub identity required)",
|
|
8
15
|
prApproved: "Approved {repository}#{number} as {actor}",
|
|
@@ -14,10 +21,11 @@ export const messages = {
|
|
|
14
21
|
apiHumanPrincipal: "Agents cannot approve or merge. Use a human STAMP_TOKEN session.",
|
|
15
22
|
apiWriteCoords: "Re-read the PR and retry with both --head and --base.",
|
|
16
23
|
apiGitHubBinding: "Bind your GitHub account in Stamp settings, then retry.",
|
|
17
|
-
usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) (human GitHub identity
|
|
24
|
+
usagePrComment: "usage: {cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) [--expected-head SHA] (a human posts as their bound GitHub identity; an agent posts as the Stamp App with an attribution line naming the agent; with --expected-head the comment is refused if the pull request has moved)",
|
|
25
|
+
prCommentExpectedHeadInvalid: "--expected-head must be the full 40-character commit SHA you reviewed.",
|
|
18
26
|
prCommentBodyInvalid: "Comment must be nonempty and at most 64 KiB of UTF-8 text.",
|
|
19
27
|
prCommentCreated: "Comment posted as {actor}: {url}",
|
|
20
|
-
prCommentRejected: "Comment request was rejected. Check your
|
|
28
|
+
prCommentRejected: "Comment request was rejected. Check your session, GitHub binding (humans), repository access and input.",
|
|
21
29
|
prCommentOutcomeUnknown: "Comment outcome is unknown. Check the PR comments before sending again; do not automatically resend.",
|
|
22
30
|
usagePrList: "usage: {cli} pr list",
|
|
23
31
|
usagePrView: "usage: {cli} pr view <number|URL> [--repo OWNER/REPO]",
|
|
@@ -35,6 +43,9 @@ export const messages = {
|
|
|
35
43
|
prDiffUnavailable: "patch unavailable",
|
|
36
44
|
prDiffEmpty: "No changed files reported.",
|
|
37
45
|
prChecksEmpty: "No checks reported.",
|
|
46
|
+
prChecksUnreadable: "Checks could not be read for this pull request, so this is not \"no checks\" — the gateway was refused by GitHub (most often a missing Checks permission on the app). Treat CI as unknown.",
|
|
47
|
+
prCIUnreadable: "unreadable",
|
|
48
|
+
prVerdictCIUnreadable: "CI unreadable — not evidence of green",
|
|
38
49
|
prReadNotFound: "Check the repository and PR number, and confirm this Agent created the PR through Stamp.",
|
|
39
50
|
prReadHeadMoved: "The PR head changed while Stamp read the diff; rerun the command and review the new head.",
|
|
40
51
|
prReadDiffIncomplete: "GitHub did not return the complete PR diff; retry later instead of relying on partial files.",
|
|
@@ -77,8 +88,12 @@ export const messages = {
|
|
|
77
88
|
{cli} whoami who the gateway thinks you are
|
|
78
89
|
{cli} migration-help old manifest actions → CLI mapping
|
|
79
90
|
{cli} key enroll [--public-key FILE|-] bind this agent's SSH public key (default ~/.ssh/id_ed25519.pub)
|
|
91
|
+
{cli} key list list this agent's enrolled SSH keys
|
|
92
|
+
{cli} key revoke KEY_ID revoke one of this agent's enrolled keys
|
|
93
|
+
{cli} known-hosts refresh re-pin this instance's SSH host key from /.well-known
|
|
80
94
|
{cli} identity bind --email ADDR bind commit-author email (DCO)
|
|
81
95
|
{cli} receipt get <id> gateway acceptance + GitHub publication status
|
|
96
|
+
{cli} changelog [--limit N] [--all] release history: CLI/API changes per version (--all: everything)
|
|
82
97
|
{cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
83
98
|
{cli} pr list
|
|
84
99
|
{cli} pr view <number|URL> --repo OWNER/REPO
|
|
@@ -102,12 +117,23 @@ export const messages = {
|
|
|
102
117
|
flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance), STAMP_SERVICE, STAMP_LANG`,
|
|
103
118
|
usageRepoClone: "usage: {cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
|
|
104
119
|
cloned: "Cloned {repository} from {url}",
|
|
120
|
+
cloneCommitTrailers: "Every commit you push here must end with these trailers, as one block at the very end with no blank line between them (GitHub only reads the last contiguous block):",
|
|
105
121
|
cloneFailed: "clone of {repository} via the Stamp gateway failed",
|
|
106
122
|
networkUnreachable: "could not reach {base} ({cause}); check the instance address (STAMP_URL) and your network, then retry",
|
|
107
123
|
networkHostUnresolved: "{base} does not resolve ({cause}); check the instance address (STAMP_URL) and DNS, then retry",
|
|
108
124
|
cloneIdentityMissing: "no SSH private key at {path}: enroll one with `{cli} key enroll` (it reads {path}.pub), or point at an existing key with --identity FILE",
|
|
125
|
+
cloneEnrolledIdentityMissing: "the key `{cli} key enroll` recorded for {origin} is not at {path} on this machine: run `{cli} key enroll` here, or point at the key with --identity FILE",
|
|
109
126
|
cloneKnownHostsUnavailable: "{url} returned HTTP {status}: this instance does not publish its SSH host key, so there is nothing to pin — pass --known-hosts FILE, or set STAMP_KNOWN_HOSTS",
|
|
110
127
|
cloneKnownHostsInvalid: "{url} did not return a usable known_hosts line; refusing to pin it — check the instance, or pass --known-hosts FILE",
|
|
128
|
+
usageKnownHostsRefresh: "usage: known-hosts refresh [--known-hosts FILE]",
|
|
129
|
+
knownHostsRefreshed: "pinned {pattern} in {path}\n{fingerprint}",
|
|
130
|
+
knownHostsRepoAligned: "this repository reads that file\n note: a GIT_SSH_COMMAND set in the environment you push from overrides this and cannot be seen from here, so this does not vouch for the next push",
|
|
131
|
+
knownHostsRepoUnchecked: "could not confirm whether this repository reads the file that was just refreshed\n refreshed: {written}\n {reason}\nthis is not a failure and not a confirmation: treat the repository as unchecked",
|
|
132
|
+
knownHostsUncheckedNoRepo: "not inside a git repository, so there is no repository configuration to ask",
|
|
133
|
+
knownHostsUncheckedExplicitPath: "--known-hosts named this file explicitly, so no repository was checked against it",
|
|
134
|
+
knownHostsUncheckedProbe: "the repository's ssh command could not be run, so its effective known_hosts is unknown",
|
|
135
|
+
knownHostsRepoElsewhere: "this repository does not read the file that was just refreshed\n refreshed: {written}\n this repository reads: {effective}\nuntil they agree, refreshing does nothing for pushes from here; set core.sshCommand in this repository:\n git config core.sshCommand \"{sshCommand}\"",
|
|
136
|
+
knownHostsRepoUnconfigured: "this repository has no core.sshCommand, so it does not read the file that was just refreshed\n refreshed: {written}\n this repository reads: {effective}\nit connects through ssh's own configuration, or through a GIT_SSH_COMMAND set for each push, which this command cannot see and cannot vouch for; set core.sshCommand in this repository:\n git config core.sshCommand \"{sshCommand}\"",
|
|
111
137
|
clonePublicKeyRejected: "the gateway rejected the key at {path} (publickey). If it is not enrolled yet, enroll its public half: `{cli} key enroll --public-key {publicKey}`",
|
|
112
138
|
cloneIdentityPinned: "pinned the Stamp SSH identity for {directory} (git config core.sshCommand)",
|
|
113
139
|
cloneIdentityPinFailed: "could not write the SSH identity into {directory}; run it yourself: git -C {directory} config --local core.sshCommand \"{command}\"",
|
|
@@ -119,10 +145,25 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
119
145
|
logoutForgot: "forgot agent session {path}",
|
|
120
146
|
logoutNothing: "nothing stored (human/CI lane uses STAMP_TOKEN)",
|
|
121
147
|
enrolled: "enrolled {fingerprint} ({keyId})",
|
|
148
|
+
enrolledIdentityRecorded: "`{cli} repo clone` on this machine will use {path}",
|
|
149
|
+
enrolledIdentityNotRecorded: "the private key {path} is not on this machine, so `{cli} repo clone` here will need --identity FILE",
|
|
122
150
|
bound: "bound {email}",
|
|
123
151
|
usageKeyEnroll: "usage: {cli} key enroll [--public-key FILE|-]",
|
|
152
|
+
usageKeyList: "usage: {cli} key list",
|
|
153
|
+
usageKeyRevoke: "usage: {cli} key revoke KEY_ID",
|
|
154
|
+
keyListEmpty: "no enrolled keys",
|
|
155
|
+
keyRevoked: "revoked {keyId}",
|
|
124
156
|
usageIdentityBind: "usage: {cli} identity bind --email ADDR",
|
|
125
157
|
usageReceiptGet: "usage: {cli} receipt get <receipt-id>",
|
|
158
|
+
usageChangelog: "usage: {cli} changelog [--limit N] [--all]",
|
|
159
|
+
changelogScopeAgent: "Showing CLI and API changes; --all shows everything.",
|
|
160
|
+
changelogScopeAll: "Showing every change, including the web app and internal work.",
|
|
161
|
+
changelogNoneForAgents: "no CLI or API changes in this release ({hidden} other; --all shows them)",
|
|
162
|
+
changelogHiddenCount: "({hidden} other change(s) hidden; --all shows them)",
|
|
163
|
+
changelogBuild: "Gateway build {version} ({commit})",
|
|
164
|
+
changelogEmpty: "No releases recorded in this build.",
|
|
165
|
+
changelogNoEntries: "no pull requests recorded",
|
|
166
|
+
changelogCurrentMark: "<- running",
|
|
126
167
|
usageFollow: "usage: {cli} <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
|
|
127
168
|
usageSubscription: "usage: {cli} subscription pause|resume <owner/repo> --kind issue|pull --number N",
|
|
128
169
|
usageWatch: "usage: {cli} {cmd} <owner/repo> --event TYPE",
|
|
@@ -181,7 +222,14 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
181
222
|
},
|
|
182
223
|
"zh-CN": {
|
|
183
224
|
usagePrCreate: "用法:{cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]",
|
|
184
|
-
usagePrRead: "用法:{cli} pr <list|view|diff|checks|comment|approve|merge> [参数]",
|
|
225
|
+
usagePrRead: "用法:{cli} pr <list|view|review|diff|checks|comment|approve|merge> [参数]",
|
|
226
|
+
usagePrReview: "用法:{cli} pr review <编号|URL> [--repo OWNER/REPO] —— 要钉的 exact head、base、merge-base、检查,以及对 merge-base 做 diff/patch-id 的命令",
|
|
227
|
+
prReviewExactHead: "Exact head",
|
|
228
|
+
prReviewBase: "Base",
|
|
229
|
+
prReviewMergeBase: "Merge-base",
|
|
230
|
+
prReviewMergeBaseRule: "log/stat/diff/patch-id 一律对 merge-base,不要对当前 base:base 分支可能在分叉后已前进,那些提交会被当成这张 PR 的",
|
|
231
|
+
prReviewCommands: "本地复核(经 Stamp clone 之后)",
|
|
232
|
+
prReviewVerdict: "要贴的判词",
|
|
185
233
|
usagePrApprove: "用法:{cli} pr approve <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--body TEXT](需要本人 GitHub 身份)",
|
|
186
234
|
usagePrMerge: "用法:{cli} pr merge <NUMBER -R OWNER/REPO|PR_URL> --head SHA --base SHA [--method merge|squash|rebase](需要本人 GitHub 身份)",
|
|
187
235
|
prApproved: "已以 {actor} 身份批准 {repository}#{number}",
|
|
@@ -193,10 +241,11 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
193
241
|
apiHumanPrincipal: "Agent 不能批准或合并。请使用绑定了 GitHub 的人类 STAMP_TOKEN 会话。",
|
|
194
242
|
apiWriteCoords: "请重读 PR,带上当前的 --head 和 --base 再试。",
|
|
195
243
|
apiGitHubBinding: "请先在 Stamp 设置里绑定 GitHub,再重试。",
|
|
196
|
-
usagePrComment: "用法:{cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-)
|
|
244
|
+
usagePrComment: "用法:{cli} pr comment <NUMBER -R OWNER/REPO|PR_URL> (--body TEXT|--body-file FILE|-) [--expected-head SHA](人类以本人绑定的 GitHub 身份发表;agent 以 Stamp App 身份发表并附带署名行;带 --expected-head 时 PR 的 head 变了就拒绝发表)",
|
|
245
|
+
prCommentExpectedHeadInvalid: "--expected-head 必须是你复核过的完整 40 位 commit SHA。",
|
|
197
246
|
prCommentBodyInvalid: "评论不能为空,UTF-8 文本最多 64 KiB。",
|
|
198
247
|
prCommentCreated: "已以 {actor} 身份发表评论:{url}",
|
|
199
|
-
prCommentRejected: "
|
|
248
|
+
prCommentRejected: "评论请求被拒绝,请检查会话、GitHub 绑定(人类)、仓库权限和输入。",
|
|
200
249
|
prCommentOutcomeUnknown: "评论结果不明。请先查看 PR 评论,不要自动重发。",
|
|
201
250
|
usagePrList: "用法:{cli} pr list",
|
|
202
251
|
usagePrView: "用法:{cli} pr view <编号|URL> [--repo OWNER/REPO]",
|
|
@@ -214,6 +263,9 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
214
263
|
prDiffUnavailable: "patch 不可用",
|
|
215
264
|
prDiffEmpty: "没有变更文件。",
|
|
216
265
|
prChecksEmpty: "没有检查记录。",
|
|
266
|
+
prChecksUnreadable: "无法读取这个 PR 的检查结果,所以这不是\"没有检查\"——网关被 GitHub 拒绝了(通常是 App 缺少 Checks 权限)。请把 CI 当作未知。",
|
|
267
|
+
prCIUnreadable: "无法读取",
|
|
268
|
+
prVerdictCIUnreadable: "CI 无法读取——不能当作已通过",
|
|
217
269
|
prReadNotFound: "请检查仓库和 PR 编号,并确认该 PR 是此 Agent 通过 Stamp 创建的。",
|
|
218
270
|
prReadHeadMoved: "Stamp 读取 diff 时 PR head 已变化;请重新运行命令并审阅新的 head。",
|
|
219
271
|
prReadDiffIncomplete: "GitHub 未返回完整的 PR diff;请稍后重试,不要依赖部分文件。",
|
|
@@ -256,8 +308,12 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
256
308
|
{cli} whoami 网关认为你是谁
|
|
257
309
|
{cli} migration-help 旧 manifest action → CLI 对照
|
|
258
310
|
{cli} key enroll [--public-key FILE|-] 绑定此 Agent 的 SSH 公钥(默认 ~/.ssh/id_ed25519.pub)
|
|
311
|
+
{cli} key list 列出此 Agent 已登记的 SSH 公钥
|
|
312
|
+
{cli} key revoke KEY_ID 撤销此 Agent 的一把已登记公钥
|
|
313
|
+
{cli} known-hosts refresh 从 /.well-known 重新钉住本实例的 SSH 主机公钥
|
|
259
314
|
{cli} identity bind --email ADDR 绑定提交作者邮箱(DCO)
|
|
260
315
|
{cli} receipt get <id> 网关接受与 GitHub 发表状态
|
|
316
|
+
{cli} changelog [--limit N] [--all] 更新日志:每个版本的命令行/接口变化(--all 看全部)
|
|
261
317
|
{cli} pr create --receipt ID --repo OWNER/REPO --head BRANCH --sha SHA --base BRANCH --title TITLE (--body TEXT|--body-file FILE|-) [--idempotency-key KEY]
|
|
262
318
|
{cli} pr list
|
|
263
319
|
{cli} pr view <编号|URL> --repo OWNER/REPO
|
|
@@ -281,12 +337,23 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN (human/CI), STAMP_URL (instance
|
|
|
281
337
|
flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、STAMP_SERVICE、STAMP_LANG`,
|
|
282
338
|
usageRepoClone: "用法:{cli} repo clone <repository> [<directory>] [--identity FILE] [--known-hosts FILE] [-- <gitflags>...]",
|
|
283
339
|
cloned: "已从 {url} 克隆 {repository}",
|
|
340
|
+
cloneCommitTrailers: "推到这里的每个 commit 末尾都要带这两行 trailer(连成一块放在最末尾,中间不要空行;GitHub 只认最后一个连续块):",
|
|
284
341
|
cloneFailed: "经 Stamp 网关克隆 {repository} 失败",
|
|
285
342
|
networkUnreachable: "无法连接 {base}({cause});检查实例地址(STAMP_URL)和网络后重试",
|
|
286
343
|
networkHostUnresolved: "{base} 解析不了({cause});检查实例地址(STAMP_URL)和 DNS 后重试",
|
|
287
344
|
cloneIdentityMissing: "{path} 没有 SSH 私钥:用 `{cli} key enroll` 登记一把(它读 {path}.pub),或用 --identity FILE 指到已有私钥",
|
|
345
|
+
cloneEnrolledIdentityMissing: "`{cli} key enroll` 为 {origin} 记录的私钥在这台机器上不在 {path}:在这里重新 `{cli} key enroll`,或用 --identity FILE 指到那把钥",
|
|
288
346
|
cloneKnownHostsUnavailable: "{url} 返回 HTTP {status}:这个实例没有发布自己的 SSH 主机公钥,没有可钉的东西——用 --known-hosts FILE 指定,或设 STAMP_KNOWN_HOSTS",
|
|
289
347
|
cloneKnownHostsInvalid: "{url} 返回的不是可用的 known_hosts 行;拒绝钉它——检查实例,或用 --known-hosts FILE",
|
|
348
|
+
usageKnownHostsRefresh: "用法:known-hosts refresh [--known-hosts FILE]",
|
|
349
|
+
knownHostsRefreshed: "已在 {path} 中钉住 {pattern}\n{fingerprint}",
|
|
350
|
+
knownHostsRepoAligned: "这个仓库会读取该文件\n 注意:推送所在环境里设置的 GIT_SSH_COMMAND 会覆盖它,而本命令看不到,因此这不能为下一次推送背书",
|
|
351
|
+
knownHostsRepoUnchecked: "未能确认这个仓库是否会读取刚刚刷新的那个文件\n 已刷新:{written}\n {reason}\n这既不是失败也不是确认:请把该仓库当作未检查",
|
|
352
|
+
knownHostsUncheckedNoRepo: "不在 git 仓库内,没有仓库配置可问",
|
|
353
|
+
knownHostsUncheckedExplicitPath: "--known-hosts 显式指定了这个文件,因此没有拿任何仓库去核对它",
|
|
354
|
+
knownHostsUncheckedProbe: "无法运行该仓库的 ssh 命令,因此它实际使用的 known_hosts 未知",
|
|
355
|
+
knownHostsRepoElsewhere: "这个仓库不会读取刚刚刷新的那个文件\n 已刷新:{written}\n 本仓库实际读取:{effective}\n两者不一致时,刷新对从这里发起的推送没有任何作用;请为本仓库设置 core.sshCommand:\n git config core.sshCommand \"{sshCommand}\"",
|
|
356
|
+
knownHostsRepoUnconfigured: "这个仓库没有设置 core.sshCommand,因此不会读取刚刚刷新的那个文件\n 已刷新:{written}\n 本仓库实际读取:{effective}\n它通过 ssh 自己的配置连接,或依赖每次推送临时设置的 GIT_SSH_COMMAND——后者本命令看不到,也无法为它背书;请为本仓库设置 core.sshCommand:\n git config core.sshCommand \"{sshCommand}\"",
|
|
290
357
|
clonePublicKeyRejected: "网关拒绝了 {path} 这把钥(publickey)。如果它还没登记,先登记它的公钥:`{cli} key enroll --public-key {publicKey}`",
|
|
291
358
|
cloneIdentityPinned: "已把 Stamp 的 SSH 身份钉到 {directory}(git config core.sshCommand)",
|
|
292
359
|
cloneIdentityPinFailed: "无法把 SSH 身份写入 {directory};可手动执行:git -C {directory} config --local core.sshCommand \"{command}\"",
|
|
@@ -298,10 +365,25 @@ flags: --json --lang en|zh-CN env: STAMP_TOKEN(人类/CI)、STAMP_URL、ST
|
|
|
298
365
|
logoutForgot: "已忘记 Agent 会话 {path}",
|
|
299
366
|
logoutNothing: "没有本地会话(人类/CI 通道使用 STAMP_TOKEN)",
|
|
300
367
|
enrolled: "已登记 {fingerprint}({keyId})",
|
|
368
|
+
enrolledIdentityRecorded: "这台机器上的 `{cli} repo clone` 会使用 {path}",
|
|
369
|
+
enrolledIdentityNotRecorded: "私钥 {path} 不在这台机器上,这里的 `{cli} repo clone` 需要 --identity FILE",
|
|
301
370
|
bound: "已绑定 {email}",
|
|
302
371
|
usageKeyEnroll: "用法:{cli} key enroll [--public-key FILE|-]",
|
|
372
|
+
usageKeyList: "用法:{cli} key list",
|
|
373
|
+
usageKeyRevoke: "用法:{cli} key revoke KEY_ID",
|
|
374
|
+
keyListEmpty: "没有已登记的公钥",
|
|
375
|
+
keyRevoked: "已撤销 {keyId}",
|
|
303
376
|
usageIdentityBind: "用法:{cli} identity bind --email ADDR",
|
|
304
377
|
usageReceiptGet: "用法:{cli} receipt get <receipt-id>",
|
|
378
|
+
usageChangelog: "用法:{cli} changelog [--limit N] [--all]",
|
|
379
|
+
changelogScopeAgent: "只显示命令行和接口的变化;--all 看全部。",
|
|
380
|
+
changelogScopeAll: "显示全部变化,包括网页端和内部改动。",
|
|
381
|
+
changelogNoneForAgents: "这个版本没有命令行或接口的变化(另有 {hidden} 项;--all 可看)",
|
|
382
|
+
changelogHiddenCount: "(隐藏了 {hidden} 项其他改动;--all 可看)",
|
|
383
|
+
changelogBuild: "网关构建 {version}({commit})",
|
|
384
|
+
changelogEmpty: "这个构建里没有版本记录。",
|
|
385
|
+
changelogNoEntries: "没有记录到 PR",
|
|
386
|
+
changelogCurrentMark: "<- 当前运行",
|
|
305
387
|
usageFollow: "用法:{cli} <follow|unfollow|subscription …> <owner/repo> --kind issue|pull --number N",
|
|
306
388
|
usageSubscription: "用法:{cli} subscription pause|resume <owner/repo> --kind issue|pull --number N",
|
|
307
389
|
usageWatch: "用法:{cli} {cmd} <owner/repo> --event TYPE",
|
package/lib/main.mjs
CHANGED
|
@@ -6,11 +6,13 @@ import { selectLocale, t, setCliName, prefix } from "./locale.mjs";
|
|
|
6
6
|
import { presentError, printGatewayError } from "./errors.mjs";
|
|
7
7
|
import * as session from "./commands/session.mjs";
|
|
8
8
|
import * as key from "./commands/key.mjs";
|
|
9
|
+
import * as knownhosts from "./commands/knownhosts.mjs";
|
|
9
10
|
import * as identity from "./commands/identity.mjs";
|
|
10
11
|
import * as receipt from "./commands/receipt.mjs";
|
|
11
12
|
import * as repo from "./commands/repo.mjs";
|
|
12
13
|
import * as pr from "./commands/pr.mjs";
|
|
13
14
|
import * as subscribe from "./commands/subscribe.mjs";
|
|
15
|
+
import * as changelog from "./commands/changelog.mjs";
|
|
14
16
|
|
|
15
17
|
const require = createRequire(import.meta.url);
|
|
16
18
|
const pkg = require("../package.json");
|
|
@@ -21,6 +23,7 @@ const commands = {
|
|
|
21
23
|
whoami: session.whoami,
|
|
22
24
|
"migration-help": session.migrationHelp,
|
|
23
25
|
key: key.run,
|
|
26
|
+
"known-hosts": knownhosts.run,
|
|
24
27
|
identity: identity.run,
|
|
25
28
|
receipt: receipt.run,
|
|
26
29
|
repo: repo.run,
|
|
@@ -31,6 +34,7 @@ const commands = {
|
|
|
31
34
|
subscriptions: subscribe.subscriptions,
|
|
32
35
|
watch: subscribe.watch,
|
|
33
36
|
unwatch: subscribe.watch,
|
|
37
|
+
changelog: changelog.run,
|
|
34
38
|
};
|
|
35
39
|
|
|
36
40
|
export async function main(argv, opts) {
|
|
@@ -39,7 +43,7 @@ export async function main(argv, opts) {
|
|
|
39
43
|
const err = opts.stderr ?? ((s) => console.error(s));
|
|
40
44
|
const env = opts.env ?? process.env;
|
|
41
45
|
const exit = opts.exit ?? ((code) => process.exit(code));
|
|
42
|
-
const localValues = new Set(["--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
|
|
46
|
+
const localValues = new Set(["--limit", "--public-key", "--email", "--identity", "--known-hosts", "--kind", "--number", "--event", "--receipt", "--repo", "--head", "--sha", "--base", "--title", "--body", "--body-file", "--idempotency-key", "--method", "-b", "-F", "-R"]);
|
|
43
47
|
let json = false, langFlag, help = false, version = false;
|
|
44
48
|
const commandArgs = [];
|
|
45
49
|
for (let i = 0; i < args.length; i++) {
|
package/lib/pr/comment.mjs
CHANGED
|
@@ -6,7 +6,7 @@ export function parsePRCommentArgs(input) {
|
|
|
6
6
|
const targetArgs = [], flags = new Map();
|
|
7
7
|
for (let i = 0; i < input.length; i++) {
|
|
8
8
|
const arg = input[i];
|
|
9
|
-
const match = arg.match(/^(--body|--body-file)(?:=(.*))?$/s);
|
|
9
|
+
const match = arg.match(/^(--body|--body-file|--expected-head)(?:=(.*))?$/s);
|
|
10
10
|
const name = match?.[1] ?? ({ "-b": "--body", "-F": "--body-file" })[arg];
|
|
11
11
|
if (!name) { targetArgs.push(arg); continue; }
|
|
12
12
|
if (flags.has(name)) throw new AgentError("usagePrComment");
|
|
@@ -15,7 +15,10 @@ export function parsePRCommentArgs(input) {
|
|
|
15
15
|
flags.set(name, value);
|
|
16
16
|
}
|
|
17
17
|
const target = parsePRTargetArgs(targetArgs, "usagePrComment");
|
|
18
|
+
const expectedHead = flags.get("--expected-head");
|
|
19
|
+
flags.delete("--expected-head");
|
|
18
20
|
if (flags.size !== 1) throw new AgentError("usagePrComment");
|
|
21
|
+
if (expectedHead !== undefined && !/^[0-9a-fA-F]{40}$/.test(expectedHead)) throw new AgentError("prCommentExpectedHeadInvalid");
|
|
19
22
|
let body = flags.get("--body");
|
|
20
23
|
if (flags.has("--body-file")) {
|
|
21
24
|
const file = flags.get("--body-file");
|
|
@@ -23,7 +26,9 @@ export function parsePRCommentArgs(input) {
|
|
|
23
26
|
catch { throw new AgentError("prBodyRead"); }
|
|
24
27
|
}
|
|
25
28
|
if (!body?.trim() || Buffer.byteLength(body, "utf8") > 65536) throw new AgentError("prCommentBodyInvalid");
|
|
26
|
-
|
|
29
|
+
const request = { body };
|
|
30
|
+
if (expectedHead !== undefined) request.expectedHead = expectedHead.toLowerCase();
|
|
31
|
+
return { target, path: `${prDetailPath(target)}/comments`, body: request };
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
export function validatePRCommentResult(result, target) {
|
|
@@ -31,7 +36,7 @@ export function validatePRCommentResult(result, target) {
|
|
|
31
36
|
const valid = result && typeof result === "object" && !Array.isArray(result)
|
|
32
37
|
&& typeof result.repository === "string" && result.repository.toLowerCase() === expectedRepo.toLowerCase()
|
|
33
38
|
&& result.number === target.number && Number.isSafeInteger(result.commentId) && result.commentId > 0
|
|
34
|
-
&& typeof result.actorLogin === "string" && /^[A-Za-z0-9-]
|
|
39
|
+
&& typeof result.actorLogin === "string" && /^[A-Za-z0-9-]+(\[bot\])?$/.test(result.actorLogin)
|
|
35
40
|
&& typeof result.url === "string"
|
|
36
41
|
&& result.url.toLowerCase() === `https://github.com/${expectedRepo}/pull/${target.number}#issuecomment-${result.commentId}`.toLowerCase();
|
|
37
42
|
if (!valid) throw new AgentError("prCommentOutcomeUnknown");
|
package/lib/pr/read.mjs
CHANGED
|
@@ -239,6 +239,12 @@ export function validatePRDetail(value, expected) {
|
|
|
239
239
|
requireString(detail.headRef);
|
|
240
240
|
requireString(detail.baseRef);
|
|
241
241
|
if (!ciStatuses.has(requireString(detail.ciStatus))) throw new AgentError("prReadInvalidResponse");
|
|
242
|
+
// Optional: absent means the CI sources were actually read. Validated rather
|
|
243
|
+
// than ignored so a malformed value is caught here instead of silently
|
|
244
|
+
// deciding an exit code further down.
|
|
245
|
+
if (detail.ciUnreadable !== undefined && typeof detail.ciUnreadable !== "boolean") {
|
|
246
|
+
throw new AgentError("prReadInvalidResponse");
|
|
247
|
+
}
|
|
242
248
|
requireString(detail.reviewStatus);
|
|
243
249
|
requireString(detail.reviewFreshness);
|
|
244
250
|
if (typeof detail.stale !== "boolean" || typeof detail.invalidated !== "boolean") throw new AgentError("prReadInvalidResponse");
|
|
@@ -382,7 +388,11 @@ export function formatPRDetail(detail, labels) {
|
|
|
382
388
|
const lines = [
|
|
383
389
|
`${safeInline(detail.repository)} #${detail.number} — ${safeInline(detail.title)}`,
|
|
384
390
|
`${labels.head}: ${safeInline(detail.headSha)}`,
|
|
385
|
-
|
|
391
|
+
// Forks on ciUnreadable rather than printing ciStatus straight through. Left
|
|
392
|
+
// alone, `pr view` would keep saying "none" while `pr checks` already says
|
|
393
|
+
// the checks could not be read — one endpoint, two commands, two answers,
|
|
394
|
+
// which is the false trail #598 started on.
|
|
395
|
+
`${labels.checks}: ${detail.ciUnreadable ? labels.ciUnreadable : safeInline(detail.ciStatus)}`,
|
|
386
396
|
`${labels.review}: ${safeInline(detail.reviewStatus)}`,
|
|
387
397
|
safeInline(detail.url),
|
|
388
398
|
];
|
|
@@ -404,6 +414,16 @@ export function formatPRChecks(detail) {
|
|
|
404
414
|
}
|
|
405
415
|
|
|
406
416
|
export function prChecksExitCode(detail) {
|
|
417
|
+
// "Unconfigured" and "unavailable" used to share the line below, because
|
|
418
|
+
// nothing on the wire could tell them apart — the comment there named both.
|
|
419
|
+
// `ciUnreadable` is the first thing that can, so the unreadable case gets its
|
|
420
|
+
// own branch instead of continuing to ride on "the set came back empty".
|
|
421
|
+
//
|
|
422
|
+
// This matters beyond tidiness: someone will eventually decide that a repo
|
|
423
|
+
// with genuinely no CI should not exit non-zero, and if the two cases are
|
|
424
|
+
// still merged, that change silently takes fail-closed with it while reading
|
|
425
|
+
// as a pure ergonomics fix in review.
|
|
426
|
+
if (detail.ciUnreadable) return 1;
|
|
407
427
|
// Match `gh pr checks`: an empty check set is not evidence that CI passed.
|
|
408
428
|
// Keep it non-zero so automation cannot treat an unconfigured or unavailable
|
|
409
429
|
// check suite as a green pull request.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// `stamp pr review <n>`: the reviewer's preparation, in one read (task #551,
|
|
2
|
+
// 飞牛 2026-09-18). Everything a non-author exact-head review starts from —
|
|
3
|
+
// the exact head to pin, the base, the merge-base, whether the base has moved
|
|
4
|
+
// since the branch forked (the trap: diffing against the current base then
|
|
5
|
+
// shows unrelated changes), checks, review state — and the local commands
|
|
6
|
+
// that diff and patch-id against the merge-base rather than the base.
|
|
7
|
+
import { safeInline } from "./read.mjs";
|
|
8
|
+
|
|
9
|
+
// The brief does NOT say whether the base has advanced: GitHub's `base.sha`
|
|
10
|
+
// on a pull request is the fork point and stays put while the base branch
|
|
11
|
+
// moves, so `baseSha !== mergeBaseSha` only detects a retarget or rebase and
|
|
12
|
+
// would call an advanced base "current" — the one sentence this tool exists
|
|
13
|
+
// to prevent (飞牛, review of #258). Until the detail carries the base
|
|
14
|
+
// branch's current tip, the rule is stated unconditionally.
|
|
15
|
+
export function reviewBrief(detail) {
|
|
16
|
+
const short = (sha) => sha.slice(0, 12);
|
|
17
|
+
return {
|
|
18
|
+
repository: detail.repository,
|
|
19
|
+
number: detail.number,
|
|
20
|
+
title: detail.title,
|
|
21
|
+
author: detail.author,
|
|
22
|
+
url: detail.url,
|
|
23
|
+
headSha: detail.headSha,
|
|
24
|
+
headRef: detail.headRef,
|
|
25
|
+
baseRef: detail.baseRef,
|
|
26
|
+
baseSha: detail.baseSha,
|
|
27
|
+
mergeBaseSha: detail.mergeBaseSha,
|
|
28
|
+
ciStatus: detail.ciStatus,
|
|
29
|
+
// Carried through because this brief is what a reviewer reads before
|
|
30
|
+
// pinning a verdict to an exact head. Dropping it here let `pr review`
|
|
31
|
+
// keep saying "none" after `pr view` and `pr checks` had both learned to
|
|
32
|
+
// say the checks were refused -- the same quiet falsehood, on the path
|
|
33
|
+
// where it costs the most (cross, reviewing #602).
|
|
34
|
+
ciUnreadable: detail.ciUnreadable === true,
|
|
35
|
+
reviewStatus: detail.reviewStatus,
|
|
36
|
+
reviewFreshness: detail.reviewFreshness,
|
|
37
|
+
checks: detail.checks.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),
|
|
38
|
+
commands: {
|
|
39
|
+
fetch: `git fetch origin ${detail.headRef} ${detail.baseRef}`,
|
|
40
|
+
diff: `git diff ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
41
|
+
stat: `git diff --stat ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
42
|
+
log: `git log --oneline ${short(detail.mergeBaseSha)}..${short(detail.headSha)}`,
|
|
43
|
+
patchId: `git diff ${short(detail.mergeBaseSha)} ${short(detail.headSha)} | git patch-id --stable`,
|
|
44
|
+
},
|
|
45
|
+
verdict: `GO|CHANGES @ exact ${detail.headSha}`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function formatPRReview(brief, t) {
|
|
50
|
+
const lines = [
|
|
51
|
+
`${safeInline(brief.repository)} #${brief.number} — ${safeInline(brief.title)} (${safeInline(brief.author)})`,
|
|
52
|
+
`${t("prReviewExactHead")}: ${safeInline(brief.headSha)} (${safeInline(brief.headRef)})`,
|
|
53
|
+
`${t("prReviewBase")}: ${safeInline(brief.baseRef)} @ ${safeInline(brief.baseSha)}`,
|
|
54
|
+
`${t("prReviewMergeBase")}: ${safeInline(brief.mergeBaseSha)}`,
|
|
55
|
+
` ${t("prReviewMergeBaseRule")}`,
|
|
56
|
+
brief.ciUnreadable
|
|
57
|
+
? `${t("prChecksLabel")}: ${t("prCIUnreadable")}`
|
|
58
|
+
: `${t("prChecksLabel")}: ${safeInline(brief.ciStatus)}${brief.checks.length ? " — " + brief.checks.map((c) => `${safeInline(c.name)}=${safeInline(c.conclusion || c.status)}`).join(" ") : ""}`,
|
|
59
|
+
`${t("prReviewLabel")}: ${safeInline(brief.reviewStatus)} (${safeInline(brief.reviewFreshness)})`,
|
|
60
|
+
safeInline(brief.url),
|
|
61
|
+
"",
|
|
62
|
+
`${t("prReviewCommands")}:`,
|
|
63
|
+
` ${brief.commands.fetch}`,
|
|
64
|
+
` ${brief.commands.log}`,
|
|
65
|
+
` ${brief.commands.stat}`,
|
|
66
|
+
` ${brief.commands.diff}`,
|
|
67
|
+
` ${brief.commands.patchId}`,
|
|
68
|
+
"",
|
|
69
|
+
// The qualifier goes ON this line, not eight lines above it. `Checks:
|
|
70
|
+
// unreadable` already appears near the top, but this is the line a reviewer
|
|
71
|
+
// copies to record a verdict, and by the time they reach it there is a whole
|
|
72
|
+
// block of commands in between. This card's entire subject is a true
|
|
73
|
+
// statement sitting somewhere other than where the decision is made; putting
|
|
74
|
+
// it only at the top would have been a milder version of the same thing
|
|
75
|
+
// (飞牛, reviewing #282).
|
|
76
|
+
brief.ciUnreadable
|
|
77
|
+
? `${t("prReviewVerdict")}: ${brief.verdict} (${t("prVerdictCIUnreadable")})`
|
|
78
|
+
: `${t("prReviewVerdict")}: ${brief.verdict}`,
|
|
79
|
+
];
|
|
80
|
+
return lines;
|
|
81
|
+
}
|
|
@@ -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
|
+
}
|
package/lib/repo/ssh.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { dirname, join } from "node:path";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
4
5
|
|
|
5
6
|
// `stamp repo clone` must not ask a human to export GIT_SSH_COMMAND: after
|
|
6
7
|
// `stamp key enroll` the CLI already knows which key it enrolled and the
|
|
@@ -15,11 +16,22 @@ export function defaultIdentityPath(env) {
|
|
|
15
16
|
return join(homedir(), ".ssh", "id_ed25519");
|
|
16
17
|
}
|
|
17
18
|
|
|
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) {
|
|
19
24
|
const fromFlag = String(flagValue ?? "").trim();
|
|
20
|
-
if (fromFlag) return fromFlag;
|
|
25
|
+
if (fromFlag) return { identityPath: fromFlag, source: "flag" };
|
|
21
26
|
const fromEnv = String(env?.STAMP_SSH_IDENTITY ?? "").trim();
|
|
22
|
-
return fromEnv
|
|
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;
|
|
23
35
|
}
|
|
24
36
|
|
|
25
37
|
// defaultKnownHostsPath is one stable file for every Stamp instance (a
|
|
@@ -94,3 +106,122 @@ export async function fetchPublishedKnownHosts({ apiBase, fetchImpl = fetch }) {
|
|
|
94
106
|
if (!parsed) return { ok: false, invalid: true };
|
|
95
107
|
return { ok: true, pattern: parsed.pattern, line: parsed.line };
|
|
96
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
|
+
}
|