@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,11 +1,16 @@
1
- import { assertToolNamespace, cachedConnectKey, HUB_TOOL, loadConfig, removeConnectKey, storeConnectKey } 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';
2
4
  import { CliConnectClient, CliConnectError } from './connect.js';
3
- import { CliUsageError, firstSet, normalizeUrl, profileUrl, resolveProfile, sameInstance, selectProfile } from './resolve.js';
5
+ import { evictKey, forgetKeys, hasOldSlots, hubKeysOf, keysHeldElsewhere, keysOfProfile, moveOldSlots, newestKey, sameEmail, sameSlot, storeHubKey, storeUnrevokedKey, text } from './kept-keys.js';
6
+ import { withFileLockAsync } from './lock.js';
7
+ import { decide, httpUrl, profileFlag, readLogins, requireHubCloudUrl, siteFactsOf } from './sign-in.js';
8
+ import { CliUsageError, firstSet, normalizeUrl, profileUrl, sameInstance, selectProfile } from './resolve.js';
4
9
  /**
5
- * Probe a tool instance's unauthenticated discovery endpoint
10
+ * Probe a site's unauthenticated discovery endpoint
6
11
  * (`GET {toolBaseUrl}/api/v1/instance`). Returns what it advertises, or
7
- * `null` when the instance is unreachable or answers a foreign shape —
8
- * callers treat both exactly like "not cloud".
12
+ * `null` when the site is unreachable or answers a foreign shape — callers
13
+ * treat both exactly like "not cloud".
9
14
  */
10
15
  export async function probeToolInstance(toolBaseUrl, fetchImpl) {
11
16
  const f = fetchImpl ?? globalThis.fetch.bind(globalThis);
@@ -24,142 +29,517 @@ export async function probeToolInstance(toolBaseUrl, fetchImpl) {
24
29
  return null;
25
30
  const authMethods = methods.filter((m) => typeof m === 'string');
26
31
  const edition = typeof info?.edition === 'string' ? info.edition : undefined;
27
- return { cloud: authMethods.includes('antasphere') || edition === 'cloud', edition, authMethods };
32
+ const hub = text(info?.auth?.hub);
33
+ return {
34
+ url: normalizeUrl(toolBaseUrl),
35
+ cloud: authMethods.includes('antasphere') || edition === 'cloud',
36
+ edition,
37
+ authMethods,
38
+ hub: hub ? normalizeUrl(hub) : null,
39
+ name: typeof info?.name === 'string' ? info.name : null,
40
+ cliVersion: typeof info?.cli?.version === 'string' ? info.cli.version : null
41
+ };
28
42
  }
29
43
  catch {
30
44
  return null;
31
45
  }
32
46
  }
33
- /** The hub's URL env var: the instance the account CLI talks to. */
47
+ /** The hub's URL env var: for a site that names no hub, the hub a command signs in at. */
34
48
  export const HUB_URL_ENV = 'ANTASPHERE_URL';
49
+ const DAY_MS = 24 * 60 * 60 * 1000;
50
+ /** The limit of each revoke cli-core sends on a command's way, when `requestTimeoutMs` gives none. */
51
+ const REVOKE_TIMEOUT_MS = 10_000;
52
+ /** The longest limit a Node timer takes as it is (2^31 − 1 ms): a longer one is cut to 1 ms. */
53
+ const MAX_REVOKE_TIMEOUT_MS = 2_147_483_647;
54
+ /** The facts a probe gives, as a profile remembers them. */
55
+ function factsOf(probe, seenAt) {
56
+ return { hub: probe.hub, federated: probe.cloud, name: probe.name, cliVersion: probe.cliVersion, seenAt };
57
+ }
58
+ /** Whether a profile's memory of its site is missing, unreadable, or not from the last 24 hours. */
59
+ function siteDue(profile, nowMs) {
60
+ const site = siteFactsOf(profile);
61
+ const age = site ? nowMs - Date.parse(site.seenAt) : Number.NaN;
62
+ return !(age >= 0 && age <= DAY_MS);
63
+ }
35
64
  /**
36
- * The hub profile the exchange uses, selected the way the account CLI
37
- * selects it: when `ANTASPHERE_URL` is set, the profile at that instance
38
- * (`selectProfile`'s URL rule: the active one first when several name it,
39
- * then `cloud`, then the first declared); a URL nothing on disk names
40
- * yields the in-memory profile `selectProfile` makes (named for its host,
41
- * `cloud` for `cloudUrl`, a `baseUrl` and no key), so the caller's
42
- * missing-login error fires. Without `ANTASPHERE_URL`, the active profile,
43
- * and none when no profile is active (here the account CLI's rule differs:
44
- * it would fall back to its cloud profile; a tool CLI asks for a login
45
- * instead) (PRDCT-3392: following the active profile whatever
46
- * `ANTASPHERE_URL` said asked the wrong hub). Its NAME is the connect cache's slot (config.ts
47
- * `connectKeys`): stable per hub account on this machine, independent of
48
- * any org selection.
65
+ * Remember what a site said of itself on its profile, under `updateConfig`:
66
+ * only for a profile on disk at that site (`probe.url`; a profile with no
67
+ * `baseUrl` is at `cloudUrl`), and only when the hub, `federated`, the name
68
+ * or the CLI version differ from what the profile holds, or when its
69
+ * `seenAt` is older than 24 hours, or with `force` (`profiles --check`).
70
+ * Otherwise nothing is written. Answers whether the file changed.
49
71
  */
