@antasphere/cli-core 0.5.0 → 0.7.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.
Files changed (48) hide show
  1. package/README.md +324 -85
  2. package/dist/auth.d.ts +1 -1
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/config.d.ts +120 -62
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +207 -91
  7. package/dist/config.js.map +1 -1
  8. package/dist/connect-on-demand.d.ts +196 -99
  9. package/dist/connect-on-demand.d.ts.map +1 -1
  10. package/dist/connect-on-demand.js +565 -117
  11. package/dist/connect-on-demand.js.map +1 -1
  12. package/dist/connect.d.ts +8 -8
  13. package/dist/connect.d.ts.map +1 -1
  14. package/dist/index.d.ts +25 -17
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +20 -15
  17. package/dist/index.js.map +1 -1
  18. package/dist/kept-keys.d.ts +208 -0
  19. package/dist/kept-keys.d.ts.map +1 -0
  20. package/dist/kept-keys.js +484 -0
  21. package/dist/kept-keys.js.map +1 -0
  22. package/dist/lock.d.ts +65 -0
  23. package/dist/lock.d.ts.map +1 -0
  24. package/dist/lock.js +408 -0
  25. package/dist/lock.js.map +1 -0
  26. package/dist/migrate.d.ts +9 -3
  27. package/dist/migrate.d.ts.map +1 -1
  28. package/dist/migrate.js +32 -11
  29. package/dist/migrate.js.map +1 -1
  30. package/dist/resolve.d.ts +12 -4
  31. package/dist/resolve.d.ts.map +1 -1
  32. package/dist/resolve.js +12 -8
  33. package/dist/resolve.js.map +1 -1
  34. package/dist/sign-in.d.ts +266 -0
  35. package/dist/sign-in.d.ts.map +1 -0
  36. package/dist/sign-in.js +398 -0
  37. package/dist/sign-in.js.map +1 -0
  38. package/package.json +1 -1
  39. package/src/auth.ts +1 -1
  40. package/src/config.ts +303 -136
  41. package/src/connect-on-demand.ts +801 -223
  42. package/src/connect.ts +8 -8
  43. package/src/index.ts +42 -26
  44. package/src/kept-keys.ts +561 -0
  45. package/src/lock.ts +479 -0
  46. package/src/migrate.ts +33 -11
  47. package/src/resolve.ts +20 -15
  48. package/src/sign-in.ts +601 -0
@@ -1,82 +1,124 @@
1
- import {
2
- assertToolNamespace,
3
- HUB_TOOL,
4
- loadConfig,
5
- lookupConnectKey,
6
- removeConnectKey,
7
- storeConnectKey
8
- } from './config.js';
9
- import type { CliEnv, CliProfile } from './config.js';
1
+ import { createHash } from 'node:crypto';
2
+ import { CliAuthClient, CliAuthError } from './auth.js';
3
+ import { assertToolNamespace, configPath, HUB_TOOL, loadConfig, updateConfig } from './config.js';
4
+ import type { CliEnv, CliHubKey, CliProfile, CliSiteFacts } from './config.js';
10
5
  import { CliConnectClient, CliConnectError } from './connect.js';
11
6
  import type { CliConnectResult } from './connect.js';
12
7
  import {
13
- CliUsageError,
14
- firstSet,
15
- normalizeUrl,
16
- profileUrl,
17
- resolveProfile,
18
- sameInstance
19
- } from './resolve.js';
20
- import type { ResolvedProfile } from './resolve.js';
8
+ evictKey,
9
+ forgetKeys,
10
+ hasOldSlots,
11
+ hubKeysOf,
12
+ keysHeldElsewhere,
13
+ keysOfProfile,
14
+ moveOldSlots,
15
+ newestKey,
16
+ sameEmail,
17
+ sameSlot,
18
+ storeHubKey,
19
+ storeUnrevokedKey,
20
+ text
21
+ } from './kept-keys.js';
22
+ import { withFileLockAsync } from './lock.js';
23
+ import { decide, httpUrl, profileFlag, readLogins, requireHubCloudUrl, siteFactsOf } from './sign-in.js';
24
+ import type { CliLogin, Decision, SignInPlan } from './sign-in.js';
25
+ import { CliUsageError, firstSet, normalizeUrl, profileUrl, sameInstance, selectProfile } from './resolve.js';
21
26
 
22
27
  /**
23
- * Connect-on-demand (binding patterns §7, gcloud model), extracted from the
24
- * Slideless CLI so every Antasphere tool CLI inherits "one `antasphere login`
25
- * serves every federated tool". When a tool CLI resolves NO credential of its
26
- * own, it calls `connectOnDemand` with the profile it selected
27
- * (`selectProfile`: the profile IS the instance):
28
+ * Connect-on-demand (binding patterns §7, gcloud model): one Antasphere login
29
+ * per hub serves every federated tool. When a tool CLI resolves NO credential
30
+ * of its own, it calls `connectOnDemand` with the profile it selected
31
+ * (`selectProfile`: the profile IS the site), and the sign-in FOLLOWS THE
32
+ * SITE (R2, PRDCT-3521): the login used is the login at the hub the site
33
+ * trusts (`planSignIn`), never the machine's active hub login.
28
34
  *
29
- * 0. The cache is consulted FIRST: a key minted earlier for THIS instance
30
- * under the active hub profile is USER-scoped (hub ADR 014) — it serves
31
- * every subsequent run and every org, with zero network (no probe, no
32
- * hub round-trip, no fresh mint). It is read on the selected profile
33
- * only when that profile is at the resolved instance (its `baseUrl`,
34
- * else the tool's `cloudUrl` when the profile has none), so a cached
35
- * key never travels to another origin. `cached: false` skips this step.
36
- * 1. On a miss, discovery gates the flow: only an Antasphere-CLOUD
37
- * instance can mint keys through the hub (unauthenticated GET
38
- * /instance — never guess). Unreachable, foreign, or self-hosted
39
- * instances answer `not_cloud` and the tool raises its classic no-key
40
- * error unchanged.
41
- * 2. The hub credential is what `antasphere login` stored on the hub
42
- * profile (the config home's HUB_TOOL namespace) — hub URL included,
43
- * never a hardcoded constant here.
44
- * 3. `CliConnectClient.exchange` trades it for a tool-local key (one
45
- * re-exchange retry when the 120 s JWT dies in transit; a rejected hub
46
- * credential maps to guided `antasphere login` advice on either
47
- * attempt; a hub REFUSAL, a 403 that is not the scope case, propagates
48
- * as its `CliConnectError` with the hub's own sentence and `exitCode`
49
- * 3).
50
- * 4. The minted key is cached on the SELECTED profile under the hub
51
- * profile's name. A profile not on disk yet is created with this
52
- * instance's URL, and made active only when the tool had no profile at
53
- * all; an existing profile is never renamed or repointed, and one that
54
- * is at another instance never receives the key.
35
+ * 0. A profile at another site than the command's is refused before any
36
+ * request, and so is a profile with no site of its own that holds a
37
+ * key (its keys are never adopted): nothing is minted for a profile
38
+ * that cannot keep the key (PRDCT-3044). The old slots are moved once.
39
+ * Then the plan: a refusal
40
+ * (`ANTASPHERE_URL` or `--hub` naming another hub than the site's) is
41
+ * thrown; a servable kept key is served with zero network, after one
42
+ * discovery read when what the profile remembers of its site is missing
43
+ * or older than a day (`cached: false` skips this step).
44
+ * 1. Discovery gates the flow: only a site that signs in through an
45
+ * Antasphere hub can mint keys through one (unauthenticated GET
46
+ * /instance, never a guess); an unreachable, foreign or self-hosted site
47
+ * answers `not_cloud`, and the tool raises its classic no-key error.
48
+ * What the site says is remembered on its profile (`rememberSite`).
49
+ * 2. The plan again, on the fresh facts: a refusal, a hub to pick or a
50
+ * login to pick is a `CliUsageError` naming the way out.
55
51
  *
56
- * A stranded key recovers: on a 401 with a key that came from the cache,
57
- * the tool CLI calls `refreshConnectKey` once (evict, exchange again with
58
- * `cached: false`) and retries its request once; a second 401 fails.
52
+ * Whatever the command ends with (a key served, an error, `not_cloud` from
53
+ * a site that answered, an exchange), the stale keys of its plan go first:
54
+ * revoked on the profile's own site with no lock held, then forgotten; a
55
+ * site that does not answer within the limit (`requestTimeoutMs`, 10 s:
56
+ * every revoke on a command's way is bounded) keeps them for the next
57
+ * command. A key whose login is gone is one of them. A stale key another
58
+ * profile at that same site still holds is never revoked: it is forgotten
59
+ * on this profile only, and `notify` says so (`keysHeldElsewhere`, R2's
60
+ * one rule).
61
+ * 3. The mint is single-flight: a second lock, per (profile, hub, e-mail),
62
+ * the file read again inside it (and the login, when it carried no
63
+ * e-mail: another command's exchange may have told its address), and
64
+ * the exchange only when the key is still missing. The hub key goes to
65
+ * the chosen login's OWN hub and nowhere else (one re-exchange retry
66
+ * when the 120 s JWT dies in transit; a rejected hub key maps to
67
+ * `messages.hubLoginRejected`; a refusal propagates as its
68
+ * `CliConnectError`, exit code 3). A hub the profile's `lastHub` chose
69
+ * (or, in a recovery, the refused key's) that does not know this site's
70
+ * resource ends on that error with the way out appended (`login --hub
71
+ * <hub>`).
72
+ * 4. First stored wins: when another command stored a kept key for the
73
+ * slot after this command's re-read under the mint lock, it is kept and
74
+ * used, and the key just minted is revoked on the site; when the site
75
+ * does not answer that revoke, the key is filed undated in its slot, a
76
+ * stale duplicate the next command revokes; when it refuses it (a 403),
77
+ * `notify` is told and nothing is filed. A key the profile held at
78
+ * that re-read is not first stored (a login with no e-mail is never
79
+ * served a key, so its exchange may mint for a slot that holds one): the
80
+ * key just minted is stored beside it, and the older one is a stale
81
+ * duplicate the next command revokes. A key minted for a profile that
82
+ * cannot keep it is revoked on its site, and `notify` is told when that
83
+ * revoke did not answer. The store writes the address of the hub the
84
+ * exchange went through on the profile, in its normal form
85
+ * (`normalizeUrl`: `lastHub`), whichever key is kept.
86
+ * 5. A login whose address the hub's answer contradicts (or that had none)
87
+ * takes the hub's address (`healed`), before the mint lock is let go:
88
+ * a command waiting on it with that login finds the key just kept.
59
89
  *
60
- * A new tool needs only its namespace, its cloud URL, and copy — the flow
61
- * itself is tool-agnostic.
90
+ * A stranded key recovers: on a 401 with a key served `cached: true`, the
91
+ * tool CLI calls `refreshConnectKey` once with that key (compare-and-evict,
92
+ * the refused key's hub kept as the profile's `lastHub` when it holds none,
93
+ * then the exchange again for the refused key's account, at that key's hub
94
+ * when the site names none and a login is in place there) and retries its
95
+ * request once; a second 401 fails.
62
96
  */
