@antasphere/cli-core 0.6.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 -96
  2. package/dist/auth.d.ts +1 -1
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/config.d.ts +120 -73
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +207 -109
  7. package/dist/config.js.map +1 -1
  8. package/dist/connect-on-demand.d.ts +194 -132
  9. package/dist/connect-on-demand.d.ts.map +1 -1
  10. package/dist/connect-on-demand.js +561 -148
  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 -158
  41. package/src/connect-on-demand.ts +797 -271
  42. package/src/connect.ts +8 -8
  43. package/src/index.ts +40 -27
  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,91 +1,124 @@
1
- import {
2
- assertToolNamespace,
3
- cachedConnectKey,
4
- HUB_TOOL,
5
- loadConfig,
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
- selectProfile
20
- } from './resolve.js';
21
- 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';
22
26
 
23
27
  /**
24
- * Connect-on-demand (binding patterns §7, gcloud model), extracted from the
25
- * Slideless CLI so every Antasphere tool CLI inherits "one `antasphere login`
26
- * serves every federated tool". When a tool CLI resolves NO credential of its
27
- * own, it calls `connectOnDemand` with the profile it selected
28
- * (`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.
29
34
  *
30
- * 0. The cache is consulted FIRST: a key minted earlier for THIS instance
31
- * under the hub profile (the one `ANTASPHERE_URL` names, else the
32
- * active one: `selectHubProfile`) is USER-scoped (hub ADR 014) — it
33
- * serves every subsequent run and every org, with zero network (no
34
- * probe, no hub round-trip, no fresh mint). It is read on the selected
35
- * profile only when that profile is at the resolved instance (its
36
- * `baseUrl`, else the tool's `cloudUrl` when the profile has none), so
37
- * a cached key never travels to another origin, and it is served only
38
- * to the address that minted it: the hub profile's `email` and the
39
- * cached entry's `email` must both be there and match
40
- * (`cachedConnectKey`). `cached: false` skips this step.
41
- * 1. On a miss, discovery gates the flow: only an Antasphere-CLOUD
42
- * instance can mint keys through the hub (unauthenticated GET
43
- * /instance — never guess). Unreachable, foreign, or self-hosted
44
- * instances answer `not_cloud` and the tool raises its classic no-key
45
- * error unchanged.
46
- * 2. The hub credential is what `antasphere login` stored on the hub
47
- * profile (the config home's HUB_TOOL namespace) — hub URL included,
48
- * never a hardcoded constant here. The hub profile is the one
49
- * `ANTASPHERE_URL` names (the profile at that instance, the way the
50
- * account CLI picks it), else the active one; a URL no hub profile is
51
- * at has no credential, and the guided `antasphere login` error says
52
- * so.
53
- * 3. `CliConnectClient.exchange` trades it for a tool-local key (one
54
- * re-exchange retry when the 120 s JWT dies in transit; a rejected hub
55
- * credential maps to guided `antasphere login` advice on either
56
- * attempt; a hub REFUSAL, a 403 that is not the scope case, propagates
57
- * as its `CliConnectError` with the hub's own sentence and `exitCode`
58
- * 3).
59
- * 4. The minted key is cached on the SELECTED profile under the hub
60
- * profile's name. A profile not on disk yet is created with this
61
- * instance's URL, and made active only when the tool had no profile at
62
- * all; an existing profile is never renamed or repointed, and one that
63
- * 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.
64
51
  *
65
- * A stranded key recovers: on a 401 with a key that came from the cache,
66
- * the tool CLI calls `refreshConnectKey` once (evict, exchange again with
67
- * `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.
68
89
  *
69
- * A new tool needs only its namespace, its cloud URL, and copy — the flow
70
- * 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.
71
96
  */
72
97
 
73
- /** What the unauthenticated discovery probe learned about a tool instance. */
98
+ /** What the unauthenticated discovery probe learned about a site. */
74
99
  export interface ToolInstanceProbe {
75
- /** Whether the instance signs in through the Antasphere hub (advertises
76
- * 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). */
77
104
  cloud: boolean;
78
- /** The instance's self-reported edition (`cloud`, `oss`, …). */
105
+ /** The site's self-reported edition (`cloud`, `oss`, …). */
79
106
  edition: string | undefined;
80
107
  /** The advertised auth methods (open enum — unknown entries kept). */
81
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;
82
115
  }
