@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.
- package/README.md +14 -0
- package/lib/agent-login.mjs +10 -1
- package/lib/auth.mjs +45 -2
- package/lib/client.mjs +67 -10
- package/lib/commands/changelog.mjs +58 -0
- package/lib/commands/identity.mjs +12 -0
- package/lib/commands/key.mjs +58 -0
- package/lib/commands/knownhosts.mjs +144 -0
- package/lib/commands/pr.mjs +189 -0
- package/lib/commands/receipt.mjs +16 -0
- package/lib/commands/repo.mjs +78 -0
- package/lib/commands/session.mjs +52 -0
- package/lib/commands/subscribe.mjs +35 -0
- package/lib/errors.mjs +11 -37
- package/lib/expiry.mjs +27 -0
- package/lib/flags.mjs +26 -0
- package/lib/locale.mjs +167 -17
- package/lib/main.mjs +43 -302
- package/lib/{pr-comment.mjs → pr/comment.mjs} +10 -5
- package/lib/{pull-request.mjs → pr/create.mjs} +1 -1
- package/lib/{pr-read.mjs → pr/read.mjs} +29 -5
- package/lib/pr/review.mjs +81 -0
- package/lib/pr/write.mjs +82 -0
- package/lib/{repo-clone.mjs → repo/clone.mjs} +15 -0
- package/lib/repo/identities.mjs +43 -0
- package/lib/repo/ssh.mjs +227 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,6 +36,20 @@ Configuration layering is `environment > executable defaults`: `STAMP_URL` and
|
|
|
36
36
|
`STAMP_SERVICE` override either bin explicitly. There are no per-run URL or
|
|
37
37
|
service command-line flags today.
|
|
38
38
|
|
|
39
|
+
`repo clone` carries the SSH identity itself (task #475): it uses the key
|
|
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
|
|
49
|
+
`~/.stamp/known_hosts` (`--known-hosts FILE` / `STAMP_KNOWN_HOSTS`), then records
|
|
50
|
+
the same command as the clone's `core.sshCommand` so later `git push`/`git fetch`
|
|
51
|
+
inherit it. No `GIT_SSH_COMMAND` export is needed.
|
|
52
|
+
|
|
39
53
|
When `STAMP_URL` is not explicit, an existing Agent session stored against the
|
|
40
54
|
exact legacy staging origin `https://github-staging.botiverse.dev` or the
|
|
41
55
|
former CLI placeholder `https://github.botiverse.dev` is used against the new
|
package/lib/agent-login.mjs
CHANGED
|
@@ -160,7 +160,16 @@ export async function runAgentLogin(a, apiBase, opts = {}) {
|
|
|
160
160
|
const runner = opts.invoke ?? ((a2) => defaultInvoke(a.raftBin, a2));
|
|
161
161
|
const res = runner(args);
|
|
162
162
|
if (res.status !== 0) {
|
|
163
|
-
|
|
163
|
+
// Surface raft's OWN diagnostics (@Mason / @Tenny / @skyzh): raft already
|
|
164
|
+
// reports the LAYERED reason -- the error, the stable Code and the Next
|
|
165
|
+
// action -- and the next action is what the reader actually needs. Keep all
|
|
166
|
+
// of it (not just the first line): truncating to one line drops the fix.
|
|
167
|
+
const diagnostic = String(res.stderr ?? "")
|
|
168
|
+
.split("\n")
|
|
169
|
+
.map((l) => l.trimEnd())
|
|
170
|
+
.filter((l) => l.trim().length > 0)
|
|
171
|
+
.join("\n");
|
|
172
|
+
agentFail("invoke_exit", { status: res.status ?? "spawn error", diagnostic });
|
|
164
173
|
}
|
|
165
174
|
const { grant } = parseAgentLoginInvoke(res.stdout, service, now);
|
|
166
175
|
|
package/lib/auth.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { unlinkSync, existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
2
3
|
import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
|
|
3
4
|
import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } from "./agent-login.mjs";
|
|
4
5
|
import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
|
|
@@ -25,6 +26,22 @@ const KNOWN_INSTANCES = new Map([
|
|
|
25
26
|
["https://stamp.build", "stamp"],
|
|
26
27
|
["https://staging.stamp.build", "raft-git-gateway-staging"],
|
|
27
28
|
]);
|
|
29
|
+
|
|
30
|
+
// origin -> the installed binary that serves that instance, for the "wrong
|
|
31
|
+
// entry point" case (task #436): a session stored for staging rejects `stamp`,
|
|
32
|
+
// and telling the reader to run `stamp login` again sends them further from the
|
|
33
|
+
// fix. Only the instances we ship a binary for are named.
|
|
34
|
+
const INSTANCE_BINARIES = new Map([
|
|
35
|
+
["https://stamp.build", "stamp"],
|
|
36
|
+
["https://staging.stamp.build", "stamp-staging"],
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
// siblingBinaryFor names the binary that serves the instance a stored session
|
|
40
|
+
// belongs to, so the refusal can point at it instead of at a re-login. Empty
|
|
41
|
+
// for an unknown/self-hosted origin: we do not guess a command that may not exist.
|
|
42
|
+
export function siblingBinaryFor(storedOrigin) {
|
|
43
|
+
return INSTANCE_BINARIES.get(storedOrigin) ?? "";
|
|
44
|
+
}
|
|
28
45
|
// storeMatchesOrigin reports whether a stored session belongs to the SAME
|
|
29
46
|
// instance as the target base. It is ONE branch-free property — the parsed
|
|
30
47
|
// origins must be strictly equal — and it must hold at EVERY actual use
|
|
@@ -59,6 +76,30 @@ export function assertCoherentPair(apiBase, service) {
|
|
|
59
76
|
}
|
|
60
77
|
}
|
|
61
78
|
|
|
79
|
+
// A partial managed-agent environment fails closed, and the message has to say
|
|
80
|
+
// WHICH variable is missing (task #480): "incomplete agent markers" makes the
|
|
81
|
+
// operator diff three variables by hand. The package reports the outcome, not
|
|
82
|
+
// the field, so the mapping is derived here from the environment and only the
|
|
83
|
+
// documented outcomes are matched; an unrecognized reason keeps the generic
|
|
84
|
+
// wording rather than guessing.
|
|
85
|
+
const AGENT_MARKERS = ["SLOCK_CLI_TRANSPORT_DIR", "SLOCK_HOME", "SLOCK_AGENT_ID"];
|
|
86
|
+
|
|
87
|
+
export function admissionFailure(admission, env = {}) {
|
|
88
|
+
if (admission?.reason === "incomplete agent markers") {
|
|
89
|
+
return new AgentError("admissionMissingVars", {
|
|
90
|
+
missing: AGENT_MARKERS.filter((name) => !env[name]).join(", "),
|
|
91
|
+
present: AGENT_MARKERS.filter((name) => env[name]).join(", ") || "none",
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
if (admission?.reason === "invalid SLOCK_AGENT_ID") {
|
|
95
|
+
return new AgentError("admissionInvalidAgentID", { value: String(env.SLOCK_AGENT_ID ?? "") });
|
|
96
|
+
}
|
|
97
|
+
if (admission?.reason === "raft wrapper missing or not executable in transport dir") {
|
|
98
|
+
return new AgentError("admissionRaftWrapper", { path: join(String(env.SLOCK_CLI_TRANSPORT_DIR ?? ""), "raft") });
|
|
99
|
+
}
|
|
100
|
+
return new AgentError("admissionPartial", { reason: String(admission?.reason ?? "unknown") });
|
|
101
|
+
}
|
|
102
|
+
|
|
62
103
|
export function resolveAuth({ urlBase, urlExplicit, env = process.env, service, locale = "en", cliName = "stamp" }) {
|
|
63
104
|
// The instance slug may be left unset (e.g. `stamp-staging` passes only its
|
|
64
105
|
// base). Derive it: an explicit STAMP_SERVICE wins, else the base's owner,
|
|
@@ -69,7 +110,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
|
|
|
69
110
|
}
|
|
70
111
|
const admission = admitAgent(env);
|
|
71
112
|
if (admission.kind === "fail_closed") {
|
|
72
|
-
|
|
113
|
+
throw admissionFailure(admission, env);
|
|
73
114
|
}
|
|
74
115
|
if (admission.kind === "agent") {
|
|
75
116
|
const a = admission.env;
|
|
@@ -109,10 +150,12 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service,
|
|
|
109
150
|
async token() {
|
|
110
151
|
if (!usableStore) {
|
|
111
152
|
if (storedOriginElsewhere !== null) {
|
|
112
|
-
|
|
153
|
+
const sibling = siblingBinaryFor(storedOriginElsewhere);
|
|
154
|
+
throw new AgentError(sibling && sibling !== cliName ? "sessionOriginMismatchSibling" : "sessionOriginMismatch", {
|
|
113
155
|
stored: storedOriginElsewhere,
|
|
114
156
|
target: originOf(apiBase) ?? apiBase,
|
|
115
157
|
cli: cliName,
|
|
158
|
+
other: sibling,
|
|
116
159
|
});
|
|
117
160
|
}
|
|
118
161
|
throw new AgentError("notLoggedIn");
|
package/lib/client.mjs
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import { AgentError } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
// NetworkError is an AgentError about the transport, not about the request. A
|
|
4
|
+
// WRITE that fails this way has an UNKNOWN outcome (the request may have
|
|
5
|
+
// reached the gateway), so the write commands must keep their "outcome is
|
|
6
|
+
// unknown, do not resend" contract instead of inviting a retry.
|
|
7
|
+
export class NetworkError extends AgentError {}
|
|
8
|
+
|
|
1
9
|
export class ApiError extends Error {
|
|
2
10
|
constructor(status, body, text) {
|
|
3
11
|
super(`${status}: ${body?.error ?? (text ?? "").slice(0, 200)}`);
|
|
@@ -6,17 +14,66 @@ export class ApiError extends Error {
|
|
|
6
14
|
}
|
|
7
15
|
}
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
// A connection-level failure (never an HTTP status) arrives from undici as
|
|
18
|
+
// TypeError("fetch failed") with the real reason on `.cause`. The CLI used to
|
|
19
|
+
// hand that bare string to the operator; task #476 showed a first `pr list` on a
|
|
20
|
+
// cold instance failing that way while a rerun worked, because nothing retried
|
|
21
|
+
// the one attempt and nothing said what to try next. Text and JSON output share
|
|
22
|
+
// this client — the failure happens before either formatter runs — so the fix
|
|
23
|
+
// belongs here, not in one output path.
|
|
24
|
+
const RETRYABLE_NETWORK_CODES = new Set([
|
|
25
|
+
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "EAI_AGAIN",
|
|
26
|
+
"UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT",
|
|
27
|
+
]);
|
|
28
|
+
const DNS_NETWORK_CODES = new Set(["ENOTFOUND", "EAI_AGAIN"]);
|
|
29
|
+
|
|
30
|
+
export function networkFailureOf(error) {
|
|
31
|
+
const code = String(error?.cause?.code ?? error?.code ?? "");
|
|
32
|
+
const message = String(error?.cause?.message ?? error?.message ?? "");
|
|
33
|
+
if (DNS_NETWORK_CODES.has(code)) return { code, retryable: true };
|
|
34
|
+
if (RETRYABLE_NETWORK_CODES.has(code)) return { code, retryable: true };
|
|
35
|
+
if (code || /fetch failed/i.test(message)) {
|
|
36
|
+
// Unknown transport failure: report it, but do not spin on it.
|
|
37
|
+
return { code: code || message || "fetch failed", retryable: false };
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function networkErrorKey(failure) {
|
|
43
|
+
return DNS_NETWORK_CODES.has(failure.code) ? "networkHostUnresolved" : "networkUnreachable";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function makeClient(auth, fetchImpl = fetch, options = {}) {
|
|
47
|
+
// Reads are idempotent, so a bounded retry is safe; writes are not retried
|
|
48
|
+
// here (they carry their own idempotency key and a retry decision).
|
|
49
|
+
const readRetries = Number.isInteger(options.readRetries) ? Math.max(0, options.readRetries) : 2;
|
|
50
|
+
const retryDelayMs = Number.isInteger(options.retryDelayMs) ? Math.max(0, options.retryDelayMs) : 250;
|
|
51
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
52
|
+
|
|
10
53
|
async function once(method, path, body, token) {
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
54
|
+
const attempts = method === "GET" ? readRetries + 1 : 1;
|
|
55
|
+
for (let attempt = 1; ; attempt++) {
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetchImpl(`${auth.apiBase}${path}`, {
|
|
59
|
+
method,
|
|
60
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
|
|
61
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
62
|
+
});
|
|
63
|
+
} catch (error) {
|
|
64
|
+
const failure = networkFailureOf(error);
|
|
65
|
+
if (!failure) throw error;
|
|
66
|
+
if (failure.retryable && attempt < attempts) {
|
|
67
|
+
await sleep(retryDelayMs * attempt);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
throw new NetworkError(networkErrorKey(failure), { base: auth.apiBase, cause: failure.code });
|
|
71
|
+
}
|
|
72
|
+
const text = await res.text();
|
|
73
|
+
let json = null;
|
|
74
|
+
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
|
|
75
|
+
return { res, json, text };
|
|
76
|
+
}
|
|
20
77
|
}
|
|
21
78
|
return async function api(method, path, body) {
|
|
22
79
|
const used = await auth.token();
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { t } from "../locale.mjs";
|
|
2
|
+
import { takeFlag } from "../flags.mjs";
|
|
3
|
+
|
|
4
|
+
export async function run(ctx) {
|
|
5
|
+
const sub = ctx.args.shift();
|
|
6
|
+
if (sub !== "bind") throw new Error(t(ctx.locale, "usageIdentityBind"));
|
|
7
|
+
const agentEmail = takeFlag(ctx.args, "email");
|
|
8
|
+
if (!agentEmail) throw new Error(t(ctx.locale, "usageIdentityBind"));
|
|
9
|
+
const d = await ctx.api("POST", "/v1/identities", { agentEmail });
|
|
10
|
+
ctx.emit(d, () => ctx.out(t(ctx.locale, "bound", { email: d.agentEmail })));
|
|
11
|
+
return ctx.exit(0);
|
|
12
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { t } from "../locale.mjs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { takeFlag, readPublicKey } from "../flags.mjs";
|
|
7
|
+
import { recordIdentity } from "../repo/identities.mjs";
|
|
8
|
+
|
|
9
|
+
export async function run(ctx) {
|
|
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
|
+
}
|
|
28
|
+
if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
|
|
29
|
+
const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
30
|
+
if (keyPath !== "-" && !existsSync(keyPath)) {
|
|
31
|
+
// The default path is the interesting case: `key enroll` on a machine with
|
|
32
|
+
// no key reads a path the operator never typed, so name it and name the two
|
|
33
|
+
// ways out (task #480).
|
|
34
|
+
throw new Error(t(ctx.locale, "keyPublicKeyMissing", { path: keyPath, private: keyPath.replace(/\.pub$/i, "") }));
|
|
35
|
+
}
|
|
36
|
+
const publicKey = readPublicKey(keyPath);
|
|
37
|
+
const d = await ctx.api("POST", "/v1/keys", { publicKey });
|
|
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
|
+
});
|
|
57
|
+
return ctx.exit(0);
|
|
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
|
+
}
|