@botbuddy/cli 1.75.3 → 1.77.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.77.0
4
+
5
+ - The bb-status band's project row shows BB's Must + unsure progress (BOT-3259). The badge is the percent alone, for example `88%`, followed by `22 done · 3 left · 3 unsure`: done and left count Must tickets and tickets with no Must/Could milestone, and unsure counts the open ones with no milestone. Could, canceled and duplicate tickets no longer count. Each number links to the project drawer filtered to those tickets (`/kanban?card=project:<id>&progress=done|left|unsure`). The figure comes from BB (`v_project_progress`, through `get_session_status` and `get_epic_health`), so it matches the drawer exactly; against an older MCP the row keeps its previous `done/total`. bb-status plugin 1.5.0.
6
+
7
+ ## 1.76.0
8
+
9
+ - A stored credential is bound to the BotBuddy server that issued it and is never sent to another (BOT-3257). Before, with `BOTBUDDY_SERVER_URL` pointing at staging, every owner-authenticated command (`bb mcp setup` included) sent the machine's production client key to staging, and a staging `bb login` overwrote the production one. Production keeps `~/.botbuddy/config.json` and the Keychain service `BOTBUDDY_CLIENT_KEY`; any other server gets `~/.botbuddy/servers/<origin>/config.json` and `BOTBUDDY_CLIENT_KEY@<origin>`. A login written before this release has no `server_origin` and counts as production-only, so it keeps working. With no login for the target server while another server's exists, a command stops before any request with `credential_origin_mismatch`, naming both origins and the `bb login` to run. The worktree session cache records `server_origin` and is never presented to another server; the default `BOTBUDDY_MCP_KEY` binding is production-only; `bb mcp setup` against another server refuses the default variable (`mcp_env_required_for_server`). `bb logout` clears only the current server's slot. Explicit credentials (a session-token flag or export, or a binding naming another variable) are unchanged.
10
+
3
11
  ## 1.75.2
4
12
 
5
13
  - The bb-status band connects a new Claude Code session in a reused worktree whose cache belongs to a Claude session that has gone **and** whose BB session has expired (BOT-3252). Before, the band moved such a cache aside only while the old BB session was still live; for an expired one it bootstrapped with the stale cache in place, the bootstrap's `close_session` on the owner sign-in was refused with `agent_identity_required`, and the band showed "BB identity belongs to another session" forever. It now sets the cache aside to `.botbuddy/agent-state.superseded-<id>.json` in that case too (and for an expired holder with no transcript on this host), under the same state lock, and restores it if the bootstrap fails. A holder whose Claude session is active is still never taken over.
@@ -11,7 +11,7 @@
11
11
  "name": "bb-status",
12
12
  "source": "./bb-status",
13
13
  "description": "BB session status above the prompt: tickets, PRs with review counts, epic, staging, context use and active waits, for BotBuddy and Supply Guard sessions",
14
- "version": "1.4.4"
14
+ "version": "1.5.0"
15
15
  },
16
16
  {
17
17
  "name": "bb-session",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bb-status",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "BB session status above the prompt: tickets, PRs with review counts, epic, staging, context use and active waits, live only while the session is on screen.",
5
5
  "author": {
6
6
  "name": "BotBuddy"
@@ -131,6 +131,19 @@ function validCounts(c) {
131
131
  COUNT_KEYS.reduce((n, k) => n + c[k], 0) === c.total
132
132
  );
133
133
  }
134
+ // BOT-3259: BB's Must + unsure figure; unsure is a subset of remaining.
135
+ const PROGRESS_KINDS = [
136
+ ["complete", "done", "done"],
137
+ ["remaining", "left", "left"],
138
+ ["unsure", "unsure", "unsure"],
139
+ ];
140
+ function validProgress(p) {
141
+ return (
142
+ !!p &&
143
+ PROGRESS_KINDS.every(([k]) => Number.isSafeInteger(p[k]) && p[k] >= 0 && p[k] <= 100000) &&
144
+ p.unsure <= p.remaining
145
+ );
146
+ }
134
147
  function countsText(c) {
135
148
  return [c.done + " done", c.in_progress + " in progress", c.blocked + " blocked", c.todo + " todo"].join(" · ");
136
149
  }
@@ -196,7 +209,8 @@ function validSnapshot(value, harness, now) {
196
209
  (value.epic.total === undefined ||
197
210
  (Number.isSafeInteger(value.epic.total) && Number.isSafeInteger(value.epic.done) && value.epic.done >= 0 && value.epic.done <= value.epic.total)) &&
198
211
  (value.epic.role === undefined || value.epic.role === "coordinator") &&
199
- (value.epic.counts === undefined || validCounts(value.epic.counts))
212
+ (value.epic.counts === undefined || validCounts(value.epic.counts)) &&
213
+ (value.epic.progress === undefined || validProgress(value.epic.progress))
200
214
  )) ||
201
215
  (value.blockers !== null &&
202
216
  !(value.tenant === "botbuddy" && Array.isArray(value.blockers) && value.blockers.length <= 100)) ||
@@ -252,6 +266,8 @@ const APP = "https://app.bot-buddy.ai";
252
266
  const LINKS = {
253
267
  ticket: (key) => APP + "/kanban?card=ticket:" + key,
254
268
  project: (id) => APP + "/kanban?card=project:" + id,
269
+ // BOT-3259: the project drawer, filtered to one progress set (done|left|unsure).
270
+ projectProgress: (id, kind) => APP + "/kanban?card=project:" + id + "&progress=" + kind,
255
271
  pr: (repo, n) => APP + "/kanban?card=pr:" + repo + "%23" + n,
256
272
  // BOT-3223 AC-1: a wait badge opens that wait on BB's Waits page.
257
273
  wait: (id) => APP + "/waits?wait=" + id,
@@ -909,7 +925,12 @@ function bandLine(el, spec, widths, right) {
909
925
  if (id.label) ids.push(el.Link({ href: id.href, label: id.label }));
910
926
  if (id.out) ids.push(el.Text({ children: [" "] }), el.Link({ href: id.out, label: "↗" }));
911
927
  });
912
- const title = [el.Text({ wrap: "wrap", dimColor: spec.dim || undefined, children: [spec.title] })];
928
+ const title = [];
929
+ // BOT-3259: the project's counts, each opening the drawer filtered to that set.
930
+ for (const link of spec.links || []) {
931
+ title.push(el.Link({ href: link.href, label: link.label }), dim(el, " · "));
932
+ }
933
+ title.push(el.Text({ wrap: "wrap", dimColor: spec.dim || undefined, children: [spec.title] }));
913
934
  if (spec.note) title.push(dim(el, " " + spec.note));
