@botiverse/stamp-cli 0.3.14 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,208 +0,0 @@
1
- /**
2
- * Agent CLI login (RFC 057). Ported from the Hands/testbed CLIs.
3
- *
4
- * 1. Local PKCE verifier; send only S256 challenge through Raft.
5
- * 2. Exact wrapper `$SLOCK_CLI_TRANSPORT_DIR/raft integration invoke
6
- * --service <slug> --action agent-login --json` (never PATH `raft`).
7
- * 3. Exchange grant + verifier at POST /api/auth/agent/exchange.
8
- * 4. Persist via @botiverse/agent-session-store.
9
- */
10
- import { spawnSync } from "node:child_process";
11
- import { randomBytes, createHash } from "node:crypto";
12
- import { writeAgentSession } from "@botiverse/agent-session-store";
13
- import { AgentError, agentFail } from "./errors.mjs";
14
-
15
- export const STAMP_SERVICE = "stamp";
16
- export const STAMP_DEFAULT_URL = "https://staging.stamp.build";
17
- export const STAMP_LEGACY_STAGING_URL = "https://github-staging.botiverse.dev";
18
- export const STAMP_LEGACY_DEFAULT_URL = "https://github.botiverse.dev";
19
- export const TOKEN_DEADLINE_MS = 20_000;
20
-
21
- function base64url(buf) {
22
- return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
23
- }
24
-
25
- export function generatePkce() {
26
- const verifier = base64url(randomBytes(64));
27
- const challenge = base64url(createHash("sha256").update(verifier).digest());
28
- return { verifier, challenge };
29
- }
30
-
31
- function hasExactKeys(o, keys) {
32
- const k = Object.keys(o);
33
- return k.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(o, key));
34
- }
35
-
36
- export function parseRfc3339(s) {
37
- if (typeof s !== "string") return null;
38
- if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(s)) return null;
39
- const t = Date.parse(s);
40
- return Number.isFinite(t) ? t : null;
41
- }
42
-
43
- const AGENT_GRANT_TTL_CEILING_MS = 300_000 + 120_000;
44
-
45
- export function parseAgentLoginInvoke(stdout, service, now) {
46
- let outer;
47
- try { outer = JSON.parse(stdout); } catch { agentFail("invoke_not_json"); }
48
- if (!outer || typeof outer !== "object") agentFail("invoke_not_object");
49
- if (outer.ok !== true) agentFail("invoke_failed");
50
- if (!hasExactKeys(outer, ["ok", "data"])) agentFail("invoke_envelope");
51
- const data = outer.data;
52
- if (!data || typeof data !== "object") agentFail("invoke_data");
53
- if (!hasExactKeys(data, ["service", "action", "status", "result"])) agentFail("invoke_data_fields");
54
- if (data.service !== service) agentFail("invoke_service");
55
- if (data.action !== "agent-login") agentFail("invoke_action");
56
- if (data.status !== 200) agentFail("invoke_http");
57
- const result = data.result;
58
- if (!result || typeof result !== "object") agentFail("grant_body");
59
- if (!hasExactKeys(result, ["schema", "service", "grant", "expires_at"])) agentFail("grant_fields");
60
- if (result.schema !== "raft-cli-agent-login-grant.v1") agentFail("grant_schema");
61
- if (result.service !== service) agentFail("grant_service");
62
- if (typeof result.grant !== "string" || result.grant.length === 0) agentFail("grant_missing");
63
- const exp = parseRfc3339(result.expires_at);
64
- if (exp === null) agentFail("grant_expires_at");
65
- if (exp <= now) agentFail("grant_expired");
66
- if (exp > now + AGENT_GRANT_TTL_CEILING_MS) agentFail("grant_ttl");
67
- return { grant: result.grant, expires_at: result.expires_at };
68
- }
69
-
70
- export function parseAgentSession(body, now) {
71
- if (!body || typeof body !== "object") agentFail("session_not_object");
72
- if (!hasExactKeys(body, ["schema", "token_type", "access_token", "access_expires_at", "refresh_token", "refresh_expires_at"])) {
73
- agentFail("session_fields");
74
- }
75
- if (body.schema !== "raft-cli-agent-session.v1") agentFail("session_schema");
76
- if (body.token_type !== "Bearer") agentFail("session_token_type");
77
- for (const k of ["access_token", "refresh_token"]) {
78
- if (typeof body[k] !== "string" || body[k].length === 0) agentFail("session_missing", { field: k });
79
- }
80
- const accessExp = parseRfc3339(body.access_expires_at);
81
- if (accessExp === null) agentFail("session_access_exp");
82
- if (accessExp <= now) agentFail("session_access_expired");
83
- if (body.refresh_expires_at !== null) {
84
- const refreshExp = parseRfc3339(body.refresh_expires_at);
85
- if (refreshExp === null) agentFail("session_refresh_exp");
86
- if (refreshExp <= now) agentFail("session_refresh_expired");
87
- }
88
- return body;
89
- }
90
-
91
- export const MAX_TOKEN_RESPONSE_BYTES = 64 * 1024;
92
-
93
- export async function readBoundedText(res, controller) {
94
- const declared = Number(res.headers?.get?.("content-length"));
95
- if (Number.isFinite(declared) && declared > MAX_TOKEN_RESPONSE_BYTES) {
96
- agentFail("token_size_limit");
97
- }
98
- const reader = res.body?.getReader?.();
99
- if (!reader) {
100
- const t = await res.text();
101
- if (t.length > MAX_TOKEN_RESPONSE_BYTES) agentFail("token_size_limit");
102
- return t;
103
- }
104
- if (controller?.signal) {
105
- const abort = () => { void reader.cancel().catch(() => {}); };
106
- if (controller.signal.aborted) abort();
107
- else controller.signal.addEventListener("abort", abort, { once: true });
108
- }
109
- const chunks = [];
110
- let total = 0;
111
- for (;;) {
112
- if (controller?.signal?.aborted) agentFail("token_deadline");
113
- let step;
114
- try {
115
- step = await reader.read();
116
- } catch (e) {
117
- if (controller?.signal?.aborted || e?.name === "AbortError") {
118
- agentFail("token_deadline");
119
- }
120
- throw e;
121
- }
122
- const { done, value } = step;
123
- if (done) break;
124
- if (value) {
125
- total += value.byteLength;
126
- if (total > MAX_TOKEN_RESPONSE_BYTES) {
127
- // Cancel the reader only — aborting the controller here races an unhandled AbortError.
128
- try { await reader.cancel(); } catch { /* ignore */ }
129
- agentFail("token_size_limit");
130
- }
131
- chunks.push(value);
132
- }
133
- }
134
- const out = new Uint8Array(total);
135
- let off = 0;
136
- for (const c of chunks) { out.set(c, off); off += c.byteLength; }
137
- return new TextDecoder().decode(out);
138
- }
139
-
140
- function defaultInvoke(raftBin, args) {
141
- const res = spawnSync(raftBin, args, { encoding: "utf8" });
142
- return { status: res.error ? null : res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "" };
143
- }
144
-
145
- export async function runAgentLogin(a, apiBase, opts = {}) {
146
- const service = opts.service ?? STAMP_SERVICE;
147
- const now = opts.now ?? Date.now();
148
- const { verifier, challenge } = generatePkce();
149
- const args = [
150
- "integration", "invoke",
151
- "--service", service,
152
- "--action", "agent-login",
153
- "--json",
154
- "--data-json", JSON.stringify({
155
- schema: "raft-cli-agent-login-request.v1",
156
- code_challenge: challenge,
157
- code_challenge_method: "S256",
158
- }),
159
- ];
160
- const runner = opts.invoke ?? ((a2) => defaultInvoke(a.raftBin, a2));
161
- const res = runner(args);
162
- if (res.status !== 0) {
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 });
173
- }
174
- const { grant } = parseAgentLoginInvoke(res.stdout, service, now);
175
-
176
- const fetchImpl = opts.fetchImpl ?? fetch;
177
- const deadlineMs = opts.deadlineMs ?? TOKEN_DEADLINE_MS;
178
- const controller = new AbortController();
179
- const timer = setTimeout(() => controller.abort(), deadlineMs);
180
- try {
181
- const exchangeRes = await fetchImpl(new URL("/api/auth/agent/exchange", apiBase).toString(), {
182
- method: "POST",
183
- headers: { "content-type": "application/json", accept: "application/json" },
184
- body: JSON.stringify({ schema: "raft-cli-agent-login-exchange.v1", grant, code_verifier: verifier }),
185
- redirect: "manual",
186
- signal: controller.signal,
187
- });
188
- const status = exchangeRes.status;
189
- if (status >= 300 && status < 400) {
190
- agentFail("exchange_redirect", { status });
191
- }
192
- if (!exchangeRes.ok) {
193
- agentFail("exchange_failed", { status });
194
- }
195
- const exchangeText = await readBoundedText(exchangeRes, controller);
196
- let exchangeBody;
197
- try { exchangeBody = JSON.parse(exchangeText); } catch { agentFail("exchange_not_json"); }
198
- const session = parseAgentSession(exchangeBody, now);
199
- writeAgentSession(a, service, session, apiBase);
200
- return session;
201
- } catch (e) {
202
- if (e instanceof AgentError) throw e;
203
- if (e?.name === "AbortError") agentFail("exchange_deadline");
204
- throw e;
205
- } finally {
206
- clearTimeout(timer);
207
- }
208
- }
@@ -1,192 +0,0 @@
1
- /**
2
- * Agent token auto-refresh + cross-process single-flight (RFC 057; ported from Hands/testbed).
3
- */
4
- import { openSync, closeSync, writeSync, readFileSync, existsSync, unlinkSync } from "node:fs";
5
- import { dirname, join } from "node:path";
6
- import { randomBytes } from "node:crypto";
7
- import { agentAuthPath, writeAgentSession } from "@botiverse/agent-session-store";
8
- import { parseAgentSession, readBoundedText, STAMP_SERVICE } from "./agent-login.mjs";
9
- import { AgentError, agentFail } from "./errors.mjs";
10
- import { storeMatchesOrigin } from "./auth.mjs";
11
-
12
- export const REFRESH_SKEW_MS = 60_000;
13
- const REFRESH_DEADLINE_MS = 20_000;
14
- const LOCK_WAIT_MS = 25_000;
15
- const LOCK_POLL_MS = 100;
16
-
17
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
- const newOwnerId = () => `${process.pid}:${randomBytes(12).toString("hex")}`;
19
-
20
- export function readStore(a, service = STAMP_SERVICE) {
21
- let path;
22
- try { path = agentAuthPath(a, service); } catch { return null; }
23
- if (!existsSync(path)) return null;
24
- try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
25
- }
26
-
27
- function accessExpiresWithinSkew(store, now) {
28
- const exp = Date.parse(store.access_expires_at);
29
- return !Number.isFinite(exp) || exp - now <= REFRESH_SKEW_MS;
30
- }
31
- function accessExpired(store, now) {
32
- const exp = Date.parse(store.access_expires_at);
33
- return !Number.isFinite(exp) || exp <= now;
34
- }
35
- export function refreshLockPath(a, service = STAMP_SERVICE) {
36
- return join(dirname(agentAuthPath(a, service)), ".auth.refresh.lock");
37
- }
38
-
39
- async function rotate(a, service, store, now, fetchImpl, deadlineMs, apiBase) {
40
- const targetBase = apiBase ?? store.api_base;
41
- const controller = new AbortController();
42
- const timer = setTimeout(() => controller.abort(), deadlineMs);
43
- try {
44
- const res = await fetchImpl(new URL("/api/auth/agent/refresh", targetBase).toString(), {
45
- method: "POST",
46
- headers: { "content-type": "application/json", accept: "application/json" },
47
- body: JSON.stringify({ schema: "raft-cli-agent-refresh.v1", refresh_token: store.refresh_token }),
48
- signal: controller.signal,
49
- redirect: "manual",
50
- });
51
- const status = res.status;
52
- if (status >= 300 && status < 400) {
53
- agentFail("refresh_redirect", { status });
54
- }
55
- if (!res.ok) agentFail("refresh_failed", { status });
56
- const text = await readBoundedText(res, controller);
57
- let body;
58
- try { body = JSON.parse(text); } catch { agentFail("refresh_not_json"); }
59
- const session = parseAgentSession(body, now);
60
- writeAgentSession(a, service, session, targetBase, () => new Date(now).toISOString());
61
- return session;
62
- } catch (e) {
63
- if (e instanceof AgentError) throw e;
64
- if (e?.name === "AbortError") agentFail("refresh_deadline");
65
- throw e;
66
- } finally {
67
- clearTimeout(timer);
68
- }
69
- }
70
-
71
- function successorIfRejected(store, rejectedAccess) {
72
- return rejectedAccess && store?.access_token && store.access_token !== rejectedAccess
73
- ? store.access_token
74
- : null;
75
- }
76
-
77
- export async function getFreshAgentAccessToken(a, opts = {}) {
78
- const service = opts.service ?? STAMP_SERVICE;
79
- const now = opts.now ?? Date.now();
80
- const store = readStore(a, service);
81
- if (!store) return null;
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;
85
- return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, false, opts.deadlineMs ?? REFRESH_DEADLINE_MS, undefined, opts.apiBase);
86
- }
87
-
88
- export async function forceRefreshAgentToken(a, opts = {}) {
89
- const service = opts.service ?? STAMP_SERVICE;
90
- const now = opts.now ?? Date.now();
91
- const store = readStore(a, service);
92
- if (!store) return null;
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;
95
- if (reused) return reused;
96
- return singleFlightRefresh(a, service, store, now, opts.fetchImpl ?? fetch, opts.sleepImpl ?? sleep, true, opts.deadlineMs ?? REFRESH_DEADLINE_MS, opts.rejectedAccess, opts.apiBase);
97
- }
98
-
99
- async function singleFlightRefresh(a, service, baseline, now, fetchImpl, sleepImpl, force, deadlineMs, rejectedAccess, apiBase) {
100
- const lock = refreshLockPath(a, service);
101
- const ownerId = newOwnerId();
102
- let acquired;
103
- try {
104
- const fd = openSync(lock, "wx");
105
- try { writeSync(fd, ownerId); } finally { try { closeSync(fd); } catch { /* ignore */ } }
106
- acquired = true;
107
- } catch (e) {
108
- if (e?.code !== "EEXIST") throw e;
109
- acquired = acquireIfDeadOwner(lock, ownerId);
110
- if (!acquired) return waitForNewerSession(a, service, baseline, now, force, sleepImpl, rejectedAccess, apiBase);
111
- }
112
- try {
113
- const fresh = readStore(a, service);
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).
118
- const reused = successorIfRejected(fresh, rejectedAccess);
119
- if (reused) return reused;
120
- if (!force && !accessExpiresWithinSkew(fresh, now)) return fresh.access_token;
121
- const session = await rotate(a, service, fresh, now, fetchImpl, deadlineMs, apiBase);
122
- return session.access_token;
123
- } finally {
124
- releaseOwnLock(lock, ownerId);
125
- }
126
- }
127
-
128
- export function releaseOwnLock(lock, ownerId) {
129
- try { if (readFileSync(lock, "utf8") === ownerId) unlinkSync(lock); } catch { /* gone or foreign */ }
130
- }
131
-
132
- export function acquireIfDeadOwner(lock, ownerId) {
133
- const ffd = acquireReaperFence(`${lock}.reap`);
134
- if (ffd === null) return false;
135
- try {
136
- let owner = "";
137
- try { owner = readFileSync(lock, "utf8"); } catch (e) { if (e?.code !== "ENOENT") return false; }
138
- if (owner) {
139
- const pid = ownerPid(owner);
140
- if (pid === null || ownerAlive(pid)) return false;
141
- try { unlinkSync(lock); } catch { /* vanished */ }
142
- }
143
- let fd;
144
- try { fd = openSync(lock, "wx"); } catch (e) { if (e?.code === "EEXIST") return false; throw e; }
145
- try { writeSync(fd, ownerId); } finally { try { closeSync(fd); } catch { /* ignore */ } }
146
- return true;
147
- } finally {
148
- try { closeSync(ffd); } catch { /* ignore */ }
149
- try { unlinkSync(`${lock}.reap`); } catch { /* ignore */ }
150
- }
151
- }
152
-
153
- function acquireReaperFence(fence) {
154
- try {
155
- const fd = openSync(fence, "wx");
156
- try { writeSync(fd, newOwnerId()); } catch { /* marker only */ }
157
- return fd;
158
- } catch {
159
- return null;
160
- }
161
- }
162
- function ownerPid(owner) {
163
- const m = /^(\d+):/.exec(owner);
164
- if (!m) return null;
165
- const pid = Number(m[1]);
166
- return Number.isInteger(pid) && pid > 0 ? pid : null;
167
- }
168
- function ownerAlive(pid) {
169
- try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
170
- }
171
-
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;
177
- const maxPolls = Math.ceil(LOCK_WAIT_MS / LOCK_POLL_MS);
178
- for (let i = 0; i < maxPolls; i += 1) {
179
- await sleepImpl(LOCK_POLL_MS);
180
- const cur = readStore(a, service);
181
- if (cur && !storeMatchesOrigin(cur, targetBase)) continue;
182
- const reused = successorIfRejected(cur, rejectedAccess);
183
- if (reused) return reused;
184
- if (cur && cur.refresh_token !== baseline.refresh_token) return cur.access_token;
185
- }
186
- const cur = readStore(a, service);
187
- if (cur && !storeMatchesOrigin(cur, targetBase)) agentFail("notLoggedIn");
188
- const reused = successorIfRejected(cur, rejectedAccess);
189
- if (reused) return reused;
190
- if (!force && cur && !accessExpired(cur, now)) return cur.access_token;
191
- agentFail("refresh_wait_timeout");
192
- }
package/lib/auth.mjs DELETED
@@ -1,202 +0,0 @@
1
- import { unlinkSync, existsSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
- import { admitAgent, agentAuthPath } from "@botiverse/agent-session-store";
4
- import { STAMP_LEGACY_DEFAULT_URL, STAMP_LEGACY_STAGING_URL, STAMP_SERVICE } from "./agent-login.mjs";
5
- import { getFreshAgentAccessToken, forceRefreshAgentToken, readStore } from "./agent-refresh.mjs";
6
- import { AgentError, agentFail } from "./errors.mjs";
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
- }
111
- const admission = admitAgent(env);
112
- if (admission.kind === "fail_closed") {
113
- throw admissionFailure(admission, env);
114
- }
115
- if (admission.kind === "agent") {
116
- const a = admission.env;
117
- const store = readStore(a, service);
118
- const storedBase = store?.api_base;
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))
128
- ? urlBase
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
- let usableStore = storeMatchesOrigin(store, apiBase) ? store : undefined;
144
- // A session written after this resolve (`login` itself) becomes usable
145
- // for the rest of the same command: login then enrolls the agent's key.
146
- const refreshStore = () => {
147
- if (usableStore) return;
148
- const fresh = readStore(a, service);
149
- if (storeMatchesOrigin(fresh, apiBase)) usableStore = fresh;
150
- };
151
- const storedOriginElsewhere = !usableStore && storedOrigin !== null ? storedOrigin : null;
152
- return {
153
- mode: "agent",
154
- apiBase,
155
- agentEnv: a,
156
- service,
157
- // The agent's own directory for Stamp state, beside its session (artin
158
- // 09-27): its SSH key, the enrollment record and the pinned host key.
159
- // Never ~/.ssh or ~/.stamp, which every agent on a machine user shares.
160
- stateDir: dirname(agentAuthPath(a, service)),
161
- async token() {
162
- refreshStore();
163
- if (!usableStore) {
164
- if (storedOriginElsewhere !== null) {
165
- const sibling = siblingBinaryFor(storedOriginElsewhere);
166
- throw new AgentError(sibling && sibling !== cliName ? "sessionOriginMismatchSibling" : "sessionOriginMismatch", {
167
- stored: storedOriginElsewhere,
168
- target: originOf(apiBase) ?? apiBase,
169
- cli: cliName,
170
- other: sibling,
171
- });
172
- }
173
- throw new AgentError("notLoggedIn");
174
- }
175
- const tok = await getFreshAgentAccessToken(a, { service, apiBase });
176
- if (!tok) throw new AgentError("notLoggedIn");
177
- return tok;
178
- },
179
- async retryToken(rejectedAccess) {
180
- if (!usableStore) return null;
181
- return forceRefreshAgentToken(a, { service, apiBase, rejectedAccess });
182
- },
183
- logout() {
184
- const p = agentAuthPath(a, service);
185
- if (existsSync(p)) unlinkSync(p);
186
- return p;
187
- },
188
- };
189
- }
190
- const token = env.STAMP_TOKEN || "";
191
- assertCoherentPair(urlBase, service);
192
- return {
193
- mode: "human",
194
- apiBase: urlBase,
195
- async token() {
196
- if (!token) throw new AgentError("stampTokenMissing");
197
- return token;
198
- },
199
- async retryToken() { return null; },
200
- logout() { return null; },
201
- };
202
- }