50
- export function selectHubProfile(env, opts = {}) {
51
- const config = loadConfig(env, HUB_TOOL);
52
- const apiUrl = firstSet(env[HUB_URL_ENV]);
53
- if (apiUrl) {
54
- const { name, profile } = selectProfile({ config, apiUrl, cloudUrl: opts.cloudUrl });
55
- return { name, profile };
72
+ export function rememberSite(env, tool, profileName, probe, opts = {}) {
73
+ assertToolNamespace(tool);
74
+ const atSite = (profile) => {
75
+ const at = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
76
+ return at !== undefined && sameInstance(at, probe.url);
77
+ };
78
+ if (!atSite(loadConfig(env, tool).profiles[profileName]))
79
+ return false;
80
+ const now = Date.now();
81
+ const facts = factsOf(probe, new Date(now).toISOString());
82
+ return updateConfig(env, tool, (config) => {
83
+ const profile = config.profiles[profileName];
84
+ if (!atSite(profile))
85
+ return;
86
+ const held = siteFactsOf(profile);
87
+ const same = held !== undefined &&
88
+ held.hub === facts.hub &&
89
+ held.federated === facts.federated &&
90
+ held.name === facts.name &&
91
+ held.cliVersion === facts.cliVersion;
92
+ if (!opts.force && same && !siteDue(profile, now))
93
+ return;
94
+ profile.site = facts;
95
+ }).changed;
96
+ }
97
+ const DEFAULT_HUB_LOGIN_REJECTED = 'The stored Antasphere hub credential was rejected — run `antasphere login` again, then retry.';
98
+ function defaultConnected(facts) {
99
+ return `Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere.\n`;
100
+ }
101
+ /** Throws the refusal of a profile at another site than the command's; answers whether it is at it. */
102
+ function atCommandSite(profile, profileName, toolBaseUrl, cloudUrl) {
103
+ const at = profile ? profileUrl(profile, cloudUrl) : undefined;
104
+ if (at === undefined)
105
+ return false;
106
+ if (!sameInstance(at, toolBaseUrl)) {
107
+ throw new CliUsageError(`Profile "${profileName}" is the site ${normalizeUrl(at)}, and this command targets ${toolBaseUrl}.`);
56
108
  }
57
- return resolveProfile(config, undefined);
109
+ return true;
58
110
  }
59
111
  /**
60
- * The hub profile `ANTASPHERE_URL` names, else the active one — what
61
- * `antasphere login` stored. Kept for the callers of 0.5.
62
- *
63
- * @deprecated Use `selectHubProfile`, which also takes the hub's cloud URL.
112
+ * The refusal of a profile with no site of its own that holds keys (of no
113
+ * known site, never adopted): no key this command mints can be kept on it.
114
+ * It names where the person signs in instead: the profile of this site on
115
+ * disk by its name, else the site itself (`profileFlag`, the rule of every
116
+ * sentence).
64
117
  */
65
- export function activeHubProfile(env) {
66
- return selectHubProfile(env);
118
+ function noSiteOfItsOwn(opts, toolBaseUrl) {
119
+ const bin = firstSet(opts.bin) ?? opts.tool;
120
+ const there = selectProfile({
121
+ config: loadConfig(opts.env, opts.tool),
122
+ apiUrl: toolBaseUrl,
123
+ cloudUrl: opts.cloudUrl
124
+ });
125
+ const way = profileFlag(toolBaseUrl, there.created ? undefined : there.name);
126
+ return new CliUsageError(`Profile "${opts.profileName}" has no site of its own and holds keys of no known site, so this command ` +
127
+ `cannot keep a key on it. Sign in on a profile of ${toolBaseUrl} instead (${bin} ${way} login).`);
67
128
  }
68
- function defaultMissingHubLogin(tool) {
69
- const envVar = `${tool.replace(/-/g, '_').toUpperCase()}_API_KEY`;
70
- return (`This ${tool} instance signs in through the Antasphere hub. Run \`antasphere login\` once, ` +
71
- `then retry — or pass --api-key / set ${envVar}.`);
129
+ /** The outcome of a kept key the plan serves. */
130
+ function servedFrom(plan) {
131
+ const { keptKey, login, hub } = plan;
132
+ if (!keptKey || !login || !hub)
133
+ return undefined;
134
+ return {
135
+ outcome: 'connected',
136
+ key: keptKey.apiKey,
137
+ cached: true,
138
+ login: { name: login.name, hub, email: login.email ?? keptKey.email }
139
+ };
72
140
  }
73
- const DEFAULT_HUB_LOGIN_REJECTED = 'The stored Antasphere hub credential was rejected — run `antasphere login` again, then retry.';
74
- function defaultConnected(facts) {
75
- return (`Connected to ${facts.toolBaseUrl} as ${facts.email} via Antasphere` +
76
- (facts.stored
77
- ? ''
78
- : ` — key NOT cached: profile '${facts.profileName}' points at ${facts.profileBaseUrl}`) +
79
- '.\n');
141
+ /**
142
+ * The limit of each revoke on a command's way: `requestTimeoutMs` when it is an integer from 1 to
143
+ * 2^31 − 1, else 10 s.
144
+ */
145
+ function revokeLimit(opts) {
146
+ const given = opts.requestTimeoutMs;
147
+ if (typeof given !== 'number' || !Number.isInteger(given))
148
+ return REVOKE_TIMEOUT_MS;
149
+ return given >= 1 && given <= MAX_REVOKE_TIMEOUT_MS ? given : REVOKE_TIMEOUT_MS;
150
+ }
151
+ /** A fetch whose every request is aborted past `ms`, as well as by any signal it already carries. */
152
+ function limitedFetch(fetchImpl, ms) {
153
+ const base = fetchImpl ?? globalThis.fetch.bind(globalThis);
154
+ return (input, init) => {
155
+ const limit = AbortSignal.timeout(ms);
156
+ const carried = init?.signal ?? (input instanceof Request ? input.signal : undefined);
157
+ return base(input, { ...init, signal: carried ? AbortSignal.any([carried, limit]) : limit });
158
+ };
159
+ }
160
+ /**
161
+ * What a site answered to the revoke of a key, within `ms`: `revoked`; `dead` on a 401 (already
162
+ * unusable); `refused` on a 403, with its code; `no_answer` for anything else (a 5xx, a network error,
163
+ * a revoke the limit aborted).
164
+ */
165
+ async function revokeOn(site, apiKey, fetchImpl, ms) {
166
+ const auth = new CliAuthClient({ baseUrl: site, fetch: limitedFetch(fetchImpl, ms) });
167
+ try {
168
+ await auth.revoke(apiKey);
169
+ return { answer: 'revoked' };
170
+ }
171
+ catch (e) {
172
+ if (e instanceof CliAuthError && e.status === 401)
173
+ return { answer: 'dead' };
174
+ if (e instanceof CliAuthError && e.status === 403)
175
+ return { answer: 'refused', code: e.code };
176
+ return { answer: 'no_answer' };
177
+ }
178
+ }
179
+ /**
180
+ * The exchange a hub the profile remembers refused because it does not know
181
+ * this site's resource (`unknown_resource`): a hub chosen from its `lastHub`,
182
+ * or a recovery's hint (the refused key's hub). The same error, with the way
183
+ * out appended, naming the profile by `flag` (`profileFlag`). Any other error
184
+ * is returned as it is.
185
+ */
186
+ function withWayOut(e, profileName, hub, site, bin, flag) {
187
+ if (!(e instanceof CliConnectError) || e.stage !== 'hub' || e.code !== 'unknown_resource')
188
+ return e;
189
+ const said = /[.!?]$/.test(e.message.trim()) ? e.message.trim() : `${e.message.trim()}.`;
190
+ return new CliConnectError(e.stage, e.status, e.code, `${said} Profile "${profileName}" last signed in through ${hub}; if ${site} trusts another hub now, ` +
191
+ `run ${bin} ${flag} login --hub <hub>.`, e.details);
192
+ }
193
+ /** The line `notify` gets when a key minted on a site could not be revoked there (no key in it). */
194
+ function unrevoked(site) {
195
+ return `A key minted on ${site} could not be revoked there; revoke it from that site.\n`;
196
+ }
197
+ /** Revoke a key this command minted and cannot keep, on the site that minted it; say so unless it is dead. */
198
+ async function revokeOrSay(opts, site, apiKey) {
199
+ const { answer } = await revokeOn(site, apiKey, opts.fetch, revokeLimit(opts));
200
+ if (answer !== 'revoked' && answer !== 'dead')
201
+ opts.notify?.(unrevoked(site));
202
+ }
203
+ /**
204
+ * Revoke the stale keys of a profile on the profile's OWN site, then forget
205
+ * the ones that site answered for, compare-and-remove. The lock is never held
206
+ * across the network: the keys were decided from a read, the revokes run with
207
+ * no lock, and `forgetKeys` takes the lock again. A key the site answered
208
+ * already unusable (a 401) or refused to revoke (a 403) is forgotten all the
209
+ * same, and `notify` says so; a 5xx or no answer keeps the key for the next
210
+ * command. The first revoke with no answer ends the revokes of the call: that
211
+ * key and every key not tried yet stay for the next command, and nothing more
212
+ * is sent to that site, so one call of `revokeStale` costs at most one limit
213
+ * (`requestTimeoutMs`); the keys answered before it are forgotten. A key
214
+ * another profile at that same site still holds (`keysHeldElsewhere`, on the
215
+ * tool's file read once before the revokes) is not revoked: it is forgotten on
216
+ * this profile only, in the same `forgetKeys`, whether it comes before or
217
+ * after a revoke with no answer (it sends nothing), and `notify` says so once
218
+ * per profile that holds one.
219
+ */
220
+ async function revokeStale(opts, profile, stale) {
221
+ const site = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
222
+ if (stale.length === 0 || site === undefined)
223
+ return;
224
+ const elsewhere = keysHeldElsewhere(loadConfig(opts.env, opts.tool), opts.profileName, site, opts.cloudUrl);
225
+ const said = new Set();
226
+ const forget = [];
227
+ // Set by the first revoke the site did not answer: nothing more is sent to it by this call.
228
+ let unanswered = false;
229
+ for (const key of stale) {
230
+ const other = elsewhere.get(key.apiKey.trim());
231
+ if (other === undefined) {
232
+ if (unanswered)
233
+ continue;
234
+ const { answer, code } = await revokeOn(site, key.apiKey, opts.fetch, revokeLimit(opts));
235
+ if (answer === 'no_answer') {
236
+ unanswered = true;
237
+ continue;
238
+ }
239
+ forget.push(key.apiKey);
240
+ const [at, name] = [normalizeUrl(site), opts.profileName];
241
+ if (answer === 'dead') {
242
+ opts.notify?.(`A stale key of profile "${name}" was already unusable on ${at}; forgetting it.\n`);
243
+ }
244
+ if (answer === 'refused') {
245
+ opts.notify?.(`${at} refused to revoke a stale key of profile "${name}" (${code}): it stays valid there; ` +
246
+ 'revoke it from that site. Forgetting it here.\n');
247
+ }
248
+ continue;
249
+ }
250
+ const line = `Kept on ${normalizeUrl(site)}: profile "${other}" still holds that key.\n`;
251
+ if (!said.has(line))
252
+ opts.notify?.(line);
253
+ said.add(line);
254
+ forget.push(key.apiKey);
255
+ }
256
+ forgetKeys(opts.env, opts.tool, opts.profileName, forget);
257
+ }
258
+ /** The mint lock of one (profile, hub, e-mail): beside the tool's file, one per slot. */
259
+ function mintLockPath(env, tool, profileName, hub, email) {
260
+ const file = configPath(env, tool);
261
+ if (!file)
262
+ return null;
263
+ const id = createHash('sha256')
264
+ .update(`${profileName}\n${hub}\n${email?.trim().toLowerCase() ?? ''}`)
265
+ .digest('hex')
266
+ .slice(0, 16);
267
+ return `${file}.mint-${id}.lock`;
268
+ }
269
+ /**
270
+ * Run the mint of a slot single-flight across processes: under its lock
271
+ * (60 s timeout, a holder older than 120 s taken over). A waiter past the
272
+ * timeout, or a lock that cannot be taken, proceeds without it: the mint
273
+ * never fails on its lock.
274
+ */
275
+ async function singleFlight(lockPath, fn) {
276
+ if (!lockPath)
277
+ return fn();
278
+ let entered = false;
279
+ try {
280
+ return await withFileLockAsync(lockPath, () => {
281
+ entered = true;
282
+ return fn();
283
+ }, { timeoutMs: 60_000, staleMs: 120_000 });
284
+ }
285
+ catch (e) {
286
+ if (entered)
287
+ throw e;
288
+ return fn();
289
+ }
80
290
  }
81
291
  /**
82
- * Where the selected profile stands with respect to the resolved instance:
83
- * `here` (its `baseUrl`, else the tool's cloud URL, is this instance),
84
- * `elsewhere` (it is at another instance), or `free` (absent, or with no
85
- * instance at all: no `baseUrl` and no cloud URL known). The cache is read
86
- * only when `here`; a key is stored unless `elsewhere`; a key is evicted
87
- * only when `here`.
292
+ * Write the hub's answered address on the login when it carried none or
293
+ * another one (the hub file, compare-and-set on the login's key: a login
294
+ * replaced meanwhile is left alone). Answers what changed.
88
295
  */
89
- function placeOf(existing, toolBaseUrl, cloudUrl) {
90
- const at = existing ? profileUrl(existing, cloudUrl) : undefined;
91
- if (!existing || at === undefined)
92
- return { place: 'free' };
93
- return sameInstance(at, toolBaseUrl) ? { place: 'here', at } : { place: 'elsewhere', at };
296
+ function healLogin(env, login, answered) {
297
+ if (!text(answered) || sameEmail(login.email, answered))
298
+ return undefined;
299
+ let healed;
300
+ updateConfig(env, HUB_TOOL, (config) => {
301
+ const entry = config.profiles[login.name];
302
+ if (!entry || entry.apiKey !== login.profile.apiKey || sameEmail(entry.email, answered))
303
+ return;
304
+ entry.email = answered;
305
+ healed = { from: login.email ?? null, to: answered };
306
+ });
307
+ return healed;
94
308
  }
95
309
  /**
96
- * The hub → tool exchange fallback a tool CLI runs when no direct credential
97
- * resolved. Serves the cached user-scoped key when one exists for this
98
- * (instance, hub profile) on the selected profile; otherwise returns
99
- * `not_cloud` when the instance is not an Antasphere-cloud one (or
100
- * unreachable). Throws a guided `CliUsageError` when the instance IS cloud
101
- * but the hub login is missing or rejected; a refusal and every other
102
- * exchange failure propagate as their `CliConnectError` (`exitCode` says 3
103
- * for the refusal, `message` is the server's own sentence).
310
+ * The hub → tool exchange a tool CLI runs when no direct credential resolved,
311
+ * signed in by the login at the hub the site trusts (the flow is the module
312
+ * comment's). Answers the key (`cached: true` when kept, false when minted by
313
+ * this command) with the login that signed it in, or `not_cloud`. Throws a
314
+ * `CliUsageError` naming the way out when the profile is at another site or
315
+ * has no site of its own while it holds a key (both before any request),
316
+ * when `ANTASPHERE_URL` or `hubUrl` names another hub than the site's, when
317
+ * a hub or a login must be picked, when no login is at the site's hub, or
318
+ * when the hub rejected the login's key; a refusal and every other exchange
319
+ * failure propagate as their `CliConnectError` (`exitCode` 3 for a refusal).
320
+ * A missing, blank or unreadable `hubCloudUrl` is a `TypeError` naming it,
321
+ * before any read, request or write.
104
322
  */
105
323
  export async function connectOnDemand(opts) {
106
324
  assertToolNamespace(opts.tool);
325
+ requireHubCloudUrl('connectOnDemand', opts.hubCloudUrl);
326
+ return connect(opts, undefined, undefined);
327
+ }
328
+ /** The command's sign-in; a recovery passes the refused key (`avoid`) and its hub (`hubHint`). */
329
+ async function connect(opts, avoid, hubHint) {
330
+ assertToolNamespace(opts.tool);
331
+ const { env, tool, profileName } = opts;
107
332
  const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
108
333
  const messages = opts.messages ?? {};
109
- const { profileName } = opts;
110
- // 0. The cache: a key minted earlier by the hub profile (the one
111
- // ANTASPHERE_URL names, else the active one) is user-scoped — it serves
112
- // every run and every org (hub ADR 014; the org is a per-request
113
- // parameter, never part of the credential). Only the selected profile
114
- // is read, and only when it is at THIS instance: a cached key never
115
- // travels to a different instance. It is served only to the address
116
- // that minted it (both e-mails there and equal). A hit costs zero
117
- // network. `cached: false` (the re-exchange after a 401) skips it.
118
- const hub = selectHubProfile(opts.env, { cloudUrl: opts.hubCloudUrl });
119
- const existing = loadConfig(opts.env, opts.tool).profiles[profileName];
120
- const { place, at } = placeOf(existing, toolBaseUrl, opts.cloudUrl);
121
- if (opts.cached !== false && place === 'here' && hub.name) {
122
- const cachedKey = cachedConnectKey(existing, hub.name, hub.profile?.email);
123
- if (cachedKey)
124
- return { outcome: 'connected', key: cachedKey, cached: true };
125
- }
126
- // 1. Only a CLOUD instance can mint keys through the hub — ask discovery,
127
- // never guess. An unreachable or foreign instance is `not_cloud`.
128
- const probe = await probeToolInstance(toolBaseUrl, opts.fetch);
129
- if (!probe?.cloud)
334
+ const now = () => new Date().toISOString();
335
+ const read = () => loadConfig(env, tool).profiles[profileName];
336
+ // 0. The profile and its place; the old slots moved once.
337
+ let profile = read();
338
+ const here = atCommandSite(profile, profileName, toolBaseUrl, opts.cloudUrl);
339
+ // A profile with no site of its own that holds a key (the store's own condition) cannot keep the
340
+ // key: refused before any request, so nothing is minted, revoked or written.
341
+ if (profile && profileUrl(profile, opts.cloudUrl) === undefined && keysOfProfile(profile).length > 0) {
342
+ throw noSiteOfItsOwn(opts, toolBaseUrl);
343
+ }
344
+ const { logins, undecided } = readLogins(env, opts.hubCloudUrl);
345
+ if (here && hasOldSlots(profile)) {
346
+ moveOldSlots(env, tool, profileName, logins, now());
347
+ profile = read();
348
+ }
349
+ const plan = (site) => decide({
350
+ siteUrl: toolBaseUrl,
351
+ profileName,
352
+ profile,
353
+ cloudUrl: opts.cloudUrl,
354
+ site,
355
+ logins,
356
+ undecided,
357
+ envHub: firstSet(env[HUB_URL_ENV]),
358
+ hubUrl: opts.hubUrl,
359
+ email: opts.email,
360
+ bin: firstSet(opts.bin) ?? tool,
361
+ ownKeyFirst: false,
362
+ avoid,
363
+ hubHint,
364
+ now: now()
365
+ });
366
+ // What is stale goes before ANY outcome of the command, its errors included: revoked on the
367
+ // profile's own site (no lock held), then forgotten, and the profile read again; a site that did
368
+ // not answer keeps the key for the next command.
369
+ const settle = async (decision) => {
370
+ if (decision.plan.stale.length === 0)
371
+ return;
372
+ await revokeStale(opts, here ? profile : undefined, decision.plan.stale);
373
+ profile = read();
374
+ };
375
+ let probe;
376
+ if (opts.cached !== false) {
377
+ let first = plan(undefined);
378
+ if (first.plan.reason === 'refused') {
379
+ await settle(first);
380
+ throw new CliUsageError(first.plan.refusal ?? '');
381
+ }
382
+ if (first.plan.keptKey && siteDue(profile, Date.now())) {
383
+ // Once a day a served key first reads what its site says now; offline, the key serves.
384
+ probe = await probeToolInstance(toolBaseUrl, opts.fetch);
385
+ if (probe) {
386
+ rememberSite(env, tool, profileName, probe, { cloudUrl: opts.cloudUrl });
387
+ profile = read();
388
+ first = plan(factsOf(probe, now()));
389
+ if (first.plan.reason === 'refused') {
390
+ await settle(first);
391
+ throw new CliUsageError(first.plan.refusal ?? '');
392
+ }
393
+ }
394
+ }
395
+ const served = servedFrom(first.plan);
396
+ if (served) {
397
+ await settle(first);
398
+ return served;
399
+ }
400
+ }
401
+ // 1. Only a site that signs in through a hub can mint through one: ask, never guess.
402
+ if (probe === undefined)
403
+ probe = await probeToolInstance(toolBaseUrl, opts.fetch);
404
+ if (probe) {
405
+ rememberSite(env, tool, profileName, probe, { cloudUrl: opts.cloudUrl });
406
+ profile = read();
407
+ }
408
+ if (!probe?.cloud) {
409
+ // A site that answered, and signs in by itself: its stale keys go all the same. One that did not
410
+ // answer would not answer a revoke either.
411
+ if (probe)
412
+ await settle(plan(factsOf(probe, now())));
130
413
  return { outcome: 'not_cloud' };
131
- // 2. The hub credential is what `antasphere login` stored on the hub
132
- // profile (HUB_TOOL namespace) — one login for the whole tool family.
133
- // The hub URL comes from that same profile, never from a constant here;
134
- // an in-memory profile (ANTASPHERE_URL naming no profile) has no key.
135
- // A blank field is no field (the package's one blank rule, firstSet).
136
- const hubKey = firstSet(hub.profile?.apiKey);
137
- // A hub profile with no baseUrl (a hand edit, another writer: every
138
- // Antasphere login writes one) is at the hub's cloud URL when the caller
139
- // names one, the same rule a tool profile has with `cloudUrl`, and the
140
- // rule `selectProfile` already applies to place it; the exchange half
141
- // agrees with the selection half (verifier round 1, F4; round 3, F2).
142
- const hubBaseUrl = firstSet(hub.profile?.baseUrl, opts.hubCloudUrl);
143
- if (!hubKey || !hubBaseUrl || !hub.name) {
144
- throw new CliUsageError(messages.missingHubLogin ?? defaultMissingHubLogin(opts.tool));
145
- }
146
- // 3. The exchange resource defaults to THIS instance's registered resource
147
- // URL — its MCP endpoint, derived from the resolved instance origin.
148
- // The body names NO org: the exchange is user-scoped end to end.
149
- const resource = opts.resource ?? `${toolBaseUrl}/mcp`;
150
- const connect = new CliConnectClient({
414
+ }
415
+ const facts = factsOf(probe, now());
416
+ // 2. The plan on the fresh facts; what is stale goes first, before any error and any exchange.
417
+ const second = plan(facts);
418
+ await settle(second);
419
+ const { login, hub } = second.plan;
420
+ if (!login || !hub)
421
+ throw new CliUsageError(second.sentence ?? second.plan.refusal ?? '');
422
+ const served = servedFrom(second.plan);
423
+ if (served)
424
+ return served;
425
+ const signedIn = (email) => ({ name: login.name, hub, email });
426
+ // 3. The mint, single-flight per (profile, hub, e-mail).
427
+ const hubKey = text(login.profile.apiKey) ?? '';
428
+ const bin = firstSet(opts.bin) ?? tool;
429
+ const minted = await singleFlight(mintLockPath(env, tool, profileName, hub, login.email), async () => {
430
+ // The file read again: a key another command minted meanwhile is used; the keys it holds now are
431
+ // this command's last read before its exchange, never « first stored » at its store. A login that
432
+ // carried no address is read again too: another command's exchange may have told it, under this lock.
433
+ const again = read();
434
+ const address = login.email ?? addressNow(env, login);
435
+ const there = keptFor(again, address, hub, toolBaseUrl, opts.cloudUrl, avoid);
436
+ if (there)
437
+ return { there };
438
+ const held = hubKeysOf(again).map((k) => k.apiKey);
439
+ // A hub the profile remembers (its `lastHub`, or a refused key's) may no longer be the site's.
440
+ const remembered = second.hubSource === 'remembered' || second.hubSource === 'refused_key';
441
+ const flag = profileFlag(toolBaseUrl, here ? profileName : undefined);
442
+ const result = await exchange(opts, toolBaseUrl, login.hub, hubKey, messages).catch((e) => {
443
+ throw remembered ? withWayOut(e, profileName, hub, toolBaseUrl, bin, flag) : e;
444
+ });
445
+ const email = text(result.user?.email) ?? login.email ?? '';
446
+ const entry = { hub, email, apiKey: result.key, mintedAt: now() };
447
+ // 4. First stored wins; the hub the exchange went through is remembered with the key.
448
+ const store = storeHubKey(env, tool, profileName, entry, {
449
+ baseUrl: toolBaseUrl,
450
+ cloudUrl: opts.cloudUrl,
451
+ site: facts,
452
+ avoid,
453
+ lastHub: normalizeUrl(login.hub),
454
+ held
455
+ });
456
+ // 5. The login's address, as the hub answered it, written before the lock is let go: a command
457
+ // waiting on it with the same login then finds this key instead of minting its own.
458
+ const healed = 'kept' in store ? healLogin(env, login, email) : undefined;
459
+ return { result, email, store, healed };
460
+ });
461
+ if ('there' in minted) {
462
+ // Another command minted it while this one waited: nothing minted here.
463
+ return {
464
+ outcome: 'connected',
465
+ key: minted.there.apiKey,
466
+ cached: true,
467
+ login: signedIn(login.email ?? minted.there.email)
468
+ };
469
+ }
470
+ const { result, email, store, healed } = minted;
471
+ if ('elsewhere' in store) {
472
+ await revokeOrSay(opts, toolBaseUrl, result.key);
473
+ throw new CliUsageError(`Profile "${profileName}" is the site ${normalizeUrl(store.elsewhere)}, and this command targets ${toolBaseUrl}.`);
474
+ }
475
+ if ('unknown_site' in store) {
476
+ // Another writer gave the profile a key during the exchange: step 0 let it through, the store
477
+ // did not.
478
+ await revokeOrSay(opts, toolBaseUrl, result.key);
479
+ throw noSiteOfItsOwn(opts, toolBaseUrl);
480
+ }
481
+ const extra = healed ? { healed } : {};
482
+ if (!store.ours) {
483
+ const { answer } = await revokeOn(toolBaseUrl, result.key, opts.fetch, revokeLimit(opts));
484
+ // Refused (a 403): it stays valid there, and filed it would be refused again at every command.
485
+ if (answer === 'refused')
486
+ opts.notify?.(unrevoked(toolBaseUrl));
487
+ if (answer === 'no_answer') {
488
+ // Never left live and unrecorded: filed undated in its slot, a stale duplicate the next
489
+ // command revokes; said instead when the profile is no longer at this site.
490
+ const lost = { hub, email, apiKey: result.key, mintedAt: '' };
491
+ const place = { baseUrl: toolBaseUrl, cloudUrl: opts.cloudUrl };
492
+ if (!storeUnrevokedKey(env, tool, profileName, lost, place))
493
+ opts.notify?.(unrevoked(toolBaseUrl));
494
+ }
495
+ return { outcome: 'connected', key: store.kept.apiKey, cached: true, login: signedIn(email), ...extra };
496
+ }
497
+ // 6. The notice, and the key.
498
+ const notice = { toolBaseUrl, email, stored: true, profileName };
499
+ opts.notify?.((messages.connected ?? defaultConnected)(notice));
500
+ return {
501
+ outcome: 'connected',
502
+ key: result.key,
503
+ cached: false,
504
+ result,
505
+ stored: true,
506
+ login: signedIn(email),
507
+ ...extra
508
+ };
509
+ }
510
+ /** The kept key a profile holds now for the slot `(hub, email)` at this site, when it holds one (`avoid` aside). */
511
+ function keptFor(profile, email, hub, toolBaseUrl, cloudUrl, avoid) {
512
+ const at = profile ? profileUrl(profile, cloudUrl) : undefined;
513
+ if (!email || at === undefined || !sameInstance(at, toolBaseUrl))
514
+ return undefined;
515
+ const slot = { hub, email };
516
+ return newestKey(hubKeysOf(profile).filter((k) => k.apiKey !== avoid && sameSlot(k, slot)));
517
+ }
518
+ /**
519
+ * The address a login carries now in the hub file, while its entry is still that login (the same hub
520
+ * key): another command's exchange may have told it since this command read the file.
521
+ */
522
+ function addressNow(env, login) {
523
+ const entry = loadConfig(env, HUB_TOOL).profiles[login.name];
524
+ return entry && entry.apiKey === login.profile.apiKey ? text(entry.email) : undefined;
525
+ }
526
+ /**
527
+ * The two-call exchange with the login's key, sent to the login's OWN hub:
528
+ * one attempt, with the hub's verdict on the KEY mapped to the guided login
529
+ * error whichever attempt it comes on, and one fresh exchange when the 120 s
530
+ * JWT died in transit. A refusal and every wire error propagate as they are.
531
+ */
532
+ async function exchange(opts, toolBaseUrl, hubBaseUrl, hubKey, messages) {
533
+ const client = new CliConnectClient({
151
534
  hubBaseUrl,
152
535
  toolBaseUrl,
153
536
  ...(opts.fetch ? { fetch: opts.fetch } : {})
154
537
  });
155
- const body = { resource };
156
- // One attempt, with the hub's verdict on the KEY mapped to the guided
157
- // login error whichever attempt it comes on. A refusal (403 that is not
158
- // the scope case) and every wire error propagate as they are: the error
159
- // carries the server's own sentence and its exit code.
538
+ // The resource defaults to this site's registered resource URL; the body names NO org.
539
+ const body = { resource: opts.resource ?? `${toolBaseUrl}/mcp` };
160
540
  const attempt = async () => {
161
541
  try {
162
- return await connect.exchange(hubKey, body);
542
+ return await client.exchange(hubKey, body);
163
543
  }
164
544
  catch (e) {
165
545
  if (e instanceof CliConnectError && e.needsHubLogin) {
@@ -168,54 +548,87 @@ export async function connectOnDemand(opts) {
168
548
  throw e;
169
549
  }
170
550
  };
171
- let result;
172
551
  try {
173
- result = await attempt();
552
+ return await attempt();
174
553
  }
175
554
  catch (e) {
176
555
  if (!(e instanceof CliConnectError && e.needsReExchange))
177
556
  throw e;
178
- // The 120 s JWT died in transit (expired/replayed) — one fresh
179
- // exchange; a second rejection propagates.
180
- result = await attempt();
181
- }
182
- // 4. Cache the minted key on the SELECTED profile under the hub profile's
183
- // name. A profile not on disk yet, or one with no instance of its own,
184
- // takes this instance's URL; a profile at another instance never
185
- // receives the key and is never repointed.
186
- const stored = place !== 'elsewhere';
187
- if (stored) {
188
- storeConnectKey(opts.env, opts.tool, profileName, hub.name, { apiKey: result.key, email: result.user.email, mintedAt: new Date().toISOString() }, { baseUrl: toolBaseUrl });
189
- }
190
- const facts = {
191
- toolBaseUrl,
192
- email: result.user.email,
193
- stored,
194
- profileName,
195
- // `stored` is false only when the profile is at another instance.
196
- ...(stored ? {} : { profileBaseUrl: at })
197
- };
198
- opts.notify?.((messages.connected ?? defaultConnected)(facts));
199
- return { outcome: 'connected', key: result.key, result, cached: false, stored };
557
+ return attempt();
558
+ }
200
559
  }
201
560
  /**
202
561
  * The stranded-key recovery: what a tool CLI calls once when a request
203
- * answered 401 with a key that `connectOnDemand` served from the cache
204
- * (`cached: true`). Evicts that key from the selected profile (the hub
205
- * revoked it, or a membership was swept), only when that profile is at
206
- * this instance (a key of another instance is never touched), and runs the
207
- * exchange again with the cache skipped. The caller retries its request
208
- * once with the new key and fails on a second 401; `not_cloud` means there
209
- * is nothing to recover with, and the caller fails with its 401 as it
210
- * stands.
562
+ * answered 401 with a key `connectOnDemand` served (`cached: true`), with that
563
+ * key as `refusedKey`. COMPARE-AND-EVICT: the kept entry whose key is
564
+ * `refusedKey` is removed (only on a profile at this site); when none is,
565
+ * another command already replaced it, and the kept key the plan now serves
566
+ * is returned (`cached: true`) with no exchange. Otherwise the exchange runs
567
+ * again (`cached: false`), never serving the refused key. The refused key's
568
+ * slot is read before the eviction takes it away: the recovery continues the
569
+ * command whose key was refused, so its account picks the login at the hub
570
+ * the recovery signs in at, the way the `email` option does when the caller
571
+ * gives none, and its hub is the recovery's first hint, never the `hubUrl`
572
+ * option: for a site that names no hub, the order is `--hub`,
573
+ * `ANTASPHERE_URL`, the refused key's hub while a login is in place there,
574
+ * the newest kept key in place, then `lastHub`; a site that names a hub
575
+ * decides it. The eviction's own write also keeps that hub as the profile's
576
+ * `lastHub` when the profile holds none (one from before the field), for the
577
+ * commands after it. An exchange that hub refuses because it does not know
578
+ * the site ends on the way out, as at a remembered hub (`login --hub`). The
579
+ * caller retries its request once with the new key and fails on a second
580
+ * 401; `not_cloud` means there is nothing to recover with. A missing, blank
581
+ * or unreadable `hubCloudUrl` is a `TypeError` naming it, before anything is
582
+ * read, evicted or sent.
211
583
  */
212
584
  export async function refreshConnectKey(opts) {
213
585
  assertToolNamespace(opts.tool);
214
- const hub = selectHubProfile(opts.env, { cloudUrl: opts.hubCloudUrl });
215
- const existing = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
216
- const { place } = placeOf(existing, normalizeUrl(opts.toolBaseUrl), opts.cloudUrl);
217
- if (hub.name && place === 'here')
218
- removeConnectKey(opts.env, opts.tool, opts.profileName, hub.name);
219
- return connectOnDemand({ ...opts, cached: false });
586
+ requireHubCloudUrl('refreshConnectKey', opts.hubCloudUrl);
587
+ const { refusedKey, ...rest } = opts;
588
+ const toolBaseUrl = normalizeUrl(opts.toolBaseUrl);
589
+ const profile = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
590
+ const at = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
591
+ const here = at !== undefined && sameInstance(at, toolBaseUrl);
592
+ // The refused key's slot, before the eviction removes the only kept key that says which hub.
593
+ const refused = here
594
+ ? hubKeysOf(profile).find((k) => k.apiKey === refusedKey || k.apiKey.trim() === refusedKey)
595
+ : undefined;
596
+ const email = firstSet(opts.email, refused?.email);
597
+ // The refused key's hub: the recovery's first hint for a site that names none, and the profile's
598
+ // lastHub when it holds none.
599
+ const hubHint = refused?.hub;
600
+ const lastHub = refused && httpUrl(refused.hub) ? normalizeUrl(refused.hub) : undefined;
601
+ // The hub file first: one that does not parse stops the recovery before anything is written.
602
+ const { logins, undecided } = readLogins(opts.env, opts.hubCloudUrl);
603
+ if (here) {
604
+ const remember = lastHub ? { lastHub, site: toolBaseUrl, cloudUrl: opts.cloudUrl } : undefined;
605
+ if (!evictKey(opts.env, opts.tool, opts.profileName, refusedKey, remember)) {
606
+ const now = loadConfig(opts.env, opts.tool).profiles[opts.profileName];
607
+ const decision = decide({
608
+ siteUrl: toolBaseUrl,
609
+ profileName: opts.profileName,
610
+ profile: now,
611
+ cloudUrl: opts.cloudUrl,
612
+ site: undefined,
613
+ logins,
614
+ undecided,
615
+ envHub: firstSet(opts.env[HUB_URL_ENV]),
616
+ hubUrl: opts.hubUrl,
617
+ email,
618
+ bin: firstSet(opts.bin) ?? opts.tool,
619
+ ownKeyFirst: false,
620
+ avoid: refusedKey,
621
+ hubHint,
622
+ now: new Date().toISOString()
623
+ });
624
+ const served = servedFrom(decision.plan);
625
+ if (served) {
626
+ // What is stale goes before the replacement is returned, as in every outcome of a command.
627
+ await revokeStale(opts, now, decision.plan.stale);
628
+ return served;
629
+ }
630
+ }
631
+ }
632
+ return connect({ ...rest, email, cached: false }, refusedKey, hubHint);
220
633
  }
221
634
  //# sourceMappingURL=connect-on-demand.js.map