914
935
  const children = [
915
936
  el.Box({ key: spec.key + "-ids", flexDirection: "row", width: widths.ids, flexShrink: 0, children: ids }),
@@ -1162,7 +1183,15 @@ function bandLines(el, $, inPane) {
1162
1183
  iconSource: inked(epicIcon(s.epic.state, s.epic.percent), badgeColors(epicHex(s.epic.state)).bg),
1163
1184
  iconAlt: "project " + s.epic.state + " " + s.epic.percent + "%",
1164
1185
  hex: epicHex(s.epic.state),
1165
- status: [{ text: s.epic.percent + "%" }, ...(Number.isSafeInteger(s.epic.total) && s.epic.total > 0 ? [{ text: s.epic.done + "/" + s.epic.total, muted: true }] : [])],
1186
+ // BOT-3259: with BB's Must + unsure figure the badge is the percent alone and
1187
+ // the counts follow as links; an older snapshot keeps its done/total.
1188
+ status: [
1189
+ { text: s.epic.percent + "%" },
1190
+ ...(!s.epic.progress && Number.isSafeInteger(s.epic.total) && s.epic.total > 0 ? [{ text: s.epic.done + "/" + s.epic.total, muted: true }] : []),
1191
+ ],
1192
+ links: s.epic.progress
1193
+ ? PROGRESS_KINDS.map(([k, label, kind]) => ({ label: s.epic.progress[k] + " " + label, href: LINKS.projectProgress(s.epic.id, kind) }))
1194
+ : [],
1166
1195
  // BOT-3213: the project a coordinator session runs, with its tickets by state.
1167
1196
  title: s.epic.role === "coordinator"
1168
1197
  ? "Coordinating · " + (s.epic.counts ? countsText(s.epic.counts) + " · " : "") + s.epic.name
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.75.3",
3
- "source_commit": "b5af47529a41af38cdcd79b62eedd3c31cbd09e9",
4
- "source_sha256": "000bf4d0d2feaedf9549481a4d08d0f581c69d3852919e19042d8168c7f93985",
2
+ "release_version": "1.77.0",
3
+ "source_commit": "08cb1b1f5270e4ee981f6b525b15af0441d06e2e",
4
+ "source_sha256": "81ec69696b1ee15b6210102383e8e799659bcba7b3c0bde2911ce51e51b2aa84",
5
5
  "target": "darwin-arm64",
6
- "sha256": "3e60dd08632c15f55a2c8f25f53c1dded730d773c2502e31ba66864f1d4b5266"
6
+ "sha256": "5f535e56d83f0112fc4ac9c3fa968f022df2d8cb8bf1fdf31892faa4a2000527"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.75.3",
3
- "source_commit": "b5af47529a41af38cdcd79b62eedd3c31cbd09e9",
4
- "source_sha256": "000bf4d0d2feaedf9549481a4d08d0f581c69d3852919e19042d8168c7f93985",
2
+ "release_version": "1.77.0",
3
+ "source_commit": "08cb1b1f5270e4ee981f6b525b15af0441d06e2e",
4
+ "source_sha256": "81ec69696b1ee15b6210102383e8e799659bcba7b3c0bde2911ce51e51b2aa84",
5
5
  "target": "linux-x64",
6
- "sha256": "1cfebb40878a9af24539cf249549cdb02854b7878c3823294586244b3171410c"
6
+ "sha256": "58d108a786afd745ddf1994ac8f2efe0c682bc72078b033c5876622a7163d595"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.75.3",
4
- "source_commit": "b5af47529a41af38cdcd79b62eedd3c31cbd09e9",
5
- "source_sha256": "000bf4d0d2feaedf9549481a4d08d0f581c69d3852919e19042d8168c7f93985",
3
+ "release_version": "1.77.0",
4
+ "source_commit": "08cb1b1f5270e4ee981f6b525b15af0441d06e2e",
5
+ "source_sha256": "81ec69696b1ee15b6210102383e8e799659bcba7b3c0bde2911ce51e51b2aa84",
6
6
  "targets": {
7
7
  "darwin-arm64": {
8
8
  "goos": "darwin",
9
9
  "goarch": "arm64",
10
10
  "binary": "daemon/bin/darwin-arm64/botbuddy-daemon",
11
- "sha256": "3e60dd08632c15f55a2c8f25f53c1dded730d773c2502e31ba66864f1d4b5266",
11
+ "sha256": "5f535e56d83f0112fc4ac9c3fa968f022df2d8cb8bf1fdf31892faa4a2000527",
12
12
  "mode": "0755"
13
13
  },
14
14
  "linux-x64": {
15
15
  "goos": "linux",
16
16
  "goarch": "amd64",
17
17
  "binary": "daemon/bin/linux-x64/botbuddy-daemon",
18
- "sha256": "1cfebb40878a9af24539cf249549cdb02854b7878c3823294586244b3171410c",
18
+ "sha256": "58d108a786afd745ddf1994ac8f2efe0c682bc72078b033c5876622a7163d595",
19
19
  "mode": "0755"
20
20
  }
21
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botbuddy/cli",
3
- "version": "1.75.3",
3
+ "version": "1.77.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,8 +2,7 @@
2
2
  // without ever printing the token unless the operator explicitly requests an
3
3
  // export snippet for the current shell.
4
4
  import { readAgentBinding } from "./wait-profile.mjs";
5
- import { resolveOwnerToken, CLIENT_KEY_SERVICE, OWNER_TOKEN_SERVICE } from "./cli-credentials.mjs";
6
- import { readKeychainSecret } from "./agent-credential-store.mjs";
5
+ import { resolveOwnerToken } from "./cli-credentials.mjs";
7
6
  import { getConfig } from "./config.mjs";
8
7
  import { isAgentStateFresh, readAgentState } from "./agent-state.mjs";
9
8
  import { selfHealAgentSession } from "./agent-session.mjs";
@@ -162,8 +161,8 @@ function applyStackLeaseCapability(report, capability) {
162
161
  export function readClientKeyStrict() {
163
162
  return resolveOwnerToken({
164
163
  getConfig,
165
- keychainRead: () => readKeychainSecret(CLIENT_KEY_SERVICE, { strict: true }),
166
- keychainReadLegacy: () => readKeychainSecret(OWNER_TOKEN_SERVICE, { strict: true }),
164
+ // BOT-3257: strict reads of THIS server origin's Keychain slot.
165
+ strict: true,
167
166
  });
168
167
  }
169
168
 
@@ -9,8 +9,9 @@ import { mkdir, stat } from "node:fs/promises";
9
9
  import { createHash } from "node:crypto";
10
10
  import { callToolJson } from "./api.mjs";
11
11
  import { readAgentBinding } from "./wait-profile.mjs";
12
- import { resolveOwnerToken, CLIENT_KEY_SERVICE, OWNER_TOKEN_SERVICE } from "./cli-credentials.mjs";
13
- import { readKeychainSecret } from "./agent-credential-store.mjs";
12
+ import { resolveOwnerToken } from "./cli-credentials.mjs";
13
+ import { configuredServerUrl, serverOrigin, recordOrigin, isProductionOrigin, CredentialOriginError, PRODUCTION_ORIGIN } from "./credential-origin.mjs";
14
+ import { DEFAULT_MCP_ENV_VAR, LEGACY_MCP_ENV_VAR } from "./agent-credential-store.mjs";
14
15
  import { getConfig } from "./config.mjs";
15
16
  import { acquireStackLock } from "./stack-file-lock.mjs";
16
17
  import { AGENT_KEY_RE, readAgentSessionTokenEnv, legacyAgentAliasHint } from "./agent-key.mjs";
@@ -186,7 +187,10 @@ export async function resolveAgentSessionCredential({
186
187
  const cached = await readState(cwd);
187
188
  // BOT-2425: a cache written for another harness session (or before the harness
188
189
  // id was recorded) is not this session's identity; re-resolve it instead.
189
- if (cached && isFresh(cached, new Date()) && cacheBelongsToHarness(cached, harnessSessionIdFromEnv(env))) {
190
+ // BOT-3257: a cache minted by another server origin (untagged = production) is
191
+ // never presented here; it is treated as absent, exactly like a stale cache.
192
+ if (cached && isFresh(cached, new Date()) && cacheBelongsToHarness(cached, harnessSessionIdFromEnv(env))
193
+ && cacheBelongsToServer(cached, env)) {
190
194
  warnLegacyResolvedToken(cached.agent_session_token, warn);
191
195
  return withIdentity({ token: cached.agent_session_token, sessionId: explicitSessionId ?? cached.session_id, agentId: cached.agent_id, source: "cache" }, cached);
192
196
  }
@@ -196,6 +200,16 @@ export async function resolveAgentSessionCredential({
196
200
  return healed;
197
201
  }
198
202
 
203
+ function targetServerOrigin(env) {
204
+ return serverOrigin(configuredServerUrl(env));
205
+ }
206
+
207
+ function cacheBelongsToServer(cached, env) {
208
+ let target;
209
+ try { target = serverOrigin(configuredServerUrl(env)); } catch { return false; }
210
+ return recordOrigin(cached) === target;
211
+ }
212
+
199
213
  // A cached/minted token carrying the legacy bb_agent_ prefix → one canonical nudge
200
214
  // (freshly minted tokens are bb_sess_, so this normally fires only for a stale
201
215
  // cached bb_agent_ token). flag/env aliases never reach here — those branches
@@ -217,8 +231,8 @@ export async function selfHealAgentSession({
217
231
  // `client_key_required` code that stack's operator fallback treats as "no key".
218
232
  ownerToken = () => resolveOwnerToken({
219
233
  getConfig,
220
- keychainRead: () => readKeychainSecret(CLIENT_KEY_SERVICE, { strict: true }),
221
- keychainReadLegacy: () => readKeychainSecret(OWNER_TOKEN_SERVICE, { strict: true }),
234
+ // BOT-3257: strict reads of THIS server origin's Keychain slot.
235
+ strict: true,
222
236
  }),
223
237
  call = callToolJson,
224
238
  writeState = writeAgentState, lock = withLock, machineId = resolveMachineId,
@@ -252,11 +266,16 @@ export async function selfHealAgentSession({
252
266
  // BOT-2425: the harness session this process runs in (exported by the
253
267
  // SessionStart hook). A cache belongs to it only when it recorded the same id.
254
268
  const envHarness = harnessSessionIdFromEnv(env);
255
- const ownCache = !!current && cacheBelongsToHarness(current, envHarness);
269
+ // BOT-3257 (Codex P1): a cache minted by another server origin is never
270
+ // reused, renewed or compared here — its token must not reach this server.
271
+ // It is treated as absent: a mint for this origin replaces it.
272
+ const sameServer = !current || cacheBelongsToServer(current, env);
273
+ const ownCache = !!current && sameServer && cacheBelongsToHarness(current, envHarness);
256
274
  let bound;
257
275
  let registrationWorktree = cwd;
258
276
  if (renewal) {
259
277
  if (!current) throw missing("session_mint_unauthorized", "The cached session identity is no longer available; refusing to recreate a removed session.");
278
+ if (!sameServer) throw new CredentialOriginError({ credentialOrigin: recordOrigin(current), targetOrigin: targetServerOrigin(env), credential: "agent session" });
260
279
  bound = await binding(cwd);
261
280
  if (!bound?.tenant) throw missing("tenant_binding_required", "No .botbuddy-agent.json binding was found; cannot verify the rejected session's tenant.");
262
281
  registrationWorktree = await worktreeRoot(cwd);
@@ -275,6 +294,7 @@ export async function selfHealAgentSession({
275
294
  }
276
295
  }
277
296
  if (!force && !renewal && current && ownCache && isFresh(current, now())) {
297
+ // (ownCache implies sameServer.)
278
298
  // A fresh cache is reused without a register call, so no capability verdict is
279
299
  // available here (bb doctor --fix forces a mint to (re)establish + report it).
280
300
  return withIdentity({ token: current.agent_session_token, sessionId: sessionId ?? current.session_id, agentId: current.agent_id, source: "cache", ticketSignals: null, stackLeaseCapability: null }, current);
@@ -284,6 +304,9 @@ export async function selfHealAgentSession({
284
304
  try {
285
305
  owner = await ownerToken();
286
306
  } catch (error) {
307
+ // BOT-3257 (Codex P1): an origin refusal is a verdict, not an unreachable
308
+ // credential store — never let it switch to the MCP-key fallback below.
309
+ if (error instanceof CredentialOriginError || error?.code === "server_url_invalid") throw error;
287
310
  ownerError = error;
288
311
  }
289
312
  bound ??= await binding(cwd);
@@ -299,6 +322,11 @@ export async function selfHealAgentSession({
299
322
  // before. No key in the env → the errors below, unchanged.
300
323
  const mcpEnv = typeof bound?.mcpEnv === "string" && bound.mcpEnv ? bound.mcpEnv : null;
301
324
  const mcpKey = ownerError && mcpEnv && typeof env?.[mcpEnv] === "string" && env[mcpEnv] ? env[mcpEnv] : null;
325
+ // BOT-3257 (Codex P1): the default MCP variable is production's slot; the
326
+ // fallback never sends it to another origin (same rule as resolveAgentKey).
327
+ if (mcpKey && (mcpEnv === DEFAULT_MCP_ENV_VAR || mcpEnv === LEGACY_MCP_ENV_VAR) && !isProductionOrigin(targetServerOrigin(env))) {
328
+ throw new CredentialOriginError({ credentialOrigin: PRODUCTION_ORIGIN, targetOrigin: targetServerOrigin(env), credential: `${mcpEnv} MCP key` });
329
+ }
302
330
  if (!mcpKey) {
303
331
  if (ownerError) {
304
332
  // BOT-1750 (Codex R4 P2): the client-key read FAILED (a locked/erroring
@@ -1,5 +1,6 @@
1
1
  // BOT-1649 — a per-worktree, gitignored cache for the short-lived agent session.
2
2
  // It deliberately holds a session token (mode 0600), never a durable client key.
3
+ import { configuredServerUrl, serverOrigin } from "./credential-origin.mjs";
3
4
  import { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
5
6
  import { dirname, join, parse, resolve } from "node:path";
@@ -118,6 +119,8 @@ function validState(value) {
118
119
  if (value.harness_session_id !== undefined
119
120
  && !(typeof value.harness_session_id === "string" && UUID_RE.test(value.harness_session_id))) return false;
120
121
  // BOT-1650: the nonsecret incarnation fence for close/heartbeat idempotency.
122
+ // BOT-3257: the server origin that minted this session. Untagged = production.
123
+ if (value.server_origin !== undefined && !(typeof value.server_origin === "string" && value.server_origin.length > 0)) return false;
121
124
  if (value.session_token_generation !== undefined
122
125
  && !(typeof value.session_token_generation === "string" && UUID_RE.test(value.session_token_generation))) return false;
123
126
  return true;
@@ -152,8 +155,12 @@ export async function readAgentState(cwd = process.cwd()) {
152
155
  }
153
156
 
154
157
  /** Atomically replace cache content and ensure the destination remains owner-only. */
155
- export async function writeAgentState(cwd, state, { platform = process.platform, restrictAcl = restrictWindowsAcl, restrictAclDir = restrictWindowsAclDir } = {}) {
158
+ export async function writeAgentState(cwd, state, { platform = process.platform, restrictAcl = restrictWindowsAcl, restrictAclDir = restrictWindowsAclDir, env = process.env } = {}) {
156
159
  if (!validState(state)) throw new Error("agent state is missing required fields");
160
+ // BOT-3257: a session is minted by the server this process targets; record its
161
+ // origin so the cache is never presented to a different server. An existing
162
+ // tag (a renewal rewriting the same session) is kept.
163
+ if (state.server_origin === undefined) state = { ...state, server_origin: serverOrigin(configuredServerUrl(env)) };
157
164
  const path = await agentStatePath(cwd);
158
165
  const directory = dirname(path);
159
166
  await mkdir(directory, { recursive: true, mode: 0o700 });
package/src/api.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getConfig, SERVER_URL } from "./config.mjs";
2
2
  import { resolveOwnerToken, resolveAgentKey } from "./cli-credentials.mjs";
3
+ import { CredentialOriginError } from "./credential-origin.mjs";
3
4
  import { readAgentBinding } from "./wait-profile.mjs";
4
5
  import { AGENT_KEY_RE } from "./agent-key.mjs";
5
6
  // BOT-1864: api.mjs ↔ agent-session.mjs is a deliberate import cycle — each side
@@ -71,6 +72,7 @@ async function authHeader(toolName = null, { resolveAuth = resolveCallAuth, exit
71
72
  const fail = (msg) => { console.error(`${red("✗")} ${msg}`); process.exit(exitCode); };
72
73
  const code = resolved.error?.error;
73
74
  if (code === "token_expired") fail(`Token expired. Run: ${cyan("botbuddy login")} to re-authenticate.`);
75
+ if (code === "credential_origin_mismatch" || code === "server_url_invalid") fail(resolved.error.message);
74
76
  if (code === "session_token_malformed") {
75
77
  fail(`The agent session token has an unexpected shape (source: ${resolved.error.source ?? "unknown"}). Run: ${cyan("bb doctor --fix")} in this checkout.`);
76
78
  }
@@ -356,13 +358,32 @@ export async function resolveCallAuth({
356
358
  return { auth: { "x-agent-api-key": session.token }, source: session.source ?? null, sessionToken: true };
357
359
  }
358
360
  }
359
- const owner = await resolveOwner();
361
+ // BOT-3257: a stored credential issued by another server origin is refused
362
+ // locally (CredentialOriginError) — never sent. An explicitly chosen binding
363
+ // key may still authenticate; only when nothing else does is the mismatch the
364
+ // answer, so the operator learns why rather than seeing "not authenticated".
365
+ let originMismatch = null;
366
+ const refusedForOrigin = async (fn) => {
367
+ try {
368
+ return await fn();
369
+ } catch (error) {
370
+ if (error instanceof CredentialOriginError || error?.code === "server_url_invalid") {
371
+ originMismatch ??= error;
372
+ return null;
373
+ }
374
+ throw error;
375
+ }
376
+ };
377
+ const owner = await refusedForOrigin(() => resolveOwner());
360
378
  if (owner && !(owner.expiresAt && Date.now() >= owner.expiresAt)) {
361
379
  return { auth: { Authorization: `Bearer ${owner.token}` }, source: "owner", ownerExpiresAt: owner.expiresAt ?? null };
362
380
  }
363
- const agentKey = await resolveAgentKeyFn();
381
+ const agentKey = await refusedForOrigin(() => resolveAgentKeyFn());
364
382
  if (agentKey) return { auth: { "x-agent-api-key": agentKey }, source: "mcp_key" };
365
383
  if (owner) return { error: { ok: false, auth: true, error: "token_expired" } };
384
+ if (originMismatch) {
385
+ return { error: { ok: false, auth: true, error: originMismatch.code, message: originMismatch.message, recovery: originMismatch.recovery ?? null } };
386
+ }
366
387
  return { error: { ok: false, auth: true, error: "not_authenticated" } };
367
388
  }
368
389
 
@@ -24,6 +24,22 @@ import {
24
24
  deleteKeychainSecret,
25
25
  } from "./agent-credential-store.mjs";
26
26
  import { resolveAgentBinding } from "./wait-profile.mjs";
27
+ import { readFileSync, readdirSync } from "node:fs";
28
+ import { join } from "node:path";
29
+ import { homedir } from "node:os";
30
+ import {
31
+ PRODUCTION_ORIGIN,
32
+ PRODUCTION_CLIENT_KEY_SERVICE,
33
+ CredentialOriginError,
34
+ assertCredentialOrigin,
35
+ clientKeyService,
36
+ configFileFor,
37
+ configuredServerUrl,
38
+ isProductionOrigin,
39
+ serverOrigin,
40
+ serversDir,
41
+ } from "./credential-origin.mjs";
42
+ import { DEFAULT_MCP_ENV_VAR, LEGACY_MCP_ENV_VAR } from "./agent-credential-store.mjs";
27
43
 
28
44
  // BOT-1574: the per-machine CLIENT KEY. `botbuddy login` mints a user-mode OAuth
29
45
  // token (BOT-1571) — tenant-agnostic, pins one tenant per request against the
@@ -33,7 +49,40 @@ import { resolveAgentBinding } from "./wait-profile.mjs";
33
49
  // per-session token (bb_sess_), so a setup credential is never mistaken for an
34
50
  // agent. (The wire format stays `mcp_at_`; "client key" is the kind, not a new
35
51
  // prefix — the OAuth token format is out of scope for BOT-1574.)
36
- export const CLIENT_KEY_SERVICE = "BOTBUDDY_CLIENT_KEY";
52
+ //
53
+ // BOT-3257: this is the PRODUCTION service. A login against any other server
54
+ // origin uses `clientKeyService(origin)` (BOTBUDDY_CLIENT_KEY@<origin>), so it
55
+ // never overwrites — and is never read in place of — the production key.
56
+ export const CLIENT_KEY_SERVICE = PRODUCTION_CLIENT_KEY_SERVICE;
57
+
58
+ // The non-secret config keys that mark a stored login (BOT-3257).
59
+ const LOGIN_RECORD_KEYS = ["access_token", "client_id", "token_expires_at"];
60
+
61
+ function hasLoginRecord(cfg) {
62
+ return Boolean(cfg) && LOGIN_RECORD_KEYS.some((key) => cfg[key] != null && cfg[key] !== "");
63
+ }
64
+
65
+ function readJson(path) {
66
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
67
+ }
68
+
69
+ // BOT-3257: is there a login stored for an origin OTHER than `targetOrigin`?
70
+ // Used only to name the mismatch when the target's own slot is empty; it reads
71
+ // non-secret metadata and never sends anything.
72
+ export function findForeignLoginOrigin(targetOrigin, { home = homedir() } = {}) {
73
+ const candidates = [];
74
+ if (!isProductionOrigin(targetOrigin)) candidates.push(configFileFor(PRODUCTION_ORIGIN, home));
75
+ try {
76
+ for (const entry of readdirSync(serversDir(home))) candidates.push(join(serversDir(home), entry, "config.json"));
77
+ } catch { /* no other origins */ }
78
+ for (const path of candidates) {
79
+ const cfg = readJson(path);
80
+ if (!hasLoginRecord(cfg)) continue;
81
+ const origin = typeof cfg.server_origin === "string" && cfg.server_origin ? cfg.server_origin : PRODUCTION_ORIGIN;
82
+ if (origin !== targetOrigin) return origin;
83
+ }
84
+ return null;
85
+ }
37
86
 
38
87
  // The legacy service the same token was stored under before BOT-1574. Still read
39
88
  // (so an already-logged-in user keeps working across the upgrade without
@@ -75,13 +124,16 @@ export function sanitizeConfigSecrets(config, { platform = process.platform, exi
75
124
  export async function migrateConfigSecrets(config, {
76
125
  platform = process.platform,
77
126
  exists,
127
+ // BOT-3257: migrate into the Keychain service of the origin this config.json
128
+ // belongs to (untagged = production), never another origin's slot.
129
+ service = clientKeyServiceForRecord(config),
78
130
  // `createOnly`: the migration write must not overwrite a token another process
79
131
  // wrote after our empty-slot read (BOT-1569 Codex P2 TOCTOU).
80
- keychainWrite = (value) => writeKeychainSecret(CLIENT_KEY_SERVICE, value, { createOnly: true }),
132
+ keychainWrite = (value) => writeKeychainSecret(service, value, { createOnly: true }),
81
133
  // `strict`: a transient READ failure throws (fail closed) instead of reading as
82
134
  // an empty slot, so the migration never overwrites a live stored token because
83
135
  // the lookup momentarily failed (BOT-1569 Codex P2).
84
- keychainRead = () => readKeychainSecret(CLIENT_KEY_SERVICE, { strict: true }),
136
+ keychainRead = () => readKeychainSecret(service, { strict: true }),
85
137
  warn = (message) => console.error(message),
86
138
  } = {}) {
87
139
  const out = { ...(config ?? {}) };
@@ -173,6 +225,15 @@ export async function migrateConfigSecrets(config, {
173
225
  return { config: out, changed, migrated };
174
226
  }
175
227
 
228
+ function clientKeyServiceForRecord(config) {
229
+ const tagged = config?.server_origin;
230
+ try {
231
+ return clientKeyService(typeof tagged === "string" && tagged ? serverOrigin(tagged) : PRODUCTION_ORIGIN);
232
+ } catch {
233
+ return clientKeyService(PRODUCTION_ORIGIN);
234
+ }
235
+ }
236
+
176
237
  // Persist the owner OAuth token. Non-secret metadata always goes to config.json;
177
238
  // the token itself goes to the Keychain on darwin, or (with a warning) stays in
178
239
  // the 0600 config.json where no Keychain exists.
@@ -181,20 +242,26 @@ export async function persistOwnerToken(
181
242
  {
182
243
  platform = process.platform,
183
244
  exists,
245
+ env = process.env,
246
+ // BOT-3257: the server that issued this token. Its origin picks the
247
+ // Keychain service and is recorded on the stored login.
248
+ serverUrl = configuredServerUrl(env),
184
249
  getConfig,
185
250
  saveConfig,
186
- keychainWrite = (value) => writeKeychainSecret(CLIENT_KEY_SERVICE, value),
251
+ keychainWrite = (value, service) => writeKeychainSecret(service, value),
187
252
  warn = (message) => console.error(message),
188
253
  } = {},
189
254
  ) {
190
255
  if (typeof token !== "string" || token.length === 0) {
191
256
  throw new Error("persistOwnerToken requires a non-empty token");
192
257
  }
258
+ const origin = serverOrigin(serverUrl);
259
+ const service = clientKeyService(origin);
193
260
  // Start from a sanitized copy so a stale on-disk secret is never carried
194
261
  // forward, then layer on the fresh non-secret metadata.
195
- const keychain = keychainAvailable(platform, exists);
262
+ const keychain = keychainAvailable(platform, exists, env);
196
263
  const { config: base } = sanitizeConfigSecrets(getConfig(), { platform, exists });
197
- const next = { ...base };
264
+ const next = { ...base, server_origin: origin };
198
265
  if (clientId !== undefined) next.client_id = clientId;
199
266
  if (expiresAt !== undefined) next.token_expires_at = expiresAt;
200
267
  // BOT-1571: the token's SCOPE (non-secret). `user` = not bound to a tenant,
@@ -209,7 +276,7 @@ export async function persistOwnerToken(
209
276
  }
210
277
 
211
278
  if (keychain) {
212
- await keychainWrite(token);
279
+ await keychainWrite(token, service);
213
280
  delete next.access_token;
214
281
  } else {
215
282
  warn(
@@ -225,44 +292,77 @@ export async function persistOwnerToken(
225
292
  // Keychain only — a stale config.json access_token is ignored, never silently
226
293
  // trusted (BOT-1520 AC5). On a non-darwin host the config.json fallback is the
227
294
  // legitimate store. Expiry metadata always comes from config.json.
295
+ //
296
+ // BOT-3257: the token is bound to the server origin that issued it. `serverUrl`
297
+ // is the server this command will send it to; a stored login tagged with (or,
298
+ // untagged, implicitly belonging to) a different origin throws
299
+ // CredentialOriginError before any request is made. When this origin has no
300
+ // login but another origin does, that is named too, so the operator learns why
301
+ // rather than seeing a bare "not authenticated".
228
302
  export async function resolveOwnerToken({
229
303
  platform = process.platform,
230
304
  exists,
305
+ env = process.env,
306
+ serverUrl = configuredServerUrl(env),
231
307
  getConfig,
232
- keychainRead = () => readKeychainSecret(CLIENT_KEY_SERVICE),
308
+ // `strict` (BOT-1750): a failing credential store throws instead of reading as absent.
309
+ strict = false,
310
+ keychainRead,
233
311
  // BOT-1574 migration: a machine logged in before 1574 has the token under the
234
312
  // legacy OWNER_TOKEN service. Read it as a fallback so an upgrade needs no
235
- // re-login; `login` rewrites it to CLIENT_KEY, and `logout` clears both.
236
- keychainReadLegacy = () => readKeychainSecret(OWNER_TOKEN_SERVICE),
313
+ // re-login; `login` rewrites it to CLIENT_KEY, and `logout` clears both. The
314
+ // legacy service only ever held a production token.
315
+ keychainReadLegacy,
316
+ findForeignLogin = (origin) => findForeignLoginOrigin(origin),
237
317
  } = {}) {
318
+ const origin = serverOrigin(serverUrl);
319
+ const service = clientKeyService(origin);
320
+ const read = keychainRead ?? (() => readKeychainSecret(service, { strict }));
321
+ const readLegacy = keychainReadLegacy ?? (() => readKeychainSecret(OWNER_TOKEN_SERVICE, { strict }));
238
322
  const cfg = getConfig() ?? {};
323
+ if (hasLoginRecord(cfg)) assertCredentialOrigin(cfg.server_origin ?? null, origin);
239
324
  const expiresAt = typeof cfg.token_expires_at === "number" ? cfg.token_expires_at : null;
240
325
  let token = null;
241
- if (keychainAvailable(platform, exists)) {
242
- token = await keychainRead();
243
- if (!token) token = await keychainReadLegacy();
326
+ if (keychainAvailable(platform, exists, env)) {
327
+ token = await read();
328
+ if (!token && isProductionOrigin(origin)) token = await readLegacy();
244
329
  } else if (typeof cfg.access_token === "string" && cfg.access_token) {
245
330
  token = cfg.access_token;
246
331
  }
247
- if (!token) return null;
332
+ if (!token) {
333
+ // Production keeps its plain "not authenticated" path (an agent may still
334
+ // authenticate with its binding key). Anywhere else, name the login that
335
+ // exists for another origin so the refusal explains itself.
336
+ if (!isProductionOrigin(origin)) {
337
+ const foreign = findForeignLogin(origin);
338
+ if (foreign) throw new CredentialOriginError({ credentialOrigin: foreign, targetOrigin: origin });
339
+ }
340
+ return null;
341
+ }
248
342
  const tenantMode = cfg.token_tenant_mode === "user" || cfg.token_tenant_mode === "tenant" ? cfg.token_tenant_mode : null;
249
343
  const tenantId = typeof cfg.token_tenant_id === "string" && cfg.token_tenant_id ? cfg.token_tenant_id : null;
250
344
  const tenants = Array.isArray(cfg.token_tenants) ? cfg.token_tenants.filter((t) => typeof t === "string" && t) : [];
251
- return { token, expiresAt, tenantMode, tenantId, tenants };
345
+ return { token, expiresAt, tenantMode, tenantId, tenants, serverOrigin: origin };
252
346
  }
253
347
 
254
348
  // Remove the client key from every store (`botbuddy logout`). Clears BOTH the
255
349
  // current CLIENT_KEY item and the legacy OWNER_TOKEN item so a pre-1574 token
256
350
  // left behind by the read-both migration is never orphaned in the Keychain.
351
+ //
352
+ // BOT-3257: only the current server origin's slot. Logging out of staging never
353
+ // deletes the production key (the legacy service is production-only).
257
354
  export async function clearOwnerToken({
258
355
  platform = process.platform,
259
356
  exists,
357
+ env = process.env,
358
+ serverUrl = configuredServerUrl(env),
260
359
  keychainDelete = async () => {
261
- await deleteKeychainSecret(CLIENT_KEY_SERVICE);
262
- await deleteKeychainSecret(OWNER_TOKEN_SERVICE);
360
+ const origin = serverOrigin(serverUrl);
361
+ await deleteKeychainSecret(clientKeyService(origin));
362
+ if (isProductionOrigin(origin)) await deleteKeychainSecret(OWNER_TOKEN_SERVICE);
263
363
  },
264
364
  } = {}) {
265
- if (keychainAvailable(platform, exists)) {
365
+ if (keychainAvailable(platform, exists, env)) {
266
366
  await keychainDelete();
267
367
  }
268
368
  }
@@ -271,9 +371,22 @@ export async function clearOwnerToken({
271
371
  // `.botbuddy-agent.json` mcp_env var (env or Keychain) — without throwing when no
272
372
  // binding is configured. This is the fallback the owner OAuth token defers to for
273
373
  // tool-call auth now that `register` and `profile setup` are both gone.
374
+ //
375
+ // BOT-3257: the DEFAULT MCP key variable (BOTBUDDY_MCP_KEY, and its legacy
376
+ // alias) is the one `.mcp.json` and the committed binding name for production,
377
+ // so a key read from it is production-only. A binding that names any other
378
+ // variable is the caller's explicit choice for that server (the staging
379
+ // release-notes canary uses BB_RELEASE_NOTES_CANARY_MCP_KEY) and is unchanged.
274
380
  export async function resolveAgentKey(options = {}) {
381
+ const env = options.env ?? process.env;
275
382
  try {
276
- const { token } = await resolveAgentBinding(options);
383
+ const { token, tokenEnv } = await resolveAgentBinding(options);
384
+ if (token && (tokenEnv === DEFAULT_MCP_ENV_VAR || tokenEnv === LEGACY_MCP_ENV_VAR)) {
385
+ const origin = serverOrigin(options.serverUrl ?? configuredServerUrl(env));
386
+ if (!isProductionOrigin(origin)) {
387
+ throw new CredentialOriginError({ credentialOrigin: PRODUCTION_ORIGIN, targetOrigin: origin, credential: `${tokenEnv} MCP key` });
388
+ }
389
+ }
277
390
  return token || null;
278
391
  } catch (error) {
279
392
  // A missing / malformed / retired-shape binding is not authenticated — let the
package/src/commands.mjs CHANGED
@@ -1559,6 +1559,12 @@ export function mcpRecovery(code) {
1559
1559
  return "--env must be an UPPER_SNAKE_CASE variable name, e.g. BOTBUDDY_MCP_KEY_WORK.";
1560
1560
  case "reserved_env_var":
1561
1561
  return "that --env name belongs to another BotBuddy credential (it would clobber that Keychain slot) — pick a distinct MCP var like BOTBUDDY_MCP_KEY_WORK.";
1562
+ case "credential_origin_mismatch":
1563
+ return "the stored login was issued by a different BotBuddy server, so it was not sent — sign in to this server with `BOTBUDDY_SERVER_URL=<this server> bb login` (stored separately; your production login is untouched).";
1564
+ case "mcp_env_required_for_server":
1565
+ return "BOTBUDDY_MCP_KEY is the production MCP key slot — against another server, name a variable of its own, e.g. `bb mcp setup --env BOTBUDDY_MCP_KEY_STAGING`.";
1566
+ case "server_url_invalid":
1567
+ return "BOTBUDDY_SERVER_URL is not a valid http(s) URL — fix or unset it.";
1562
1568
  case "env_var_in_use":
1563
1569
  return "that Keychain slot already holds a key — revoke the old server key (`botbuddy mcp revoke <agent_id>`) if it is still live, then clear the local slot with `security delete-generic-password -s <NAME>`; or use a different --env, or pass --force to replace it in place (the replaced key is revoked).";
1564
1570
  case "previous_key_unconfirmed":
@@ -1697,7 +1703,8 @@ export async function cmdMcp(args, {
1697
1703
  // can `botbuddy mcp revoke <id>` rather than pile up unusable keys.
1698
1704
  if (!error.rolledBack && error.agentId) extra.orphan_agent_id = error.agentId;
1699
1705
  }
1700
- log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, ...extra, recovery: mcpRecovery(code) }));
1706
+ if (error instanceof McpKeyError && error.detail && !extra.detail) extra.detail = error.detail;
1707
+ log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, ...extra, recovery: error?.recovery ?? mcpRecovery(code) }));
1701
1708
  setExitCode(3);
1702
1709
  }
1703
1710
  return;
@@ -1728,7 +1735,7 @@ export async function cmdMcp(args, {
1728
1735
  }
1729
1736
  } catch (error) {
1730
1737
  const code = error instanceof McpKeyError ? error.code : "revoke_failed";
1731
- log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: mcpRecovery(code) }));
1738
+ log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: error?.recovery ?? mcpRecovery(code) }));
1732
1739
  setExitCode(3);
1733
1740
  return;
1734
1741
  }
@@ -1737,7 +1744,7 @@ export async function cmdMcp(args, {
1737
1744
  log(JSON.stringify(await revoke({ agentId, tenant, envVar })));
1738
1745
  } catch (error) {
1739
1746
  const code = error instanceof McpKeyError ? error.code : "revoke_failed";
1740
- log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: mcpRecovery(code) }));
1747
+ log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: error?.recovery ?? mcpRecovery(code) }));
1741
1748
  setExitCode(3);
1742
1749
  }
1743
1750
  return;
@@ -1749,7 +1756,7 @@ export async function cmdMcp(args, {
1749
1756
  requested = await resolveRequestedEnv(parseMcpStatusEnv(args));
1750
1757
  } catch (error) {
1751
1758
  const code = error instanceof McpKeyError ? error.code : "invalid_env_var";
1752
- log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: mcpRecovery(code) }));
1759
+ log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: error?.recovery ?? mcpRecovery(code) }));
1753
1760
  setExitCode(3);
1754
1761
  return;
1755
1762
  }
@@ -1779,7 +1786,7 @@ export async function cmdMcp(args, {
1779
1786
  requested = await resolveRequestedEnv(parseMcpStatusEnv(args));
1780
1787
  } catch (error) {
1781
1788
  const code = error instanceof McpKeyError ? error.code : "invalid_env_var";
1782
- log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: mcpRecovery(code) }));
1789
+ log(JSON.stringify({ schema_version: 1, outcome: "error", error: code, recovery: error?.recovery ?? mcpRecovery(code) }));
1783
1790
  setExitCode(3);
1784
1791
  return;
1785
1792
  }
package/src/config.mjs CHANGED
@@ -1,16 +1,30 @@
1
1
  import { readFileSync, writeFileSync, mkdirSync, unlinkSync, existsSync, chmodSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { homedir } from "os";
4
+ import { dirname } from "path";
4
5
  import { migrateConfigSecrets } from "./cli-credentials.mjs";
5
-
6
- const CONFIG_DIR = join(homedir(), ".botbuddy");
7
- const CONFIG_FILE = join(CONFIG_DIR, "config.json");
6
+ import { DEFAULT_SERVER_URL, configuredServerUrl, serverOrigin, configFileFor } from "./credential-origin.mjs";
8
7
 
9
8
  // BOT-876: overridable so the CLI can be pointed at a local Supabase stack
10
9
  // (`BOTBUDDY_SERVER_URL=http://127.0.0.1:56321/functions/v1/mcp-server`).
11
10
  // Production is the default; nothing changes for normal use.
12
- export const DEFAULT_SERVER_URL = "https://api.bot-buddy.ai/functions/v1/mcp-server";
13
- export const SERVER_URL = process.env.BOTBUDDY_SERVER_URL || DEFAULT_SERVER_URL;
11
+ export { DEFAULT_SERVER_URL };
12
+ export const SERVER_URL = configuredServerUrl(process.env);
13
+
14
+ // BOT-3257: the config file is chosen by the server's origin. Production keeps
15
+ // ~/.botbuddy/config.json; any other origin gets ~/.botbuddy/servers/<origin>/,
16
+ // so a staging login never overwrites the production one. A malformed
17
+ // BOTBUDDY_SERVER_URL gets a slot of its own that never holds a credential
18
+ // (credential resolution refuses it with server_url_invalid).
19
+ function configFileForServer() {
20
+ try {
21
+ return configFileFor(serverOrigin(SERVER_URL), homedir());
22
+ } catch {
23
+ return join(homedir(), ".botbuddy", "servers", "_invalid", "config.json");
24
+ }
25
+ }
26
+ const CONFIG_FILE = configFileForServer();
27
+ const CONFIG_DIR = dirname(CONFIG_FILE);
14
28
 
15
29
  let config = {};
16
30
 
@@ -0,0 +1,112 @@
1
+ // BOT-3257: every credential the CLI stores is bound to the server origin that
2
+ // issued it, and is never sent to a different origin.
3
+ //
4
+ // On 2026-11-13, with BOTBUDDY_SERVER_URL pointed at staging, `bb mcp setup`
5
+ // sent the machine's PRODUCTION client key to the staging mcp-server: there was
6
+ // one config.json and one Keychain slot whatever the server was. Now:
7
+ //
8
+ // - production keeps its existing slots (~/.botbuddy/config.json and the
9
+ // BOTBUDDY_CLIENT_KEY Keychain service), so existing logins keep working;
10
+ // - any other origin gets its own config file and Keychain service;
11
+ // - a stored credential with no `server_origin` tag (written before BOT-3257)
12
+ // is production-only;
13
+ // - a mismatch is refused locally, with a named error and recovery text,
14
+ // before any request is made.
15
+ //
16
+ // This module imports nothing from the rest of the CLI so config.mjs,
17
+ // cli-credentials.mjs and agent-state.mjs can all use it without a cycle.
18
+
19
+ import { join } from "node:path";
20
+ import { homedir } from "node:os";
21
+
22
+ export const DEFAULT_SERVER_URL = "https://api.bot-buddy.ai/functions/v1/mcp-server";
23
+ export const PRODUCTION_ORIGIN = new URL(DEFAULT_SERVER_URL).origin;
24
+
25
+ /** The Keychain service of the production client key (unchanged since BOT-1574). */
26
+ export const PRODUCTION_CLIENT_KEY_SERVICE = "BOTBUDDY_CLIENT_KEY";
27
+
28
+ /** The server URL the CLI targets in this process (BOT-876 override or production). */
29
+ export function configuredServerUrl(env = process.env) {
30
+ return env?.BOTBUDDY_SERVER_URL || DEFAULT_SERVER_URL;
31
+ }
32
+
33
+ /** The origin of a server URL. A malformed URL fails closed. */
34
+ export function serverOrigin(url) {
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(String(url));
38
+ } catch {
39
+ const error = new Error(`server_url_invalid: BOTBUDDY_SERVER_URL is not a URL (${url})`);
40
+ error.code = "server_url_invalid";
41
+ throw error;
42
+ }
43
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
44
+ const error = new Error(`server_url_invalid: BOTBUDDY_SERVER_URL must be http(s) (${url})`);
45
+ error.code = "server_url_invalid";
46
+ throw error;
47
+ }
48
+ return parsed.origin;
49
+ }
50
+
51
+ export function isProductionOrigin(origin) {
52
+ return origin === PRODUCTION_ORIGIN;
53
+ }
54
+
55
+ /** A filesystem- and Keychain-safe name for an origin: `http_127.0.0.1_56321`. */
56
+ export function originSlug(origin) {
57
+ const url = new URL(origin);
58
+ const port = url.port ? `_${url.port}` : "";
59
+ return `${url.protocol.replace(/:$/, "")}_${url.hostname}${port}`.replace(/[^A-Za-z0-9._-]/g, "_");
60
+ }
61
+
62
+ /** The Keychain service holding the client key issued by `origin`. */
63
+ export function clientKeyService(origin) {
64
+ return isProductionOrigin(origin) ? PRODUCTION_CLIENT_KEY_SERVICE : `${PRODUCTION_CLIENT_KEY_SERVICE}@${originSlug(origin)}`;
65
+ }
66
+
67
+ /** The config file holding the login metadata issued by `origin`. */
68
+ export function configFileFor(origin, home = homedir()) {
69
+ const dir = join(home, ".botbuddy");
70
+ return isProductionOrigin(origin) ? join(dir, "config.json") : join(dir, "servers", originSlug(origin), "config.json");
71
+ }
72
+
73
+ /** The directory holding every non-production origin's config. */
74
+ export function serversDir(home = homedir()) {
75
+ return join(home, ".botbuddy", "servers");
76
+ }
77
+
78
+ /** The origin a stored record belongs to. Untagged = production (pre-BOT-3257). */
79
+ export function recordOrigin(record) {
80
+ const tagged = record?.server_origin;
81
+ return typeof tagged === "string" && tagged ? tagged : PRODUCTION_ORIGIN;
82
+ }
83
+
84
+ export function originRecovery(targetOrigin) {
85
+ if (isProductionOrigin(targetOrigin)) {
86
+ return "sign in to production with `bb login` (unset BOTBUDDY_SERVER_URL first)";
87
+ }
88
+ return `sign in to this server with \`BOTBUDDY_SERVER_URL=${targetOrigin}/functions/v1/mcp-server bb login\` (it is stored separately and never touches your production login)`;
89
+ }
90
+
91
+ export class CredentialOriginError extends Error {
92
+ constructor({ credentialOrigin, targetOrigin, credential = "client key" }) {
93
+ super(
94
+ `credential_origin_mismatch: the stored ${credential} was issued by ${credentialOrigin}, but this command targets ${targetOrigin}. `
95
+ + `BotBuddy never sends a credential to a different server. To continue, ${originRecovery(targetOrigin)}.`,
96
+ );
97
+ this.name = "CredentialOriginError";
98
+ this.code = "credential_origin_mismatch";
99
+ this.credentialOrigin = credentialOrigin;
100
+ this.targetOrigin = targetOrigin;
101
+ this.credential = credential;
102
+ this.recovery = originRecovery(targetOrigin);
103
+ }
104
+ }
105
+
106
+ /** Throw unless a credential issued by `credentialOrigin` (null = untagged = production) may go to `targetOrigin`. */
107
+ export function assertCredentialOrigin(credentialOrigin, targetOrigin, { credential } = {}) {
108
+ const issued = credentialOrigin || PRODUCTION_ORIGIN;
109
+ if (issued !== targetOrigin) {
110
+ throw new CredentialOriginError({ credentialOrigin: issued, targetOrigin, ...(credential ? { credential } : {}) });
111
+ }
112
+ }
package/src/mcp-key.mjs CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  } from "./agent-credential-store.mjs";
24
24
  import { callToolJson, resolveCallAuth } from "./api.mjs";
25
25
  import { SERVER_URL } from "./config.mjs";
26
+ import { serverOrigin, isProductionOrigin } from "./credential-origin.mjs";
26
27
 
27
28
  // The canonical MCP env/Keychain var names live in agent-credential-store.mjs
28
29
  // (the one module wait-profile.mjs and this file both import — no cycle). Re-export
@@ -88,6 +89,17 @@ function structuredCode(response) {
88
89
  return null;
89
90
  }
90
91
 
92
+ // BOT-3257: a stored login issued by another server origin was refused locally
93
+ // (never sent). Surface that as its own code, with the recovery that names this
94
+ // server, instead of collapsing it into not_authenticated.
95
+ function throwIfOriginRefused(pinned) {
96
+ const code = pinned?.error?.error;
97
+ if (code !== "credential_origin_mismatch" && code !== "server_url_invalid") return;
98
+ const error = new McpKeyError(code, { detail: pinned.error.message ?? null });
99
+ error.recovery = pinned.error.recovery ?? null;
100
+ throw error;
101
+ }
102
+
91
103
  /** Validate an explicit `--env <NAME>`; the default needs no validation. */
92
104
  export function resolveEnvVarName(explicit, { forWrite = true } = {}) {
93
105
  if (explicit == null) return DEFAULT_MCP_ENV_VAR;
@@ -216,7 +228,18 @@ export async function setupMcpKey({
216
228
  mcpUrl = SERVER_URL,
217
229
  env = process.env,
218
230
  } = {}) {
231
+ // BOT-3257: the default MCP variable is the production slot `.mcp.json` reads.
232
+ // Minting a non-production key into it would hand that key to production
233
+ // clients, so another server needs a variable of its own — refused before
234
+ // any request.
235
+ const targetOrigin = serverOrigin(mcpUrl);
236
+ if (!isProductionOrigin(targetOrigin) && (envVar === DEFAULT_MCP_ENV_VAR || envVar === LEGACY_MCP_ENV_VAR)) {
237
+ throw new McpKeyError("mcp_env_required_for_server", {
238
+ detail: `${envVar} is the production MCP key slot; this command targets ${targetOrigin}`,
239
+ });
240
+ }
219
241
  const pinned = await resolveAuth();
242
+ throwIfOriginRefused(pinned);
220
243
  if (pinned?.error) throw new McpKeyError("not_authenticated");
221
244
  const auth = pinned?.auth ?? null;
222
245
 
@@ -418,6 +441,7 @@ export async function revokeMcpKey({
418
441
  if (typeof agentId !== "string" || !agentId.trim()) throw new McpKeyError("agent_id_required");
419
442
  const id = agentId.trim();
420
443
  const pinned = await resolveAuth();
444
+ throwIfOriginRefused(pinned);
421
445
  if (pinned?.error) throw new McpKeyError("not_authenticated");
422
446
  const auth = pinned?.auth ?? null;
423
447
 
@@ -6,6 +6,19 @@ import { promisify } from "node:util";
6
6
  import { join } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { findAgentStateRoot } from "./agent-state.mjs";
9
+ // BOT-3259: BB's one project figure (v_project_progress): Must + unsure members
10
+ // only, complete / remaining / unsure, with BB's percent. Null unless all four
11
+ // are sane, so an older MCP keeps the legacy done/total.
12
+ function mustUnsureProgress(src) {
13
+ const n = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
14
+ const c = n(src?.progress_complete);
15
+ const r = n(src?.progress_remaining);
16
+ const u = n(src?.progress_unsure);
17
+ const p = n(src?.progress_percent);
18
+ if (c === null || r === null || u === null || p === null || p > 100 || u > r) return null;
19
+ return { progress: { complete: c, remaining: r, unsure: u }, done: c, total: c + r, percent: p };
20
+ }
21
+
9
22
  const execFileAsync = promisify(execFile);
10
23
  const UUID =
11
24
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -498,6 +511,8 @@ export async function readStatus({
498
511
  }
499
512
  if (!epic.identifier && PROJECT_IDENTIFIER.test(coordinator.identifier || "")) epic.identifier = coordinator.identifier;
500
513
  }
514
+ // BOT-3259: BB's Must + unsure figure wins over every older count.
515
+ Object.assign(epic, mustUnsureProgress(se) || {});
501
516
  }
502
517
  if (owner) {
503
518
  const total = Math.max(0, (owner.children_total ?? 0) - (owner.children_canceled ?? 0));
@@ -515,6 +530,7 @@ export async function readStatus({
515
530
  done,
516
531
  total,
517
532
  percent: total ? Math.round((100 * done) / total) : 0,
533
+ ...(mustUnsureProgress(owner) || {}),
518
534
  };
519
535
  }
520
536
  // A bootstrap/session switch during either network request invalidates this snapshot.