63
97
 
64
- /** What the unauthenticated discovery probe learned about a tool instance. */
98
+ /** What the unauthenticated discovery probe learned about a site. */
65
99
  export interface ToolInstanceProbe {
66
- /** Whether the instance signs in through the Antasphere hub (advertises
67
- * the `antasphere` auth method, or calls itself the cloud edition). */
100
+ /** The site probed (`normalizeUrl`'d): whose facts these are. */
101
+ url: string;
102
+ /** Whether the site signs in through an Antasphere hub (advertises the
103
+ * `antasphere` auth method, or calls itself the cloud edition). */
68
104
  cloud: boolean;
69
- /** The instance's self-reported edition (`cloud`, `oss`, …). */
105
+ /** The site's self-reported edition (`cloud`, `oss`, …). */
70
106
  edition: string | undefined;
71
107
  /** The advertised auth methods (open enum — unknown entries kept). */
72
108
  authMethods: string[];
109
+ /** The Antasphere hub the site names (`auth.hub`, `normalizeUrl`'d), or null when it names none. */
110
+ hub: string | null;
111
+ /** Its discovery `name`, or null. */
112
+ name: string | null;
113
+ /** The CLI version it announces (`cli.version`), or null. */
114
+ cliVersion: string | null;
73
115
  }
74
116
 
75
117
  /**
76
- * Probe a tool instance's unauthenticated discovery endpoint
118
+ * Probe a site's unauthenticated discovery endpoint
77
119
  * (`GET {toolBaseUrl}/api/v1/instance`). Returns what it advertises, or
78
- * `null` when the instance is unreachable or answers a foreign shape —
79
- * callers treat both exactly like "not cloud".
120
+ * `null` when the site is unreachable or answers a foreign shape — callers
121
+ * treat both exactly like "not cloud".
80
122
  */
81
123
  export async function probeToolInstance(
82
124
  toolBaseUrl: string,
@@ -93,107 +135,187 @@ export async function probeToolInstance(
93
135
  if (!res.ok) return null;
94
136
  const info = (await res.json().catch(() => null)) as {
95
137
  edition?: unknown;
96
- auth?: { methods?: unknown };
138
+ name?: unknown;
139
+ auth?: { methods?: unknown; hub?: unknown } | null;
140
+ cli?: { version?: unknown } | null;
97
141
  } | null;
98
142
  const methods = info?.auth?.methods;
99
143
  if (!Array.isArray(methods)) return null;
100
144
  const authMethods = methods.filter((m): m is string => typeof m === 'string');
101
145
  const edition = typeof info?.edition === 'string' ? info.edition : undefined;
102
- return { cloud: authMethods.includes('antasphere') || edition === 'cloud', edition, authMethods };
146
+ const hub = text(info?.auth?.hub);
147
+ return {
148
+ url: normalizeUrl(toolBaseUrl),
149
+ cloud: authMethods.includes('antasphere') || edition === 'cloud',
150
+ edition,
151
+ authMethods,
152
+ hub: hub ? normalizeUrl(hub) : null,
153
+ name: typeof info?.name === 'string' ? info.name : null,
154
+ cliVersion: typeof info?.cli?.version === 'string' ? info.cli.version : null
155
+ };
103
156
  } catch {
104
157
  return null;
105
158
  }
106
159
  }
107
160
 
161
+ /** The hub's URL env var: for a site that names no hub, the hub a command signs in at. */
162
+ export const HUB_URL_ENV = 'ANTASPHERE_URL';
163
+
164
+ const DAY_MS = 24 * 60 * 60 * 1000;
165
+
166
+ /** The limit of each revoke cli-core sends on a command's way, when `requestTimeoutMs` gives none. */
167
+ const REVOKE_TIMEOUT_MS = 10_000;
168
+
169
+ /** The longest limit a Node timer takes as it is (2^31 − 1 ms): a longer one is cut to 1 ms. */
170
+ const MAX_REVOKE_TIMEOUT_MS = 2_147_483_647;
171
+
172
+ /** The facts a probe gives, as a profile remembers them. */
173
+ function factsOf(probe: ToolInstanceProbe, seenAt: string): CliSiteFacts {
174
+ return { hub: probe.hub, federated: probe.cloud, name: probe.name, cliVersion: probe.cliVersion, seenAt };
175
+ }
176
+
177
+ /** Whether a profile's memory of its site is missing, unreadable, or not from the last 24 hours. */
178
+ function siteDue(profile: CliProfile | undefined, nowMs: number): boolean {
179
+ const site = siteFactsOf(profile);
180
+ const age = site ? nowMs - Date.parse(site.seenAt) : Number.NaN;
181
+ return !(age >= 0 && age <= DAY_MS);
182
+ }
183
+
108
184
  /**
109
- * The ACTIVE hub profile — what `antasphere login` stored. Its NAME is the
110
- * connect cache's slot (config.ts `connectKeys`): stable per hub account on
111
- * this machine, independent of any org selection.
185
+ * Remember what a site said of itself on its profile, under `updateConfig`:
186
+ * only for a profile on disk at that site (`probe.url`; a profile with no
187
+ * `baseUrl` is at `cloudUrl`), and only when the hub, `federated`, the name
188
+ * or the CLI version differ from what the profile holds, or when its
189
+ * `seenAt` is older than 24 hours, or with `force` (`profiles --check`).
190
+ * Otherwise nothing is written. Answers whether the file changed.
112
191
  */