83
116
 
84
117
  /**
85
- * Probe a tool instance's unauthenticated discovery endpoint
118
+ * Probe a site's unauthenticated discovery endpoint
86
119
  * (`GET {toolBaseUrl}/api/v1/instance`). Returns what it advertises, or
87
- * `null` when the instance is unreachable or answers a foreign shape —
88
- * 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".
89
122
  */
90
123
  export async function probeToolInstance(
91
124
  toolBaseUrl: string,
@@ -102,142 +135,187 @@ export async function probeToolInstance(
102
135
  if (!res.ok) return null;
103
136
  const info = (await res.json().catch(() => null)) as {
104
137
  edition?: unknown;
105
- auth?: { methods?: unknown };
138
+ name?: unknown;
139
+ auth?: { methods?: unknown; hub?: unknown } | null;
140
+ cli?: { version?: unknown } | null;
106
141
  } | null;
107
142
  const methods = info?.auth?.methods;
108
143
  if (!Array.isArray(methods)) return null;
109
144
  const authMethods = methods.filter((m): m is string => typeof m === 'string');
110
145
  const edition = typeof info?.edition === 'string' ? info.edition : undefined;
111
- 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
+ };
112
156
  } catch {
113
157
  return null;
114
158
  }
115
159
  }
116
160
 
117
- /** The hub's URL env var: the instance the account CLI talks to. */
161
+ /** The hub's URL env var: for a site that names no hub, the hub a command signs in at. */
118
162
  export const HUB_URL_ENV = 'ANTASPHERE_URL';
119
163
 
120
- /**
121
- * The hub profile the exchange uses, selected the way the account CLI
122
- * selects it: when `ANTASPHERE_URL` is set, the profile at that instance
123
- * (`selectProfile`'s URL rule: the active one first when several name it,
124
- * then `cloud`, then the first declared); a URL nothing on disk names
125
- * yields the in-memory profile `selectProfile` makes (named for its host,
126
- * `cloud` for `cloudUrl`, a `baseUrl` and no key), so the caller's
127
- * missing-login error fires. Without `ANTASPHERE_URL`, the active profile,
128
- * and none when no profile is active (here the account CLI's rule differs:
129
- * it would fall back to its cloud profile; a tool CLI asks for a login
130
- * instead) (PRDCT-3392: following the active profile whatever
131
- * `ANTASPHERE_URL` said asked the wrong hub). Its NAME is the connect cache's slot (config.ts
132
- * `connectKeys`): stable per hub account on this machine, independent of
133
- * any org selection.
134
- */
135
- export function selectHubProfile(env: CliEnv, opts: { cloudUrl?: string | undefined } = {}): ResolvedProfile {
136
- const config = loadConfig(env, HUB_TOOL);
137
- const apiUrl = firstSet(env[HUB_URL_ENV]);
138
- if (apiUrl) {
139
- const { name, profile } = selectProfile({ config, apiUrl, cloudUrl: opts.cloudUrl });
140
- return { name, profile };
141
- }
142
- return resolveProfile(config, undefined);
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);
143
182
  }
144
183
 
145
184
  /**
146
- * The hub profile `ANTASPHERE_URL` names, else the active one — what
147
- * `antasphere login` stored. Kept for the callers of 0.5.
148
- *
149
- * @deprecated Use `selectHubProfile`, which also takes the hub's cloud URL.
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.
150
191
  */
151
- export function activeHubProfile(env: CliEnv): ResolvedProfile {
152
- return selectHubProfile(env);
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;
153
220
  }
154
221
 
155
- /** The facts the connected notice is rendered from (fresh exchanges only —
156
- * cache hits are silent). */
222
+ /** The facts the connected notice is rendered from (fresh exchanges only — served keys are silent). */
157
223
  export interface ConnectNoticeFacts {
158
- /** The tool instance the exchange connected to (origin-normalized). */
224
+ /** The site the exchange connected to (origin-normalized). */
159
225
  toolBaseUrl: string;
160
- /** The signed-in account's email at mint. */
226
+ /** The signed-in account's email, as the hub answered it. */
161
227
  email: string;
162
- /** Whether the minted key was persisted for the next run (on the
163
- * selected profile, under the hub profile's name); false = the profile
164
- * 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). */
165
230
  stored: boolean;
166
- /** The tool profile the cache targeted. */
231
+ /** The tool profile the key is kept on. */
167
232
  profileName: string;
168
- /** When NOT stored: the other instance the profile is at. */
233
+ /** Never set any more (kept for the shape of 0.6). */
169
234
  profileBaseUrl?: string;
170
235
  }
