@botiverse/stamp-cli 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -0
- package/bin/stamp-staging.mjs +1 -0
- package/bin/stamp.mjs +61 -5
- package/lib/agent-login.mjs +10 -1
- package/lib/agent-refresh.mjs +17 -4
- package/lib/auth.mjs +147 -5
- package/lib/client.mjs +67 -10
- package/lib/commands/identity.mjs +12 -0
- package/lib/commands/key.mjs +21 -0
- package/lib/commands/pr.mjs +158 -0
- package/lib/commands/receipt.mjs +10 -0
- package/lib/commands/repo.mjs +66 -0
- package/lib/commands/session.mjs +52 -0
- package/lib/commands/subscribe.mjs +35 -0
- package/lib/errors.mjs +11 -32
- package/lib/expiry.mjs +27 -0
- package/lib/flags.mjs +26 -0
- package/lib/locale.mjs +212 -89
- package/lib/main.mjs +44 -259
- package/lib/pr/comment.mjs +39 -0
- package/lib/{pull-request.mjs → pr/create.mjs} +1 -1
- package/lib/{pr-read.mjs → pr/read.mjs} +139 -7
- package/lib/pr/write.mjs +82 -0
- package/lib/{repo-clone.mjs → repo/clone.mjs} +15 -0
- package/lib/repo/ssh.mjs +96 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ stamp pr list
|
|
|
19
19
|
stamp pr view 123 --repo org/repo
|
|
20
20
|
stamp pr diff 123 --repo org/repo
|
|
21
21
|
stamp pr checks 123 --repo org/repo
|
|
22
|
+
stamp pr comment 123 --repo org/repo --body-file ./comment.md
|
|
22
23
|
```
|
|
23
24
|
|
|
24
25
|
- Agent: `stamp login` (PKCE grant via `raft integration invoke --action agent-login`)
|
|
@@ -35,6 +36,13 @@ Configuration layering is `environment > executable defaults`: `STAMP_URL` and
|
|
|
35
36
|
`STAMP_SERVICE` override either bin explicitly. There are no per-run URL or
|
|
36
37
|
service command-line flags today.
|
|
37
38
|
|
|
39
|
+
`repo clone` carries the SSH identity itself (task #475): it uses the key
|
|
40
|
+
`key enroll` uses (`~/.ssh/id_ed25519`, or `--identity FILE` / `STAMP_SSH_IDENTITY`)
|
|
41
|
+
and pins the host key the instance publishes at `/.well-known/ssh-known-hosts` into
|
|
42
|
+
`~/.stamp/known_hosts` (`--known-hosts FILE` / `STAMP_KNOWN_HOSTS`), then records
|
|
43
|
+
the same command as the clone's `core.sshCommand` so later `git push`/`git fetch`
|
|
44
|
+
inherit it. No `GIT_SSH_COMMAND` export is needed.
|
|
45
|
+
|
|
38
46
|
When `STAMP_URL` is not explicit, an existing Agent session stored against the
|
|
39
47
|
exact legacy staging origin `https://github-staging.botiverse.dev` or the
|
|
40
48
|
former CLI placeholder `https://github.botiverse.dev` is used against the new
|
|
@@ -64,6 +72,31 @@ reading through Stamp rather than a local GitHub credential:
|
|
|
64
72
|
- `--json` returns the service's validated machine envelope. Human-formatted
|
|
65
73
|
output strips terminal control characters from provider-authored text.
|
|
66
74
|
|
|
75
|
+
### Ordinary PR comments
|
|
76
|
+
|
|
77
|
+
`stamp pr comment 123 -R org/repo --body-file ./comment.md` uses a **human Stamp
|
|
78
|
+
session with a bound GitHub account**, and posts as that GitHub user. Agent
|
|
79
|
+
sessions are rejected; there is no fallback to an App or another person's token.
|
|
80
|
+
The existing human session authentication applies; this command does not create
|
|
81
|
+
a new login flow. The web inbox does not yet provide a comment composer.
|
|
82
|
+
|
|
83
|
+
Use `--body TEXT` (`-b`) or `--body-file FILE` (`-F`); `--body-file -` reads stdin
|
|
84
|
+
and preserves paragraphs. A PR URL can replace the number/repository pair.
|
|
85
|
+
Comments must be nonempty and at most 64 KiB of UTF-8 text. Closed or merged PRs
|
|
86
|
+
can still receive comments. This is an ordinary conversation comment, not a
|
|
87
|
+
review, inline code comment, approval or merge.
|
|
88
|
+
|
|
89
|
+
GitHub must permit the bound user's token to create comments; its
|
|
90
|
+
[issue-comment API](https://docs.github.com/en/rest/issues/comments#create-an-issue-comment)
|
|
91
|
+
accepts GitHub App user tokens with Issues or Pull requests write permission.
|
|
92
|
+
Stamp's existing repository visibility checks also apply.
|
|
93
|
+
|
|
94
|
+
Success prints the confirmed comment URL and GitHub actor; `--json` includes
|
|
95
|
+
`repository`, `number`, `commentId`, `url` and `actorLogin`. Each explicit command
|
|
96
|
+
is a new send, with no persistent deduplication. Neither CLI nor provider adapter
|
|
97
|
+
automatically resends a comment. If a response is lost or cannot be validated,
|
|
98
|
+
the command exits nonzero and asks you to inspect the PR before sending again.
|
|
99
|
+
|
|
67
100
|
The Raft manifest exposes only `agent-login`. Key enrollment, identity binding,
|
|
68
101
|
receipt reads, PR creation and subscriptions all use this CLI; the HTTP APIs
|
|
69
102
|
remain available to service clients. `stamp migration-help` maps retired action
|
package/bin/stamp-staging.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
|
|
|
8
8
|
const URL_BASE = process.env.STAMP_URL || STAMP_DEFAULT_URL;
|
|
9
9
|
|
|
10
10
|
await main(process.argv.slice(2), {
|
|
11
|
+
argv1: process.argv[1],
|
|
11
12
|
urlBase: URL_BASE,
|
|
12
13
|
urlExplicit: Boolean(process.env.STAMP_URL),
|
|
13
14
|
serviceDefault: "raft-git-gateway-staging",
|
package/bin/stamp.mjs
CHANGED
|
@@ -1,9 +1,65 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// stamp — CLI for the Agent Git gateway.
|
|
3
|
-
//
|
|
2
|
+
// stamp — CLI for the Agent Git gateway, targeting the PRODUCTION instance.
|
|
3
|
+
//
|
|
4
|
+
// Task #439: the production service slug and the default origin used to be
|
|
5
|
+
// resolved INDEPENDENTLY (lib/agent-login.mjs: STAMP_SERVICE="stamp" while the
|
|
6
|
+
// default URL was the staging origin). Once the production `stamp` service was
|
|
7
|
+
// registered, an unconfigured `stamp login` became a prod-slug + staging-origin
|
|
8
|
+
// pair — a wrong-environment target.
|
|
9
|
+
//
|
|
10
|
+
// The instance is pinned as a COHERENT PAIR (prod slug + prod origin) and the
|
|
11
|
+
// pair is defended. The defense compares the PARSED ORIGIN, not the raw string:
|
|
12
|
+
// `https://staging.stamp.build/` (trailing slash), `HTTPS://STAGING.STAMP.BUILD`
|
|
13
|
+
// and an explicit `:443` are the same origin and must be refused just the same.
|
|
4
14
|
import { main } from "../lib/main.mjs";
|
|
5
|
-
import { STAMP_DEFAULT_URL } from "../lib/agent-login.mjs";
|
|
6
15
|
|
|
7
|
-
const
|
|
16
|
+
const PROD_URL = "https://stamp.build";
|
|
17
|
+
const PROD_SERVICE = "stamp";
|
|
18
|
+
const STAGING_URL = "https://staging.stamp.build";
|
|
19
|
+
const STAGING_SERVICE = "raft-git-gateway-staging";
|
|
8
20
|
|
|
9
|
-
|
|
21
|
+
// Canonical origin of a URL, or null when it is not an absolute http(s) URL.
|
|
22
|
+
function originOf(value) {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = new URL(value);
|
|
25
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
26
|
+
return parsed.origin; // lowercases host, drops default port + path/query
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Canonical origin -> the service slug that owns it.
|
|
33
|
+
//
|
|
34
|
+
// SUPPORT BOUNDARY: this map lists the instances the CLI KNOWS. The pairing
|
|
35
|
+
// invariant can only be enforced where the origin<->service mapping is known;
|
|
36
|
+
// a self-hosted instance is not covered (the CLI has no general way to learn
|
|
37
|
+
// its mapping). Do not describe the guarantee as universal.
|
|
38
|
+
const KNOWN_INSTANCES = new Map([
|
|
39
|
+
[originOf(PROD_URL), PROD_SERVICE],
|
|
40
|
+
[originOf(STAGING_URL), STAGING_SERVICE],
|
|
41
|
+
]);
|
|
42
|
+
const originService = KNOWN_INSTANCES;
|
|
43
|
+
|
|
44
|
+
const url = process.env.STAMP_URL || PROD_URL;
|
|
45
|
+
const urlOrigin = originOf(url);
|
|
46
|
+
const owner = urlOrigin === null ? undefined : originService.get(urlOrigin);
|
|
47
|
+
|
|
48
|
+
// The instance this invocation targets. An explicit STAMP_SERVICE must match the
|
|
49
|
+
// origin's owner; otherwise derive it (a non-default origin needs its slug).
|
|
50
|
+
const requested = process.env.STAMP_SERVICE;
|
|
51
|
+
if (owner !== undefined && requested !== undefined && requested !== owner) {
|
|
52
|
+
process.stderr.write(
|
|
53
|
+
`stamp: STAMP_URL=${url} belongs to service ${owner}, not ${requested} — refusing to pair them (task #439).\n` +
|
|
54
|
+
"Set both explicitly for a non-default instance, or use `stamp-staging` for staging.\n",
|
|
55
|
+
);
|
|
56
|
+
process.exit(2);
|
|
57
|
+
}
|
|
58
|
+
const service = requested ?? owner ?? PROD_SERVICE;
|
|
59
|
+
|
|
60
|
+
await main(process.argv.slice(2), {
|
|
61
|
+
argv1: process.argv[1],
|
|
62
|
+
urlBase: url,
|
|
63
|
+
urlExplicit: Boolean(process.env.STAMP_URL),
|
|
64
|
+
serviceDefault: service,
|
|
65
|
+
});
|
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/agent-refresh.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { randomBytes } from "node:crypto";
|
|
|
7
7
|
import { agentAuthPath, writeAgentSession } from "@botiverse/agent-session-store";
|
|
8
8
|
import { parseAgentSession, readBoundedText, STAMP_SERVICE } from "./agent-login.mjs";
|
|
9
9
|
import { AgentError, agentFail } from "./errors.mjs";
|
|
10
|
+
import { storeMatchesOrigin } from "./auth.mjs";
|
|
10
11
|
|
|
11
12
|
export const REFRESH_SKEW_MS = 60_000;
|
|
12
13
|
const REFRESH_DEADLINE_MS = 20_000;
|
|
@@ -78,7 +79,9 @@ export async function getFreshAgentAccessToken(a, opts = {}) {
|
|
|
78
79
|
const now = opts.now ?? Date.now();
|
|
79
80
|
const store = readStore(a, service);
|
|
80
81
|
if (!store) return null;
|
|
81
|
-
|
|
82
|
+
// Task #439: never use a store issued for a different origin than the target.
|
|
83
|
+
if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
|
|
84
|
+
if (storeMatchesOrigin(store, opts.apiBase ?? store.api_base) && !accessExpiresWithinSkew(store, now)) return store.access_token;
|
|
82
85
|
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, false, opts.deadlineMs ?? REFRESH_DEADLINE_MS, undefined, opts.apiBase);
|
|
83
86
|
}
|
|
84
87
|
|
|
@@ -87,7 +90,8 @@ export async function forceRefreshAgentToken(a, opts = {}) {
|
|
|
87
90
|
const now = opts.now ?? Date.now();
|
|
88
91
|
const store = readStore(a, service);
|
|
89
92
|
if (!store) return null;
|
|
90
|
-
|
|
93
|
+
if (!storeMatchesOrigin(store, opts.apiBase ?? store.api_base)) return null;
|
|
94
|
+
const reused = storeMatchesOrigin(store, opts.apiBase ?? store.api_base) ? successorIfRejected(store, opts.rejectedAccess) : null;
|
|
91
95
|
if (reused) return reused;
|
|
92
96
|
return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, true, opts.deadlineMs ?? REFRESH_DEADLINE_MS, opts.rejectedAccess, opts.apiBase);
|
|
93
97
|
}
|
|
@@ -103,11 +107,14 @@ async function singleFlightRefresh(a, service, baseline, now, fetchImpl, sleepIm
|
|
|
103
107
|
} catch (e) {
|
|
104
108
|
if (e?.code !== "EEXIST") throw e;
|
|
105
109
|
acquired = acquireIfDeadOwner(lock, ownerId);
|
|
106
|
-
if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess);
|
|
110
|
+
if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase);
|
|
107
111
|
}
|
|
108
112
|
try {
|
|
109
113
|
const fresh = readStore(a, service);
|
|
110
114
|
if (!fresh) return null;
|
|
115
|
+
if (!storeMatchesOrigin(fresh, apiBase ?? fresh.api_base)) return null;
|
|
116
|
+
// A cached token may only be returned when the stored session belongs to the
|
|
117
|
+
// TARGET origin; anything else is refused upstream (no replay, no migration).
|
|
111
118
|
const reused = successorIfRejected(fresh, rejectedAccess);
|
|
112
119
|
if (reused) return reused;
|
|
113
120
|
if (!force && !accessExpiresWithinSkew(fresh, now)) return fresh.access_token;
|
|
@@ -162,16 +169,22 @@ function ownerAlive(pid) {
|
|
|
162
169
|
try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
|
|
163
170
|
}
|
|
164
171
|
|
|
165
|
-
async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess) {
|
|
172
|
+
async function waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase) {
|
|
173
|
+
// The waiter must accept a session that the winner rewrote to the TARGET
|
|
174
|
+
// origin — comparing against the (possibly legacy) baseline base would make it
|
|
175
|
+
// poll until timeout even though the store is already correct (@skyzh).
|
|
176
|
+
const targetBase = apiBase ?? baseline.api_base;
|
|
166
177
|
const maxPolls = Math.ceil(LOCK_WAIT_MS / LOCK_POLL_MS);
|
|
167
178
|
for (let i = 0; i < maxPolls; i += 1) {
|
|
168
179
|
await sleepImpl(LOCK_POLL_MS);
|
|
169
180
|
const cur = readStore(a, service);
|
|
181
|
+
if (cur && !storeMatchesOrigin(cur, targetBase)) continue;
|
|
170
182
|
const reused = successorIfRejected(cur, rejectedAccess);
|
|
171
183
|
if (reused) return reused;
|
|
172
184
|
if (cur && cur.refresh_token !== baseline.refresh_token) return cur.access_token;
|
|
173
185
|
}
|
|
174
186
|
const cur = readStore(a, service);
|
|
187
|
+
if (cur && !storeMatchesOrigin(cur, targetBase)) agentFail("notLoggedIn");
|
|
175
188
|
const reused = successorIfRejected(cur, rejectedAccess);
|
|
176
189
|
if (reused) return reused;
|
|
177
190
|
if (!force && cur && !accessExpired(cur, now)) return cur.access_token;
|
package/lib/auth.mjs
CHANGED
|
@@ -1,32 +1,173 @@
|
|
|
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";
|
|
5
6
|
import { AgentError, agentFail } from "./errors.mjs";
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
// Canonical origin of a URL, or null when it is not an absolute http(s) URL.
|
|
9
|
+
// Task #439: comparisons on the stored/api base MUST normalize the origin —
|
|
10
|
+
// a trailing slash, upper-case host or explicit :443 are the SAME origin and
|
|
11
|
+
// must not slip past the "this is a legacy default" check.
|
|
12
|
+
function originOf(value) {
|
|
13
|
+
try {
|
|
14
|
+
const parsed = new URL(value);
|
|
15
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
16
|
+
return parsed.origin;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Known instance map: canonical origin -> the service slug that owns it.
|
|
23
|
+
// SUPPORT BOUNDARY: only the instances the CLI knows can be checked statically.
|
|
24
|
+
// A self-hosted instance's origin<->service mapping is not knowable locally.
|
|
25
|
+
const KNOWN_INSTANCES = new Map([
|
|
26
|
+
["https://stamp.build", "stamp"],
|
|
27
|
+
["https://staging.stamp.build", "raft-git-gateway-staging"],
|
|
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
|
+
}
|
|
45
|
+
// storeMatchesOrigin reports whether a stored session belongs to the SAME
|
|
46
|
+
// instance as the target base. It is ONE branch-free property — the parsed
|
|
47
|
+
// origins must be strictly equal — and it must hold at EVERY actual use
|
|
48
|
+
// (token read, refresh, 401 retry), not once at resolveAuth (@Tenny: "use site"
|
|
49
|
+
// is plural; the refresh path re-reads the store file).
|
|
50
|
+
//
|
|
51
|
+
// There is deliberately NO migration of a renamed host: a session issued for a
|
|
52
|
+
// superseded origin is treated as belonging to a DIFFERENT instance and is
|
|
53
|
+
// refused (the caller re-logs in). Such a session would otherwise have to be
|
|
54
|
+
// replayed or refreshed, and that branch produced every defect in this task
|
|
55
|
+
// (@Mason, 2026-09-13: "删" — the one saved re-login is already documented as
|
|
56
|
+
// expected, so the branch is not worth its concurrency+cache complexity).
|
|
57
|
+
export function storeMatchesOrigin(store, apiBase) {
|
|
58
|
+
if (!store) return false;
|
|
59
|
+
const target = originOf(apiBase);
|
|
60
|
+
const stored = originOf(store.api_base);
|
|
61
|
+
return stored !== null && stored === target;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function assertCoherentPair(apiBase, service) {
|
|
65
|
+
const origin = originOf(apiBase);
|
|
66
|
+
if (origin === null) return; // non-http(s) base: out of this check's scope
|
|
67
|
+
const owner = KNOWN_INSTANCES.get(origin);
|
|
68
|
+
if (owner === undefined) {
|
|
69
|
+
// Unknown origin (e.g. a self-hosted instance): its origin<->service
|
|
70
|
+
// mapping is not knowable locally, so it is outside this check. See the
|
|
71
|
+
// support boundary above — do not read this as a universal guarantee.
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (service !== owner) {
|
|
75
|
+
agentFail("pair_mismatch", { origin, service, owner });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
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
|
+
|
|
103
|
+
export function resolveAuth({ urlBase, urlExplicit, env = process.env, service, locale = "en", cliName = "stamp" }) {
|
|
104
|
+
// The instance slug may be left unset (e.g. `stamp-staging` passes only its
|
|
105
|
+
// base). Derive it: an explicit STAMP_SERVICE wins, else the base's owner,
|
|
106
|
+
// else the production default. Task #439: entry default, env and a stored
|
|
107
|
+
// session must all resolve to ONE coherent pair.
|
|
108
|
+
if (service === undefined || service === "") {
|
|
109
|
+
service = env.STAMP_SERVICE || KNOWN_INSTANCES.get(originOf(urlBase)) || STAMP_SERVICE;
|
|
110
|
+
}
|
|
8
111
|
const admission = admitAgent(env);
|
|
9
112
|
if (admission.kind === "fail_closed") {
|
|
10
|
-
|
|
113
|
+
throw admissionFailure(admission, env);
|
|
11
114
|
}
|
|
12
115
|
if (admission.kind === "agent") {
|
|
13
116
|
const a = admission.env;
|
|
14
117
|
const store = readStore(a, service);
|
|
15
118
|
const storedBase = store?.api_base;
|
|
16
|
-
|
|
119
|
+
// Task #439: compare the stored base on its PARSED ORIGIN, not the raw
|
|
120
|
+
// string. A legacy default stored with a trailing slash, different case or
|
|
121
|
+
// an explicit :443 is still that legacy default and must be superseded by
|
|
122
|
+
// the caller's coherent base — otherwise a stale stored spelling silently
|
|
123
|
+
// retargets the request. A genuinely non-legacy custom instance is still
|
|
124
|
+
// preserved (that is the existing custom-base feature).
|
|
125
|
+
const storedOrigin = originOf(storedBase);
|
|
126
|
+
const legacyOrigins = new Set([STAMP_LEGACY_STAGING_URL, STAMP_LEGACY_DEFAULT_URL].map(originOf));
|
|
127
|
+
const apiBase = urlExplicit || (storedOrigin !== null && legacyOrigins.has(storedOrigin))
|
|
17
128
|
? urlBase
|
|
18
|
-
: (
|
|
129
|
+
: (storedBase ?? urlBase);
|
|
130
|
+
// The final resolved pair must belong to one instance. Checked here so every
|
|
131
|
+
// source (entry default / env / stored session) is covered, before any
|
|
132
|
+
// network work. Task #439.
|
|
133
|
+
assertCoherentPair(apiBase, service);
|
|
134
|
+
|
|
135
|
+
// Task #439 (@skyzh): a stored session is bound to the ORIGIN it was issued
|
|
136
|
+
// against. If the resolved origin differs from the origin the session was
|
|
137
|
+
// stored for (e.g. we just superseded a legacy staging base with prod), the
|
|
138
|
+
// cached access/refresh tokens must NOT be replayed against the new origin —
|
|
139
|
+
// that would send a foreign instance's credential to this one. Treat such a
|
|
140
|
+
// store as absent so the caller must log in afresh.
|
|
141
|
+
// No migration: a store issued for a DIFFERENT origin is not usable here.
|
|
142
|
+
// The refusal names the origin so the reader knows why and what to do.
|
|
143
|
+
const usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
|
|
144
|
+
const storedOriginElsewhere = !usableStore && storedOrigin !== null ? storedOrigin : null;
|
|
19
145
|
return {
|
|
20
146
|
mode: "agent",
|
|
21
147
|
apiBase,
|
|
22
148
|
agentEnv: a,
|
|
23
149
|
service,
|
|
24
150
|
async token() {
|
|
151
|
+
if (!usableStore) {
|
|
152
|
+
if (storedOriginElsewhere !== null) {
|
|
153
|
+
const sibling = siblingBinaryFor(storedOriginElsewhere);
|
|
154
|
+
throw new AgentError(sibling && sibling !== cliName ? "sessionOriginMismatchSibling" : "sessionOriginMismatch", {
|
|
155
|
+
stored: storedOriginElsewhere,
|
|
156
|
+
target: originOf(apiBase) ?? apiBase,
|
|
157
|
+
cli: cliName,
|
|
158
|
+
other: sibling,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
throw new AgentError("notLoggedIn");
|
|
162
|
+
}
|
|
25
163
|
const tok = await getFreshAgentAccessToken(a, { service, apiBase });
|
|
26
164
|
if (!tok) throw new AgentError("notLoggedIn");
|
|
27
165
|
return tok;
|
|
28
166
|
},
|
|
29
|
-
async retryToken(rejectedAccess) {
|
|
167
|
+
async retryToken(rejectedAccess) {
|
|
168
|
+
if (!usableStore) return null;
|
|
169
|
+
return forceRefreshAgentToken(a, { service, apiBase, rejectedAccess });
|
|
170
|
+
},
|
|
30
171
|
logout() {
|
|
31
172
|
const p = agentAuthPath(a, service);
|
|
32
173
|
if (existsSync(p)) unlinkSync(p);
|
|
@@ -35,6 +176,7 @@ export function resolveAuth({ urlBase, urlExplicit, env = process.env, service =
|
|
|
35
176
|
};
|
|
36
177
|
}
|
|
37
178
|
const token = env.STAMP_TOKEN || "";
|
|
179
|
+
assertCoherentPair(urlBase, service);
|
|
38
180
|
return {
|
|
39
181
|
mode: "human",
|
|
40
182
|
apiBase: urlBase,
|
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,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,21 @@
|
|
|
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 { takeFlag, readPublicKey } from "../flags.mjs";
|
|
6
|
+
|
|
7
|
+
export async function run(ctx) {
|
|
8
|
+
const sub = ctx.args.shift();
|
|
9
|
+
if (sub !== "enroll") throw new Error(t(ctx.locale, "usageKeyEnroll"));
|
|
10
|
+
const keyPath = takeFlag(ctx.args, "public-key", join(homedir(), ".ssh", "id_ed25519.pub"));
|
|
11
|
+
if (keyPath !== "-" && !existsSync(keyPath)) {
|
|
12
|
+
// The default path is the interesting case: `key enroll` on a machine with
|
|
13
|
+
// no key reads a path the operator never typed, so name it and name the two
|
|
14
|
+
// ways out (task #480).
|
|
15
|
+
throw new Error(t(ctx.locale, "keyPublicKeyMissing", { path: keyPath, private: keyPath.replace(/\.pub$/i, "") }));
|
|
16
|
+
}
|
|
17
|
+
const publicKey = readPublicKey(keyPath);
|
|
18
|
+
const d = await ctx.api("POST", "/v1/keys", { publicKey });
|
|
19
|
+
ctx.emit(d, () => ctx.out(t(ctx.locale, "enrolled", { fingerprint: d.fingerprint, keyId: d.keyId })));
|
|
20
|
+
return ctx.exit(0);
|
|
21
|
+
}
|