113
- export function activeHubProfile(env: CliEnv): ResolvedProfile {
114
- return resolveProfile(loadConfig(env, HUB_TOOL), undefined);
192
+ export function rememberSite(
193
+ env: CliEnv,
194
+ tool: string,
195
+ profileName: string,
196
+ probe: ToolInstanceProbe,
197
+ opts: { force?: boolean | undefined; cloudUrl?: string | undefined } = {}
198
+ ): boolean {
199
+ assertToolNamespace(tool);
200
+ const atSite = (profile: CliProfile | undefined): profile is CliProfile => {
201
+ const at = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
202
+ return at !== undefined && sameInstance(at, probe.url);
203
+ };
204
+ if (!atSite(loadConfig(env, tool).profiles[profileName])) return false;
205
+ const now = Date.now();
206
+ const facts = factsOf(probe, new Date(now).toISOString());
207
+ return updateConfig(env, tool, (config) => {
208
+ const profile = config.profiles[profileName];
209
+ if (!atSite(profile)) return;
210
+ const held = siteFactsOf(profile);
211
+ const same =
212
+ held !== undefined &&
213
+ held.hub === facts.hub &&
214
+ held.federated === facts.federated &&
215
+ held.name === facts.name &&
216
+ held.cliVersion === facts.cliVersion;
217
+ if (!opts.force && same && !siteDue(profile, now)) return;
218
+ profile.site = facts;
219
+ }).changed;
115
220
  }
116
221
 
117
- /** The facts the connected notice is rendered from (fresh exchanges only —
118
- * cache hits are silent). */
222
+ /** The facts the connected notice is rendered from (fresh exchanges only — served keys are silent). */
119
223
  export interface ConnectNoticeFacts {
120
- /** The tool instance the exchange connected to (origin-normalized). */
224
+ /** The site the exchange connected to (origin-normalized). */
121
225
  toolBaseUrl: string;
122
- /** The signed-in account's email at mint. */
226
+ /** The signed-in account's email, as the hub answered it. */
123
227
  email: string;
124
- /** Whether the minted key was persisted for the next run (on the
125
- * selected profile, under the hub profile's name); false = the profile
126
- * is at another instance. */
228
+ /** Whether the minted key was kept on the profile: always true (a profile at another site is
229
+ * refused before any request). */
127
230
  stored: boolean;
128
- /** The tool profile the cache targeted. */
231
+ /** The tool profile the key is kept on. */
129
232
  profileName: string;
130
- /** When NOT stored: the other instance the profile is at. */
233
+ /** Never set any more (kept for the shape of 0.6). */
131
234
  profileBaseUrl?: string;
132
235
  }
133
236
 
134
237
  /**
135
- * Branded copy seams. Defaults reproduce the Slideless CLI's strings modulo
136
- * the tool name (the tool namespace stands in for the display name, and the
137
- * key-env-var name is derived from it: `slideless` → `SLIDELESS_API_KEY`).
238
+ * Branded copy seams. The sentences that say why a command cannot sign in
239
+ * (a refusal, a hub or a login to pick, no login at the site's hub) are
240
+ * cli-core's own, with the tool's binary (`bin`) in them.
138
241
  */
139
242
  export interface ConnectOnDemandMessages {
140
- /** `CliUsageError` text when the instance is cloud but no `antasphere
141
- * login` credential is stored on the hub profile. */
142
- missingHubLogin?: string;
143
- /** `CliUsageError` text when the hub rejected the stored credential. */
243
+ /** `CliUsageError` text when the hub rejected the login's stored key. */
144
244
  hubLoginRejected?: string;
145
245
  /** Renders the success notice handed to `notify` (newline included). */
146
246
  connected?: (facts: ConnectNoticeFacts) => string;
147
247
  }
148
248
 
149
- function defaultMissingHubLogin(tool: string): string {
150
- const envVar = `${tool.replace(/-/g, '_').toUpperCase()}_API_KEY`;
151
- return (
152
- `This ${tool} instance signs in through the Antasphere hub. Run \`antasphere login\` once, ` +
153
- `then retry — or pass --api-key / set ${envVar}.`
154
- );
155
- }
156
-
157
249
  const DEFAULT_HUB_LOGIN_REJECTED =
158
250
  'The stored Antasphere hub credential was rejected — run `antasphere login` again, then retry.';
159
251
 
160
252
  function defaultConnected(facts: ConnectNoticeFacts): string {
161
- return (
162
- `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere` +
163
- (facts.stored
164
- ? ''
165
- : ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
166
- '.\n'
167
- );
253
+ return `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere.\n`;
168
254
  }
169
255
 
170
256
  export interface ConnectOnDemandOptions {
171
- /** The tool's config namespace (lowercase slug — it names the cache file). */
257
+ /** The tool's config namespace (lowercase slug — it names the profiles file). */
172
258
  tool: string;
173
- /** The resolved tool instance origin the CLI is talking to. */
259
+ /** The site the command talks to. */
174
260
  toolBaseUrl: string;
175
261
  /** The tool's cloud URL, the same value `selectProfile` got: what a
176
262
  * profile with no `baseUrl` of its own is at. Omit only for a tool with
177
- * no cloud instance. */
263
+ * no cloud site. */
178
264
  cloudUrl?: string | undefined;
179
- /** The exchange resource URL; default = this instance's MCP endpoint,
265
+ /** REQUIRED: the hub's cloud URL, what a login with no `baseUrl` of its own
266
+ * is at (`listLogins`); a `TypeError` naming it when it is missing, blank
267
+ * or not an `http:` or `https:` URL. A login's own `baseUrl` always wins,
268
+ * and its key goes to that login's own hub only. */
269
+ hubCloudUrl: string;
270
+ /** `login --hub`: the hub to sign in at, for a site that names none. Refused, both named, when
271
+ * the site names another one. */
272
+ hubUrl?: string | undefined;
273
+ /** `login --email`: the account to sign in with, among the logins at the site's hub. */
274
+ email?: string | undefined;
275
+ /** The binary named in the sentences (default: the tool's namespace). */
276
+ bin?: string | undefined;
277
+ /** The exchange resource URL; default = this site's MCP endpoint,
180
278
  * `${toolBaseUrl}/mcp` (the tool's registered resource URL). */
181
279
  resource?: string;
182
280
  /** The tool profile the CLI selected for this run (`selectProfile`), the
183
- * one the minted key is cached on. Not on disk yet → created with
184
- * `toolBaseUrl` on first contact; at another instance → the key is
185
- * returned but never stored. cli-core never guesses it. */
281
+ * one the key is kept on. Not on disk yet → created with `toolBaseUrl` on
282
+ * first contact; at another site → refused before any request. cli-core
283
+ * never guesses it. */
186
284
  profileName: string;
187
285
  env: CliEnv;
188
286
  fetch?: typeof globalThis.fetch;
189
- /** Receives the human "Connected to …" notice (tools wire their stderr);
190
- * omitted = silent. Cache hits are always silent either way. */
287
+ /** Receives the human "Connected to …" notice, and the line that says a key
288
+ * minted on the site could not be revoked there (tools wire their stderr);
289
+ * omitted = silent. Served keys are always silent either way. */
191
290
  notify?: (line: string) => void;
192
291
  messages?: ConnectOnDemandMessages;
193
- /** false = do not read the cache: run the exchange even when a key is
194
- * cached (the one re-exchange after a 401 on a cached key;
195
- * `refreshConnectKey` sets it). Default true. */
292
+ /** false = skip step 0 (serving a kept key before discovery is read):
293
+ * discovery is read and the plan decided on fresh facts. A kept key the
294
+ * file holds for the slot inside the mint lock is still used (another
295
+ * command's mint); a caller that wants a fresh key forgets the kept one
296
+ * first (`forgetKeys`). Default true. */
196
297
  cached?: boolean;
298
+ /** The limit of each revoke cli-core sends on a command's way (a profile's stale keys, a key just
299
+ * minted that cannot be kept), in milliseconds: past it the revoke is aborted and counts as no
300
+ * answer (a stale key then stays for the next command), and the command goes on. 10 s when absent;
301
+ * a value that is not an integer from 1 to 2 147 483 647 (2^31 − 1) reads as absent: a Node timer
302
+ * refuses a fraction and cuts a longer delay to 1 ms. */
303
+ requestTimeoutMs?: number;
304
+ }
305
+
306
+ export interface RefreshConnectKeyOptions extends ConnectOnDemandOptions {
307
+ /** The kept key the site refused (401): evicted only when it is still the one kept. */
308
+ refusedKey: string;
309
+ }
310
+
311
+ /** The login that signed a command in. */
312
+ export interface ConnectedLogin {
313
+ /** The login's entry name in the hub file. */
314
+ name: string;
315
+ /** Its hub. */
316
+ hub: string;
317
+ /** The account's address. */
318
+ email: string;
197
319
  }
198
320
 
199
321
  export type ConnectOnDemandOutcome =
@@ -201,102 +323,534 @@ export type ConnectOnDemandOutcome =
201
323
  outcome: 'connected';
202
324
  /** The tool-local key — this invocation's credential. */
203
325
  key: string;
204
- /** true = served from the (tool profile, hub profile) config cache:
205
- * zero network, nothing minted. false = a fresh exchange ran. A 401
206
- * on a `cached: true` key is what warrants `refreshConnectKey`. */
326
+ /** true = a kept key, nothing minted by this command (served, or stored by another
327
+ * command first). false = a fresh exchange ran and its key is kept. A 401 on a
328
+ * `cached: true` key is what warrants `refreshConnectKey`. */
207
329
  cached: boolean;
330
+ /** The login that signed the command in. */
331
+ login: ConnectedLogin;
208
332
  /** Fresh exchanges only: the full result (user, key meta). */
209
333
  result?: CliConnectResult;
210
- /** Fresh exchanges only: whether the minted key was persisted for
211
- * the next run (false = the profile is at another instance). */
334
+ /** Fresh exchanges only: the minted key is kept on the profile (always true). */
212
335
  stored?: boolean;
336
+ /** The login's address, replaced by the hub's answer after a fresh exchange
337
+ * (`from` null when it had none). */
338
+ healed?: { from: string | null; to: string };
213
339
  }
214
340
  | {
215
- /** Not an Antasphere-cloud instance (or unreachable): the caller
341
+ /** Not a site that signs in through an Antasphere hub (or unreachable): the caller
216
342
  * raises its classic no-key error unchanged. */
217
343
  outcome: 'not_cloud';
218
344
  };
219
345
 
220
- /**
221
- * Where the selected profile stands with respect to the resolved instance:
222
- * `here` (its `baseUrl`, else the tool's cloud URL, is this instance),
223
- * `elsewhere` (it is at another instance), or `free` (absent, or with no
224
- * instance at all: no `baseUrl` and no cloud URL known). The cache is read
225
- * only when `here`; a key is stored unless `elsewhere`; a key is evicted
226
- * only when `here`.
227
- */
228
- function placeOf(
229
- existing: CliProfile | undefined,
346
+ /** Throws the refusal of a profile at another site than the command's; answers whether it is at it. */
347
+ function atCommandSite(
348
+ profile: CliProfile | undefined,
349
+ profileName: string,
230
350
  toolBaseUrl: string,
231
351
  cloudUrl: string | undefined
232
- ): { place: 'here' | 'elsewhere' | 'free'; at?: string } {
233
- const at = existing ? profileUrl(existing, cloudUrl) : undefined;
234
- if (!existing || at === undefined) return { place: 'free' };
235
- return sameInstance(at, toolBaseUrl) ? { place: 'here', at } : { place: 'elsewhere', at };
352
+ ): boolean {
353
+ const at = profile ? profileUrl(profile, cloudUrl) : undefined;
354
+ if (at === undefined) return false;
355
+ if (!sameInstance(at, toolBaseUrl)) {
356
+ throw new CliUsageError(
357
+ `Profile "${profileName}" is the site ${normalizeUrl(at)}, and this command targets ${toolBaseUrl}.`
358
+ );
359
+ }
360
+ return true;
361
+ }
362
+
363
+ /**
364
+ * The refusal of a profile with no site of its own that holds keys (of no
365
+ * known site, never adopted): no key this command mints can be kept on it.
366
+ * It names where the person signs in instead: the profile of this site on
367
+ * disk by its name, else the site itself (`profileFlag`, the rule of every
368
+ * sentence).
369
+ */
370
+ function noSiteOfItsOwn(opts: ConnectOnDemandOptions, toolBaseUrl: string): CliUsageError {
371
+ const bin = firstSet(opts.bin) ?? opts.tool;
372
+ const there = selectProfile({
373
+ config: loadConfig(opts.env, opts.tool),
374
+ apiUrl: toolBaseUrl,
375
+ cloudUrl: opts.cloudUrl
376
+ });
377
+ const way = profileFlag(toolBaseUrl, there.created ? undefined : there.name);
378
+ return new CliUsageError(
379
+ `Profile "${opts.profileName}" has no site of its own and holds keys of no known site, so this command ` +
380
+ `cannot keep a key on it. Sign in on a profile of ${toolBaseUrl} instead (${bin} ${way} login).`
381
+ );
382
+ }
383
+
384
+ /** The outcome of a kept key the plan serves. */
385
+ function servedFrom(plan: SignInPlan): ConnectOnDemandOutcome | undefined {
386
+ const { keptKey, login, hub } = plan;
387
+ if (!keptKey || !login || !hub) return undefined;
388
+ return {
389
+ outcome: 'connected',
390
+ key: keptKey.apiKey,
391
+ cached: true,
392
+ login: { name: login.name, hub, email: login.email ?? keptKey.email }
393
+ };
394
+ }
395
+
396
+ /**
397
+ * The limit of each revoke on a command's way: `requestTimeoutMs` when it is an integer from 1 to
398
+ * 2^31 − 1, else 10 s.
399
+ */
400
+ function revokeLimit(opts: ConnectOnDemandOptions): number {
401
+ const given = opts.requestTimeoutMs;
402
+ if (typeof given !== 'number' || !Number.isInteger(given)) return REVOKE_TIMEOUT_MS;
403
+ return given >= 1 && given <= MAX_REVOKE_TIMEOUT_MS ? given : REVOKE_TIMEOUT_MS;
404
+ }
405
+
406
+ /** A fetch whose every request is aborted past `ms`, as well as by any signal it already carries. */
407
+ function limitedFetch(fetchImpl: typeof globalThis.fetch | undefined, ms: number): typeof globalThis.fetch {
408
+ const base = fetchImpl ?? globalThis.fetch.bind(globalThis);
409
+ return (input, init) => {
410
+ const limit = AbortSignal.timeout(ms);
411
+ const carried = init?.signal ?? (input instanceof Request ? input.signal : undefined);
412
+ return base(input, { ...init, signal: carried ? AbortSignal.any([carried, limit]) : limit });
413
+ };
414
+ }
415
+
416
+ /**
417
+ * What a site answered to the revoke of a key, within `ms`: `revoked`; `dead` on a 401 (already
418
+ * unusable); `refused` on a 403, with its code; `no_answer` for anything else (a 5xx, a network error,
419
+ * a revoke the limit aborted).
420
+ */
421
+ async function revokeOn(
422
+ site: string,
423
+ apiKey: string,
424
+ fetchImpl: typeof globalThis.fetch | undefined,
425
+ ms: number
426
+ ): Promise<{ answer: 'revoked' | 'dead' | 'refused' | 'no_answer'; code?: string }> {
427
+ const auth = new CliAuthClient({ baseUrl: site, fetch: limitedFetch(fetchImpl, ms) });
428
+ try {
429
+ await auth.revoke(apiKey);
430
+ return { answer: 'revoked' };
431
+ } catch (e) {
432
+ if (e instanceof CliAuthError && e.status === 401) return { answer: 'dead' };
433
+ if (e instanceof CliAuthError && e.status === 403) return { answer: 'refused', code: e.code };
434
+ return { answer: 'no_answer' };
435
+ }
436
+ }
437
+
438
+ /**
439
+ * The exchange a hub the profile remembers refused because it does not know
440
+ * this site's resource (`unknown_resource`): a hub chosen from its `lastHub`,
441
+ * or a recovery's hint (the refused key's hub). The same error, with the way
442
+ * out appended, naming the profile by `flag` (`profileFlag`). Any other error
443
+ * is returned as it is.
444
+ */
445
+ function withWayOut(
446
+ e: unknown,
447
+ profileName: string,
448
+ hub: string,
449
+ site: string,
450
+ bin: string,
451
+ flag: string
452
+ ): unknown {
453
+ if (!(e instanceof CliConnectError) || e.stage !== 'hub' || e.code !== 'unknown_resource') return e;
454
+ const said = /[.!?]$/.test(e.message.trim()) ? e.message.trim() : `${e.message.trim()}.`;
455
+ return new CliConnectError(
456
+ e.stage,
457
+ e.status,
458
+ e.code,
459
+ `${said} Profile "${profileName}" last signed in through ${hub}; if ${site} trusts another hub now, ` +
460
+ `run ${bin} ${flag} login --hub <hub>.`,
461
+ e.details
462
+ );
463
+ }
464
+
465
+ /** The line `notify` gets when a key minted on a site could not be revoked there (no key in it). */
466
+ function unrevoked(site: string): string {
467
+ return `A key minted on ${site} could not be revoked there; revoke it from that site.\n`;
468
+ }
469
+
470
+ /** Revoke a key this command minted and cannot keep, on the site that minted it; say so unless it is dead. */
471
+ async function revokeOrSay(opts: ConnectOnDemandOptions, site: string, apiKey: string): Promise<void> {
472
+ const { answer } = await revokeOn(site, apiKey, opts.fetch, revokeLimit(opts));
473
+ if (answer !== 'revoked' && answer !== 'dead') opts.notify?.(unrevoked(site));
474
+ }
475
+
476
+ /**
477
+ * Revoke the stale keys of a profile on the profile's OWN site, then forget
478
+ * the ones that site answered for, compare-and-remove. The lock is never held
479
+ * across the network: the keys were decided from a read, the revokes run with
480
+ * no lock, and `forgetKeys` takes the lock again. A key the site answered
481
+ * already unusable (a 401) or refused to revoke (a 403) is forgotten all the
482
+ * same, and `notify` says so; a 5xx or no answer keeps the key for the next
483
+ * command. The first revoke with no answer ends the revokes of the call: that
484
+ * key and every key not tried yet stay for the next command, and nothing more
485
+ * is sent to that site, so one call of `revokeStale` costs at most one limit
486
+ * (`requestTimeoutMs`); the keys answered before it are forgotten. A key
487
+ * another profile at that same site still holds (`keysHeldElsewhere`, on the
488
+ * tool's file read once before the revokes) is not revoked: it is forgotten on
489
+ * this profile only, in the same `forgetKeys`, whether it comes before or
490
+ * after a revoke with no answer (it sends nothing), and `notify` says so once
491
+ * per profile that holds one.
492
+ */
493
+ async function revokeStale(
494
+ opts: ConnectOnDemandOptions,
495
+ profile: CliProfile | undefined,
496
+ stale: CliHubKey[]
497
+ ): Promise<void> {
498
+ const site = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
499
+ if (stale.length === 0 || site === undefined) return;
500
+ const elsewhere = keysHeldElsewhere(loadConfig(opts.env, opts.tool), opts.profileName, site, opts.cloudUrl);
501
+ const said = new Set<string>();
502
+ const forget: string[] = [];
503
+ // Set by the first revoke the site did not answer: nothing more is sent to it by this call.
504
+ let unanswered = false;
505
+ for (const key of stale) {
506
+ const other = elsewhere.get(key.apiKey.trim());
507
+ if (other === undefined) {
508
+ if (unanswered) continue;
509
+ const { answer, code } = await revokeOn(site, key.apiKey, opts.fetch, revokeLimit(opts));
510
+ if (answer === 'no_answer') {
511
+ unanswered = true;
512
+ continue;
513
+ }
514
+ forget.push(key.apiKey);
515
+ const [at, name] = [normalizeUrl(site), opts.profileName];
516
+ if (answer === 'dead') {
517
+ opts.notify?.(`A stale key of profile "${name}" was already unusable on ${at}; forgetting it.\n`);
518
+ }
519
+ if (answer === 'refused') {
520
+ opts.notify?.(
521
+ `${at} refused to revoke a stale key of profile "${name}" (${code}): it stays valid there; ` +
522
+ 'revoke it from that site. Forgetting it here.\n'
523
+ );
524
+ }
525
+ continue;
526
+ }
527
+ const line = `Kept on ${normalizeUrl(site)}: profile "${other}" still holds that key.\n`;
528
+ if (!said.has(line)) opts.notify?.(line);
529
+ said.add(line);
530
+ forget.push(key.apiKey);
531
+ }
532
+ forgetKeys(opts.env, opts.tool, opts.profileName, forget);
533
+ }
534
+
535
+ /** The mint lock of one (profile, hub, e-mail): beside the tool's file, one per slot. */
536
+ function mintLockPath(
537
+ env: CliEnv,
538
+ tool: string,
539
+ profileName: string,
540
+ hub: string,
541
+ email: string | undefined
542
+ ) {
543
+ const file = configPath(env, tool);
544
+ if (!file) return null;
545
+ const id = createHash('sha256')
546
+ .update(`${profileName}\n${hub}\n${email?.trim().toLowerCase() ?? ''}`)
547
+ .digest('hex')
548
+ .slice(0, 16);
549
+ return `${file}.mint-${id}.lock`;
236
550
  }
237
551
 
238
552
  /**
239
- * The hub → tool exchange fallback a tool CLI runs when no direct credential
240
- * resolved. Serves the cached user-scoped key when one exists for this
241
- * (instance, hub profile) on the selected profile; otherwise returns
242
- * `not_cloud` when the instance is not an Antasphere-cloud one (or
243
- * unreachable). Throws a guided `CliUsageError` when the instance IS cloud
244
- * but the hub login is missing or rejected; a refusal and every other
245
- * exchange failure propagate as their `CliConnectError` (`exitCode` says 3
246
- * for the refusal, `message` is the server's own sentence).
553
+ * Run the mint of a slot single-flight across processes: under its lock
554
+ * (60 s timeout, a holder older than 120 s taken over). A waiter past the
555
+ * timeout, or a lock that cannot be taken, proceeds without it: the mint
556
+ * never fails on its lock.
557
+ */
558
+ async function singleFlight<T>(lockPath: string | null, fn: () => Promise<T>): Promise<T> {
559
+ if (!lockPath) return fn();
560
+ let entered = false;
561
+ try {
562
+ return await withFileLockAsync(
563
+ lockPath,
564
+ () => {
565
+ entered = true;
566
+ return fn();
567
+ },
568
+ { timeoutMs: 60_000, staleMs: 120_000 }
569
+ );
570
+ } catch (e) {
571
+ if (entered) throw e;
572
+ return fn();
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Write the hub's answered address on the login when it carried none or
578
+ * another one (the hub file, compare-and-set on the login's key: a login
579
+ * replaced meanwhile is left alone). Answers what changed.
580
+ */
581
+ function healLogin(
582
+ env: CliEnv,
583
+ login: CliLogin,
584
+ answered: string
585
+ ): { from: string | null; to: string } | undefined {
586
+ if (!text(answered) || sameEmail(login.email, answered)) return undefined;
587
+ let healed: { from: string | null; to: string } | undefined;
588
+ updateConfig(env, HUB_TOOL, (config) => {
589
+ const entry = config.profiles[login.name];
590
+ if (!entry || entry.apiKey !== login.profile.apiKey || sameEmail(entry.email, answered)) return;
591
+ entry.email = answered;
592
+ healed = { from: login.email ?? null, to: answered };
593
+ });
594
+ return healed;
595
+ }
596
+
597
+ /**
598
+ * The hub → tool exchange a tool CLI runs when no direct credential resolved,
599
+ * signed in by the login at the hub the site trusts (the flow is the module
600
+ * comment's). Answers the key (`cached: true` when kept, false when minted by
601
+ * this command) with the login that signed it in, or `not_cloud`. Throws a
602
+ * `CliUsageError` naming the way out when the profile is at another site or
603
+ * has no site of its own while it holds a key (both before any request),
604
+ * when `ANTASPHERE_URL` or `hubUrl` names another hub than the site's, when
605
+ * a hub or a login must be picked, when no login is at the site's hub, or
606
+ * when the hub rejected the login's key; a refusal and every other exchange
607
+ * failure propagate as their `CliConnectError` (`exitCode` 3 for a refusal).
608
+ * A missing, blank or unreadable `hubCloudUrl` is a `TypeError` naming it,
609
+ * before any read, request or write.
247
610
  */
248
611
  export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
249
612
  assertToolNamespace(opts.tool);
613
+ requireHubCloudUrl('connectOnDemand', opts.hubCloudUrl);
614
+ return connect(opts, undefined, undefined);
615
+ }
616
+
617
+ /** The command's sign-in; a recovery passes the refused key (`avoid`) and its hub (`hubHint`). */
618
+ async function connect(
619
+ opts: ConnectOnDemandOptions,
620
+ avoid: string | undefined,
621
+ hubHint: string | undefined
622
+ ): Promise<ConnectOnDemandOutcome> {
623
+ assertToolNamespace(opts.tool);
624
+ const { env, tool, profileName } = opts;
250
625
  const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
251
626
  const messages = opts.messages ?? {};
252
- const { profileName } = opts;
253
-
254
- // 0. The cache: a key minted earlier by the active hub profile is
255
- // user-scoped — it serves every run and every org (hub ADR 014; the
256
- // org is a per-request parameter, never part of the credential). Only
257
- // the selected profile is read, and only when it is at THIS instance:
258
- // a cached key never travels to a different instance. A hit costs zero
259
- // network. `cached: false` (the re-exchange after a 401) skips it.
260
- const hub = activeHubProfile(opts.env);
261
- const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
262
- const { place, at } = placeOf(existing, toolBaseUrl, opts.cloudUrl);
263
- if (opts.cached !== false && place === 'here' && hub.name) {
264
- const cachedKey = lookupConnectKey(existing, hub.name);
265
- if (cachedKey) return { outcome: 'connected', key: cachedKey, cached: true };
627
+ const now = () => new Date().toISOString();
628
+ const read = () => loadConfig(env, tool).profiles[profileName];
629
+
630
+ // 0. The profile and its place; the old slots moved once.
631
+ let profile = read();
632
+ const here = atCommandSite(profile, profileName, toolBaseUrl, opts.cloudUrl);
633
+ // A profile with no site of its own that holds a key (the store's own condition) cannot keep the
634
+ // key: refused before any request, so nothing is minted, revoked or written.
635
+ if (profile && profileUrl(profile, opts.cloudUrl) === undefined && keysOfProfile(profile).length > 0) {
636
+ throw noSiteOfItsOwn(opts, toolBaseUrl);
266
637
  }
638
+ const { logins, undecided } = readLogins(env, opts.hubCloudUrl);
639
+ if (here && hasOldSlots(profile)) {
640
+ moveOldSlots(env, tool, profileName, logins, now());
641
+ profile = read();
642
+ }
643
+ const plan = (site: CliSiteFacts | undefined): Decision =>
644
+ decide({
645
+ siteUrl: toolBaseUrl,
646
+ profileName,
647
+ profile,
648
+ cloudUrl: opts.cloudUrl,
649
+ site,
650
+ logins,
651
+ undecided,
652
+ envHub: firstSet(env[HUB_URL_ENV]),
653
+ hubUrl: opts.hubUrl,
654
+ email: opts.email,
655
+ bin: firstSet(opts.bin) ?? tool,
656
+ ownKeyFirst: false,
657
+ avoid,
658
+ hubHint,
659
+ now: now()
660
+ });
661
+
662
+ // What is stale goes before ANY outcome of the command, its errors included: revoked on the
663
+ // profile's own site (no lock held), then forgotten, and the profile read again; a site that did
664
+ // not answer keeps the key for the next command.
665
+ const settle = async (decision: Decision): Promise<void> => {
666
+ if (decision.plan.stale.length === 0) return;
667
+ await revokeStale(opts, here ? profile : undefined, decision.plan.stale);
668
+ profile = read();
669
+ };
267
670
 
268
- // 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
269
- // never guess. An unreachable or foreign instance is `not_cloud`.
270
- const probe = await probeToolInstance(toolBaseUrl, opts.fetch);
271
- if (!probe?.cloud) return { outcome: 'not_cloud' };
272
-
273
- // 2. The hub credential is what `antasphere login` stored on the hub
274
- // profile (HUB_TOOL namespace) — one login for the whole tool family.
275
- // The hub URL comes from that same profile, never from a constant here.
276
- // A blank field is no field (the package's one blank rule, firstSet).
277
- const hubKey = firstSet(hub.profile?.apiKey);
278
- const hubBaseUrl = firstSet(hub.profile?.baseUrl);
279
- if (!hubKey || !hubBaseUrl || !hub.name) {
280
- throw new CliUsageError(messages.missingHubLogin ?? defaultMissingHubLogin(opts.tool));
671
+ let probe: ToolInstanceProbe | null | undefined;
672
+ if (opts.cached !== false) {
673
+ let first = plan(undefined);
674
+ if (first.plan.reason === 'refused') {
675
+ await settle(first);
676
+ throw new CliUsageError(first.plan.refusal ?? '');
677
+ }
678
+ if (first.plan.keptKey && siteDue(profile, Date.now())) {
679
+ // Once a day a served key first reads what its site says now; offline, the key serves.
680
+ probe = await probeToolInstance(toolBaseUrl, opts.fetch);
681
+ if (probe) {
682
+ rememberSite(env, tool, profileName, probe, { cloudUrl: opts.cloudUrl });
683
+ profile = read();
684
+ first = plan(factsOf(probe, now()));
685
+ if (first.plan.reason === 'refused') {
686
+ await settle(first);
687
+ throw new CliUsageError(first.plan.refusal ?? '');
688
+ }
689
+ }
690
+ }
691
+ const served = servedFrom(first.plan);
692
+ if (served) {
693
+ await settle(first);
694
+ return served;
695
+ }
281
696
  }
282
697
 
283
- // 3. The exchange resource defaults to THIS instance's registered resource
284
- // URL — its MCP endpoint, derived from the resolved instance origin.
285
- // The body names NO org: the exchange is user-scoped end to end.
286
- const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
287
- const connect = new CliConnectClient({
698
+ // 1. Only a site that signs in through a hub can mint through one: ask, never guess.
699
+ if (probe === undefined) probe = await probeToolInstance(toolBaseUrl, opts.fetch);
700
+ if (probe) {
701
+ rememberSite(env, tool, profileName, probe, { cloudUrl: opts.cloudUrl });
702
+ profile = read();
703
+ }
704
+ if (!probe?.cloud) {
705
+ // A site that answered, and signs in by itself: its stale keys go all the same. One that did not
706
+ // answer would not answer a revoke either.
707
+ if (probe) await settle(plan(factsOf(probe, now())));
708
+ return { outcome: 'not_cloud' };
709
+ }
710
+ const facts = factsOf(probe, now());
711
+
712
+ // 2. The plan on the fresh facts; what is stale goes first, before any error and any exchange.
713
+ const second = plan(facts);
714
+ await settle(second);
715
+ const { login, hub } = second.plan;
716
+ if (!login || !hub) throw new CliUsageError(second.sentence ?? second.plan.refusal ?? '');
717
+ const served = servedFrom(second.plan);
718
+ if (served) return served;
719
+ const signedIn = (email: string): ConnectedLogin => ({ name: login.name, hub, email });
720
+
721
+ // 3. The mint, single-flight per (profile, hub, e-mail).
722
+ const hubKey = text(login.profile.apiKey) ?? '';
723
+ const bin = firstSet(opts.bin) ?? tool;
724
+ const minted = await singleFlight(mintLockPath(env, tool, profileName, hub, login.email), async () => {
725
+ // The file read again: a key another command minted meanwhile is used; the keys it holds now are
726
+ // this command's last read before its exchange, never « first stored » at its store. A login that
727
+ // carried no address is read again too: another command's exchange may have told it, under this lock.
728
+ const again = read();
729
+ const address = login.email ?? addressNow(env, login);
730
+ const there = keptFor(again, address, hub, toolBaseUrl, opts.cloudUrl, avoid);
731
+ if (there) return { there };
732
+ const held = hubKeysOf(again).map((k) => k.apiKey);
733
+ // A hub the profile remembers (its `lastHub`, or a refused key's) may no longer be the site's.
734
+ const remembered = second.hubSource === 'remembered' || second.hubSource === 'refused_key';
735
+ const flag = profileFlag(toolBaseUrl, here ? profileName : undefined);
736
+ const result = await exchange(opts, toolBaseUrl, login.hub, hubKey, messages).catch((e: unknown) => {
737
+ throw remembered ? withWayOut(e, profileName, hub, toolBaseUrl, bin, flag) : e;
738
+ });
739
+ const email = text(result.user?.email) ?? login.email ?? '';
740
+ const entry: CliHubKey = { hub, email, apiKey: result.key, mintedAt: now() };
741
+ // 4. First stored wins; the hub the exchange went through is remembered with the key.
742
+ const store = storeHubKey(env, tool, profileName, entry, {
743
+ baseUrl: toolBaseUrl,
744
+ cloudUrl: opts.cloudUrl,
745
+ site: facts,
746
+ avoid,
747
+ lastHub: normalizeUrl(login.hub),
748
+ held
749
+ });
750
+ // 5. The login's address, as the hub answered it, written before the lock is let go: a command
751
+ // waiting on it with the same login then finds this key instead of minting its own.
752
+ const healed = 'kept' in store ? healLogin(env, login, email) : undefined;
753
+ return { result, email, store, healed };
754
+ });
755
+ if ('there' in minted) {
756
+ // Another command minted it while this one waited: nothing minted here.
757
+ return {
758
+ outcome: 'connected',
759
+ key: minted.there.apiKey,
760
+ cached: true,
761
+ login: signedIn(login.email ?? minted.there.email)
762
+ };
763
+ }
764
+
765
+ const { result, email, store, healed } = minted;
766
+ if ('elsewhere' in store) {
767
+ await revokeOrSay(opts, toolBaseUrl, result.key);
768
+ throw new CliUsageError(
769
+ `Profile "${profileName}" is the site ${normalizeUrl(store.elsewhere)}, and this command targets ${toolBaseUrl}.`
770
+ );
771
+ }
772
+ if ('unknown_site' in store) {
773
+ // Another writer gave the profile a key during the exchange: step 0 let it through, the store
774
+ // did not.
775
+ await revokeOrSay(opts, toolBaseUrl, result.key);
776
+ throw noSiteOfItsOwn(opts, toolBaseUrl);
777
+ }
778
+ const extra = healed ? { healed } : {};
779
+ if (!store.ours) {
780
+ const { answer } = await revokeOn(toolBaseUrl, result.key, opts.fetch, revokeLimit(opts));
781
+ // Refused (a 403): it stays valid there, and filed it would be refused again at every command.
782
+ if (answer === 'refused') opts.notify?.(unrevoked(toolBaseUrl));
783
+ if (answer === 'no_answer') {
784
+ // Never left live and unrecorded: filed undated in its slot, a stale duplicate the next
785
+ // command revokes; said instead when the profile is no longer at this site.
786
+ const lost: CliHubKey = { hub, email, apiKey: result.key, mintedAt: '' };
787
+ const place = { baseUrl: toolBaseUrl, cloudUrl: opts.cloudUrl };
788
+ if (!storeUnrevokedKey(env, tool, profileName, lost, place)) opts.notify?.(unrevoked(toolBaseUrl));
789
+ }
790
+ return { outcome: 'connected', key: store.kept.apiKey, cached: true, login: signedIn(email), ...extra };
791
+ }
792
+
793
+ // 6. The notice, and the key.
794
+ const notice: ConnectNoticeFacts = { toolBaseUrl, email, stored: true, profileName };
795
+ opts.notify?.((messages.connected ?? defaultConnected)(notice));
796
+ return {
797
+ outcome: 'connected',
798
+ key: result.key,
799
+ cached: false,
800
+ result,
801
+ stored: true,
802
+ login: signedIn(email),
803
+ ...extra
804
+ };
805
+ }
806
+
807
+ /** The kept key a profile holds now for the slot `(hub, email)` at this site, when it holds one (`avoid` aside). */
808
+ function keptFor(
809
+ profile: CliProfile | undefined,
810
+ email: string | undefined,
811
+ hub: string,
812
+ toolBaseUrl: string,
813
+ cloudUrl: string | undefined,
814
+ avoid: string | undefined
815
+ ): CliHubKey | undefined {
816
+ const at = profile ? profileUrl(profile, cloudUrl) : undefined;
817
+ if (!email || at === undefined || !sameInstance(at, toolBaseUrl)) return undefined;
818
+ const slot = { hub, email };
819
+ return newestKey(hubKeysOf(profile).filter((k) => k.apiKey !== avoid && sameSlot(k, slot)));
820
+ }
821
+
822
+ /**
823
+ * The address a login carries now in the hub file, while its entry is still that login (the same hub
824
+ * key): another command's exchange may have told it since this command read the file.
825
+ */
826
+ function addressNow(env: CliEnv, login: CliLogin): string | undefined {
827
+ const entry = loadConfig(env, HUB_TOOL).profiles[login.name];
828
+ return entry && entry.apiKey === login.profile.apiKey ? text(entry.email) : undefined;
829
+ }
830
+
831
+ /**
832
+ * The two-call exchange with the login's key, sent to the login's OWN hub:
833
+ * one attempt, with the hub's verdict on the KEY mapped to the guided login
834
+ * error whichever attempt it comes on, and one fresh exchange when the 120 s
835
+ * JWT died in transit. A refusal and every wire error propagate as they are.
836
+ */
837
+ async function exchange(
838
+ opts: ConnectOnDemandOptions,
839
+ toolBaseUrl: string,
840
+ hubBaseUrl: string,
841
+ hubKey: string,
842
+ messages: ConnectOnDemandMessages
843
+ ): Promise<CliConnectResult> {
844
+ const client = new CliConnectClient({
288
845
  hubBaseUrl,
289
846
  toolBaseUrl,
290
847
  ...(opts.fetch ? { fetch: opts.fetch } : {})
291
848
  });
292
- const body = { resource };
293
- // One attempt, with the hub's verdict on the KEY mapped to the guided
294
- // login error whichever attempt it comes on. A refusal (403 that is not
295
- // the scope case) and every wire error propagate as they are: the error
296
- // carries the server's own sentence and its exit code.
849
+ // The resource defaults to this site's registered resource URL; the body names NO org.
850
+ const body = { resource: opts.resource ?? `${toolBaseUrl}/mcp` };
297
851
  const attempt = async (): Promise<CliConnectResult> => {
298
852
  try {
299
- return await connect.exchange(hubKey, body);
853
+ return await client.exchange(hubKey, body);
300
854
  } catch (e) {
301
855
  if (e instanceof CliConnectError && e.needsHubLogin) {
302
856
  throw new CliUsageError(messages.hubLoginRejected ?? DEFAULT_HUB_LOGIN_REJECTED);
@@ -304,61 +858,85 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
304
858
  throw e;
305
859
  }
306
860
  };
307
- let result: CliConnectResult;
308
861
  try {
309
- result = await attempt();
862
+ return await attempt();
310
863
  } catch (e) {
311
864
  if (!(e instanceof CliConnectError && e.needsReExchange)) throw e;
312
- // The 120 s JWT died in transit (expired/replayed) — one fresh
313
- // exchange; a second rejection propagates.
314
- result = await attempt();
315
- }
316
-
317
- // 4. Cache the minted key on the SELECTED profile under the hub profile's
318
- // name. A profile not on disk yet, or one with no instance of its own,
319
- // takes this instance's URL; a profile at another instance never
320
- // receives the key and is never repointed.
321
- const stored = place !== 'elsewhere';
322
- if (stored) {
323
- storeConnectKey(
324
- opts.env,
325
- opts.tool,
326
- profileName,
327
- hub.name,
328
- { apiKey: result.key, email: result.user.email, mintedAt: new Date().toISOString() },
329
- { baseUrl: toolBaseUrl }
330
- );
865
+ return attempt();
331
866
  }
332
-
333
- const facts: ConnectNoticeFacts = {
334
- toolBaseUrl,
335
- email: result.user.email,
336
- stored,
337
- profileName,
338
- // `stored` is false only when the profile is at another instance.
339
- ...(stored ? {} : { profileBaseUrl: at })
340
- };
341
- opts.notify?.((messages.connected ?? defaultConnected)(facts));
342
-
343
- return { outcome: 'connected', key: result.key, result, cached: false, stored };
344
867
  }
345
868
 
346
869
  /**
347
870
  * The stranded-key recovery: what a tool CLI calls once when a request
348
- * answered 401 with a key that `connectOnDemand` served from the cache
349
- * (`cached: true`). Evicts that key from the selected profile (the hub
350
- * revoked it, or a membership was swept), only when that profile is at
351
- * this instance (a key of another instance is never touched), and runs the
352
- * exchange again with the cache skipped. The caller retries its request
353
- * once with the new key and fails on a second 401; `not_cloud` means there
354
- * is nothing to recover with, and the caller fails with its 401 as it
355
- * stands.
871
+ * answered 401 with a key `connectOnDemand` served (`cached: true`), with that
872
+ * key as `refusedKey`. COMPARE-AND-EVICT: the kept entry whose key is
873
+ * `refusedKey` is removed (only on a profile at this site); when none is,
874
+ * another command already replaced it, and the kept key the plan now serves
875
+ * is returned (`cached: true`) with no exchange. Otherwise the exchange runs
876
+ * again (`cached: false`), never serving the refused key. The refused key's
877
+ * slot is read before the eviction takes it away: the recovery continues the
878
+ * command whose key was refused, so its account picks the login at the hub
879
+ * the recovery signs in at, the way the `email` option does when the caller
880
+ * gives none, and its hub is the recovery's first hint, never the `hubUrl`
881
+ * option: for a site that names no hub, the order is `--hub`,
882
+ * `ANTASPHERE_URL`, the refused key's hub while a login is in place there,
883
+ * the newest kept key in place, then `lastHub`; a site that names a hub
884
+ * decides it. The eviction's own write also keeps that hub as the profile's
885
+ * `lastHub` when the profile holds none (one from before the field), for the
886
+ * commands after it. An exchange that hub refuses because it does not know
887
+ * the site ends on the way out, as at a remembered hub (`login --hub`). The
888
+ * caller retries its request once with the new key and fails on a second
889
+ * 401; `not_cloud` means there is nothing to recover with. A missing, blank
890
+ * or unreadable `hubCloudUrl` is a `TypeError` naming it, before anything is
891
+ * read, evicted or sent.
356
892
  */
357
- export async function refreshConnectKey(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
893
+ export async function refreshConnectKey(opts: RefreshConnectKeyOptions): Promise<ConnectOnDemandOutcome> {
358
894
  assertToolNamespace(opts.tool);
359
- const hub = activeHubProfile(opts.env);
360
- const existing = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
361
- const { place } = placeOf(existing, normalizeUrl(opts.toolBaseUrl), opts.cloudUrl);
362
- if (hub.name && place === 'here') removeConnectKey(opts.env, opts.tool, opts.profileName, hub.name);
363
- return connectOnDemand({ ...opts, cached: false });
895
+ requireHubCloudUrl('refreshConnectKey', opts.hubCloudUrl);
896
+ const { refusedKey, ...rest } = opts;
897
+ const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
898
+ const profile = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
899
+ const at = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
900
+ const here = at !== undefined && sameInstance(at, toolBaseUrl);
901
+ // The refused key's slot, before the eviction removes the only kept key that says which hub.
902
+ const refused = here
903
+ ? hubKeysOf(profile).find((k) => k.apiKey === refusedKey || k.apiKey.trim() === refusedKey)
904
+ : undefined;
905
+ const email = firstSet(opts.email, refused?.email);
906
+ // The refused key's hub: the recovery's first hint for a site that names none, and the profile's
907
+ // lastHub when it holds none.
908
+ const hubHint = refused?.hub;
909
+ const lastHub = refused && httpUrl(refused.hub) ? normalizeUrl(refused.hub) : undefined;
910
+ // The hub file first: one that does not parse stops the recovery before anything is written.
911
+ const { logins, undecided } = readLogins(opts.env, opts.hubCloudUrl);
912
+ if (here) {
913
+ const remember = lastHub ? { lastHub, site: toolBaseUrl, cloudUrl: opts.cloudUrl } : undefined;
914
+ if (!evictKey(opts.env, opts.tool, opts.profileName, refusedKey, remember)) {
915
+ const now = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
916
+ const decision = decide({
917
+ siteUrl: toolBaseUrl,
918
+ profileName: opts.profileName,
919
+ profile: now,
920
+ cloudUrl: opts.cloudUrl,
921
+ site: undefined,
922
+ logins,
923
+ undecided,
924
+ envHub: firstSet(opts.env[HUB_URL_ENV]),
925
+ hubUrl: opts.hubUrl,
926
+ email,
927
+ bin: firstSet(opts.bin) ?? opts.tool,
928
+ ownKeyFirst: false,
929
+ avoid: refusedKey,
930
+ hubHint,
931
+ now: new Date().toISOString()
932
+ });
933
+ const served = servedFrom(decision.plan);
934
+ if (served) {
935
+ // What is stale goes before the replacement is returned, as in every outcome of a command.
936
+ await revokeStale(opts, now, decision.plan.stale);
937
+ return served;
938
+ }
939
+ }
940
+ }
941
+ return connect({ ...rest, email, cached: false }, refusedKey, hubHint);
364
942
  }