171
236
 
172
237
  /**
173
- * Branded copy seams. Defaults reproduce the Slideless CLI's strings modulo
174
- * the tool name (the tool namespace stands in for the display name, and the
175
- * 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.
176
241
  */
177
242
  export interface ConnectOnDemandMessages {
178
- /** `CliUsageError` text when the instance is cloud but no `antasphere
179
- * login` credential is stored on the hub profile. */
180
- missingHubLogin?: string;
181
- /** `CliUsageError` text when the hub rejected the stored credential. */
243
+ /** `CliUsageError` text when the hub rejected the login's stored key. */
182
244
  hubLoginRejected?: string;
183
245
  /** Renders the success notice handed to `notify` (newline included). */
184
246
  connected?: (facts: ConnectNoticeFacts) => string;
185
247
  }
186
248
 
187
- function defaultMissingHubLogin(tool: string): string {
188
- const envVar = `${tool.replace(/-/g, '_').toUpperCase()}_API_KEY`;
189
- return (
190
- `This ${tool} instance signs in through the Antasphere hub. Run \`antasphere login\` once, ` +
191
- `then retry — or pass --api-key / set ${envVar}.`
192
- );
193
- }
194
-
195
249
  const DEFAULT_HUB_LOGIN_REJECTED =
196
250
  'The stored Antasphere hub credential was rejected — run `antasphere login` again, then retry.';
197
251
 
198
252
  function defaultConnected(facts: ConnectNoticeFacts): string {
199
- return (
200
- `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere` +
201
- (facts.stored
202
- ? ''
203
- : ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
204
- '.\n'
205
- );
253
+ return `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere.\n`;
206
254
  }
207
255
 
208
256
  export interface ConnectOnDemandOptions {
209
- /** 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). */
210
258
  tool: string;
211
- /** The resolved tool instance origin the CLI is talking to. */
259
+ /** The site the command talks to. */
212
260
  toolBaseUrl: string;
213
261
  /** The tool's cloud URL, the same value `selectProfile` got: what a
214
262
  * profile with no `baseUrl` of its own is at. Omit only for a tool with
215
- * no cloud instance. */
263
+ * no cloud site. */
216
264
  cloudUrl?: string | undefined;
217
- /** The hub's cloud URL, three roles: what the implicit `cloud` hub profile
218
- * is at, so an `ANTASPHERE_URL` equal to it names the `cloud` slot (omit
219
- * and a fresh hub profile is named for its host); where a hub profile
220
- * with no `baseUrl` is placed for the selection; and the hub URL such a
221
- * profile's exchange goes to. A profile's own `baseUrl` always wins. */
222
- hubCloudUrl?: string | undefined;
223
- /** 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,
224
278
  * `${toolBaseUrl}/mcp` (the tool's registered resource URL). */
225
279
  resource?: string;
226
280
  /** The tool profile the CLI selected for this run (`selectProfile`), the
227
- * one the minted key is cached on. Not on disk yet → created with
228
- * `toolBaseUrl` on first contact; at another instance → the key is
229
- * 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. */
230
284
  profileName: string;
231
285
  env: CliEnv;
232
286
  fetch?: typeof globalThis.fetch;
233
- /** Receives the human "Connected to …" notice (tools wire their stderr);
234
- * 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. */
235
290
  notify?: (line: string) => void;
236
291
  messages?: ConnectOnDemandMessages;
237
- /** false = do not read the cache: run the exchange even when a key is
238
- * cached (the one re-exchange after a 401 on a cached key;
239
- * `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. */
240
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;
241
319
  }
242
320
 
243
321
  export type ConnectOnDemandOutcome =
@@ -245,110 +323,534 @@ export type ConnectOnDemandOutcome =
245
323
  outcome: 'connected';
246
324
  /** The tool-local key — this invocation's credential. */
247
325
  key: string;
248
- /** true = served from the (tool profile, hub profile) config cache:
249
- * zero network, nothing minted. false = a fresh exchange ran. A 401
250
- * 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`. */
251
329
  cached: boolean;
330
+ /** The login that signed the command in. */
331
+ login: ConnectedLogin;
252
332
  /** Fresh exchanges only: the full result (user, key meta). */
253
333
  result?: CliConnectResult;
254
- /** Fresh exchanges only: whether the minted key was persisted for
255
- * the next run (false = the profile is at another instance). */
334
+ /** Fresh exchanges only: the minted key is kept on the profile (always true). */
256
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 };
257
339
  }
258
340
  | {
259
- /** Not an Antasphere-cloud instance (or unreachable): the caller
341
+ /** Not a site that signs in through an Antasphere hub (or unreachable): the caller
260
342
  * raises its classic no-key error unchanged. */
261
343
  outcome: 'not_cloud';
262
344
  };
263
345
 
264
- /**
265
- * Where the selected profile stands with respect to the resolved instance:
266
- * `here` (its `baseUrl`, else the tool's cloud URL, is this instance),
267
- * `elsewhere` (it is at another instance), or `free` (absent, or with no
268
- * instance at all: no `baseUrl` and no cloud URL known). The cache is read
269
- * only when `here`; a key is stored unless `elsewhere`; a key is evicted
270
- * only when `here`.
271
- */
272
- function placeOf(
273
- 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,
274
350
  toolBaseUrl: string,
275
351
  cloudUrl: string | undefined
276
- ): { place: 'here' | 'elsewhere' | 'free'; at?: string } {
277
- const at = existing ? profileUrl(existing, cloudUrl) : undefined;
278
- if (!existing || at === undefined) return { place: 'free' };
279
- 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`;
280
550
  }
281
551
 
282
552
  /**
283
- * The hub → tool exchange fallback a tool CLI runs when no direct credential
284
- * resolved. Serves the cached user-scoped key when one exists for this
285
- * (instance, hub profile) on the selected profile; otherwise returns
286
- * `not_cloud` when the instance is not an Antasphere-cloud one (or
287
- * unreachable). Throws a guided `CliUsageError` when the instance IS cloud
288
- * but the hub login is missing or rejected; a refusal and every other
289
- * exchange failure propagate as their `CliConnectError` (`exitCode` says 3
290
- * 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.
291
610
  */
292
611
  export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
293
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;
294
625
  const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
295
626
  const messages = opts.messages ?? {};
296
- const { profileName } = opts;
297
-
298
- // 0. The cache: a key minted earlier by the hub profile (the one
299
- // ANTASPHERE_URL names, else the active one) is user-scoped — it serves
300
- // every run and every org (hub ADR 014; the org is a per-request
301
- // parameter, never part of the credential). Only the selected profile
302
- // is read, and only when it is at THIS instance: a cached key never
303
- // travels to a different instance. It is served only to the address
304
- // that minted it (both e-mails there and equal). A hit costs zero
305
- // network. `cached: false` (the re-exchange after a 401) skips it.
306
- const hub = selectHubProfile(opts.env, { cloudUrl: opts.hubCloudUrl });
307
- const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
308
- const { place, at } = placeOf(existing, toolBaseUrl, opts.cloudUrl);
309
- if (opts.cached !== false && place === 'here' && hub.name) {
310
- const cachedKey = cachedConnectKey(existing, hub.name, hub.profile?.email);
311
- 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);
312
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
+ };
313
670
 
314
- // 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
315
- // never guess. An unreachable or foreign instance is `not_cloud`.
316
- const probe = await probeToolInstance(toolBaseUrl, opts.fetch);
317
- if (!probe?.cloud) return { outcome: 'not_cloud' };
318
-
319
- // 2. The hub credential is what `antasphere login` stored on the hub
320
- // profile (HUB_TOOL namespace) — one login for the whole tool family.
321
- // The hub URL comes from that same profile, never from a constant here;
322
- // an in-memory profile (ANTASPHERE_URL naming no profile) has no key.
323
- // A blank field is no field (the package's one blank rule, firstSet).
324
- const hubKey = firstSet(hub.profile?.apiKey);
325
- // A hub profile with no baseUrl (a hand edit, another writer: every
326
- // Antasphere login writes one) is at the hub's cloud URL when the caller
327
- // names one, the same rule a tool profile has with `cloudUrl`, and the
328
- // rule `selectProfile` already applies to place it; the exchange half
329
- // agrees with the selection half (verifier round 1, F4; round 3, F2).
330
- const hubBaseUrl = firstSet(hub.profile?.baseUrl, opts.hubCloudUrl);
331
- if (!hubKey || !hubBaseUrl || !hub.name) {
332
- 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
+ }
333
696
  }
334
697
 
335
- // 3. The exchange resource defaults to THIS instance's registered resource
336
- // URL — its MCP endpoint, derived from the resolved instance origin.
337
- // The body names NO org: the exchange is user-scoped end to end.
338
- const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
339
- 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({
340
845
  hubBaseUrl,
341
846
  toolBaseUrl,
342
847
  ...(opts.fetch ? { fetch: opts.fetch } : {})
343
848
  });
344
- const body = { resource };
345
- // One attempt, with the hub's verdict on the KEY mapped to the guided
346
- // login error whichever attempt it comes on. A refusal (403 that is not
347
- // the scope case) and every wire error propagate as they are: the error
348
- // 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` };
349
851
  const attempt = async (): Promise<CliConnectResult> => {
350
852
  try {
351
- return await connect.exchange(hubKey, body);
853
+ return await client.exchange(hubKey, body);
352
854
  } catch (e) {
353
855
  if (e instanceof CliConnectError && e.needsHubLogin) {
354
856
  throw new CliUsageError(messages.hubLoginRejected ?? DEFAULT_HUB_LOGIN_REJECTED);
@@ -356,61 +858,85 @@ export async function connectOnDemand(opts: ConnectOnDemandOptions): Promise<Con
356
858
  throw e;
357
859
  }
358
860
  };
359
- let result: CliConnectResult;
360
861
  try {
361
- result = await attempt();
862
+ return await attempt();
362
863
  } catch (e) {
363
864
  if (!(e instanceof CliConnectError && e.needsReExchange)) throw e;
364
- // The 120 s JWT died in transit (expired/replayed) — one fresh
365
- // exchange; a second rejection propagates.
366
- result = await attempt();
367
- }
368
-
369
- // 4. Cache the minted key on the SELECTED profile under the hub profile's
370
- // name. A profile not on disk yet, or one with no instance of its own,
371
- // takes this instance's URL; a profile at another instance never
372
- // receives the key and is never repointed.
373
- const stored = place !== 'elsewhere';
374
- if (stored) {
375
- storeConnectKey(
376
- opts.env,
377
- opts.tool,
378
- profileName,
379
- hub.name,
380
- { apiKey: result.key, email: result.user.email, mintedAt: new Date().toISOString() },
381
- { baseUrl: toolBaseUrl }
382
- );
865
+ return attempt();
383
866
  }
384
-
385
- const facts: ConnectNoticeFacts = {
386
- toolBaseUrl,
387
- email: result.user.email,
388
- stored,
389
- profileName,
390
- // `stored` is false only when the profile is at another instance.
391
- ...(stored ? {} : { profileBaseUrl: at })
392
- };
393
- opts.notify?.((messages.connected ?? defaultConnected)(facts));
394
-
395
- return { outcome: 'connected', key: result.key, result, cached: false, stored };
396
867
  }
397
868
 
398
869
  /**
399
870
  * The stranded-key recovery: what a tool CLI calls once when a request
400
- * answered 401 with a key that `connectOnDemand` served from the cache
401
- * (`cached: true`). Evicts that key from the selected profile (the hub
402
- * revoked it, or a membership was swept), only when that profile is at
403
- * this instance (a key of another instance is never touched), and runs the
404
- * exchange again with the cache skipped. The caller retries its request
405
- * once with the new key and fails on a second 401; `not_cloud` means there
406
- * is nothing to recover with, and the caller fails with its 401 as it
407
- * 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.
408
892
  */
409
- export async function refreshConnectKey(opts: ConnectOnDemandOptions): Promise<ConnectOnDemandOutcome> {
893
+ export async function refreshConnectKey(opts: RefreshConnectKeyOptions): Promise<ConnectOnDemandOutcome> {
410
894
  assertToolNamespace(opts.tool);
411
- const hub = selectHubProfile(opts.env, { cloudUrl: opts.hubCloudUrl });
412
- const existing = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
413
- const { place } = placeOf(existing, normalizeUrl(opts.toolBaseUrl), opts.cloudUrl);
414
- if (hub.name && place === 'here') removeConnectKey(opts.env, opts.tool, opts.profileName, hub.name);
415
- 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);
416
942
  }