@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
@@ -0,0 +1,484 @@
1
+ import { loadConfig, updateConfig } from './config.js';
2
+ import { firstSet, profileUrl, sameInstance } from './resolve.js';
3
+ /**
4
+ * The keys a tool profile keeps (PRDCT-5192). A KEPT KEY is filed by the
5
+ * hub's address and the account's e-mail (`hubKeys`), never by a login's
6
+ * name, so renaming a login, or signing out and in again with the same
7
+ * account, strands nothing.
8
+ *
9
+ * - One key per `(hub, e-mail)`: the newest `mintedAt` is kept; another one
10
+ * for the same pair is STALE (an undated one is the oldest).
11
+ * - A kept key whose login is GONE (no login at its hub carrying its e-mail
12
+ * nor carrying none: nobody is signed in there, or only other accounts
13
+ * are) is STALE; so is one whose hub is not the hub the site names, when
14
+ * the site names one. A login that comes back mints a new key.
15
+ * - The OLD shape (`connectKeys[<login name>]`) is moved once, by the first
16
+ * command that resolves a credential on the profile: when the login of
17
+ * that name is in place and carries the entry's e-mail, the entry moves to
18
+ * `hubKeys` under that login's hub; otherwise it is STALE.
19
+ * - Unknown is not gone: while the hub file holds an entry with a key whose
20
+ * hub cannot be told (`undecidedLogins`), no key is judged gone for want of
21
+ * a login, an old slot no login matches included (`judgeGone: false`); a
22
+ * key of another hub than the site's and a duplicate stay stale. Nor is a
23
+ * key that carries an e-mail while a login at its hub carries none: that
24
+ * login may be its account. It is never served to that login (the exchange
25
+ * runs and tells the address, and from then on the rules above settle the
26
+ * key), and an old slot whose login of that name carries no e-mail stays
27
+ * where it is, neither moved nor stale, until the address is known. A key
28
+ * that carries no e-mail is matched by no login.
29
+ *
30
+ * A stale key is revoked on the profile's own site, then forgotten; until its
31
+ * revoke succeeds it stays where it is in the file, never served. A stale key
32
+ * another profile at that same site still holds is never revoked there: it is
33
+ * forgotten on this profile only (`keysHeldElsewhere`). A key the profile
34
+ * keeps, or its own key, is never stale whatever else names it.
35
+ * Everything here that writes is one `updateConfig`; nothing here touches the
36
+ * network.
37
+ */
38
+ /** A value of the file as a trimmed string, or undefined when it is not a non-blank string. */
39
+ export function text(value) {
40
+ return typeof value === 'string' ? firstSet(value) : undefined;
41
+ }
42
+ /** An e-mail in its comparable form: trimmed and case-folded; undefined when blank or absent. */
43
+ export function foldEmail(email) {
44
+ return text(email)?.toLowerCase();
45
+ }
46
+ /** Whether two e-mails are one address: both present, equal once trimmed and case-folded. */
47
+ export function sameEmail(a, b) {
48
+ const x = foldEmail(a);
49
+ return x !== undefined && x === foldEmail(b);
50
+ }
51
+ /** A mint's time for comparisons: its epoch ms, or -Infinity when absent or unreadable (the oldest). */
52
+ export function mintTime(mintedAt) {
53
+ const t = typeof mintedAt === 'string' ? Date.parse(mintedAt) : Number.NaN;
54
+ return Number.isNaN(t) ? -Infinity : t;
55
+ }
56
+ /** The newest of some kept keys (ties go to the first), or undefined. */
57
+ export function newestKey(keys) {
58
+ let best;
59
+ for (const key of keys)
60
+ if (!best || mintTime(key.mintedAt) > mintTime(best.mintedAt))
61
+ best = key;
62
+ return best;
63
+ }
64
+ /** Whether two kept keys fill one slot: one hub (`sameInstance`), one e-mail (case-folded). */
65
+ export function sameSlot(a, b) {
66
+ return sameInstance(a.hub, b.hub) && sameEmail(a.email, b.email);
67
+ }
68
+ /**
69
+ * Whether the machine cannot tell that a login is not the account of a key's e-mail: the login
70
+ * carries that e-mail, or it carries none while the key carries one (« cannot tell »). A key that
71
+ * carries no e-mail is no login's.
72
+ */
73
+ function mayBeItsLogin(login, email) {
74
+ return (sameEmail(login.email, email) || (foldEmail(login.email) === undefined && foldEmail(email) !== undefined));
75
+ }
76
+ function isObject(value) {
77
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
78
+ }
79
+ /** The profile's kept keys that read as keys, in the file's order (`mintedAt` '' when absent). */
80
+ export function hubKeysOf(profile) {
81
+ const raw = profile?.hubKeys;
82
+ if (!Array.isArray(raw))
83
+ return [];
84
+ const keys = [];
85
+ for (const k of raw) {
86
+ if (!isObject(k) || !text(k.apiKey) || typeof k.hub !== 'string' || typeof k.email !== 'string')
87
+ continue;
88
+ keys.push({
89
+ hub: k.hub,
90
+ email: k.email,
91
+ apiKey: k.apiKey,
92
+ mintedAt: typeof k.mintedAt === 'string' ? k.mintedAt : ''
93
+ });
94
+ }
95
+ return keys;
96
+ }
97
+ /** The profile's old slots that hold a key, in the file's order. */
98
+ function oldSlotsOf(profile) {
99
+ const raw = profile?.connectKeys;
100
+ if (!isObject(raw))
101
+ return [];
102
+ const slots = [];
103
+ for (const [slot, entry] of Object.entries(raw)) {
104
+ if (!isObject(entry) || !text(entry.apiKey))
105
+ continue;
106
+ slots.push([
107
+ slot,
108
+ {
109
+ apiKey: entry.apiKey,
110
+ ...(typeof entry.email === 'string' ? { email: entry.email } : {}),
111
+ ...(typeof entry.mintedAt === 'string' ? { mintedAt: entry.mintedAt } : {})
112
+ }
113
+ ]);
114
+ }
115
+ return slots;
116
+ }
117
+ /**
118
+ * The one move of the old slots, decided without writing: an entry whose
119
+ * login (by name) is in place and carries its e-mail becomes `{ hub: <that
120
+ * login's hub>, email, apiKey, mintedAt: entry.mintedAt ?? now }`, unless the
121
+ * slot already holds a key at least as new (an undated entry is the oldest);
122
+ * an entry with an e-mail whose login of that name carries none stays where
123
+ * it is, neither moved nor stale (« cannot tell »); every other entry stays,
124
+ * stale, except one no login matches while `judgeGone` is false, which
125
+ * stays, not stale.
126
+ */
127
+ function planMove(profile, logins, now, judgeGone = true) {
128
+ const plan = { moved: [], dropped: [], stays: [] };
129
+ const current = hubKeysOf(profile).map((key) => ({
130
+ key,
131
+ time: mintTime(key.mintedAt)
132
+ }));
133
+ for (const [slot, entry] of oldSlotsOf(profile)) {
134
+ if (current.some((c) => c.key.apiKey === entry.apiKey)) {
135
+ plan.dropped.push(slot);
136
+ continue;
137
+ }
138
+ const login = logins.find((l) => l.name === slot);
139
+ const email = text(entry.email) ?? '';
140
+ // Its login carries no address: it may be this slot's account. It waits for the address.
141
+ if (login && foldEmail(login.email) === undefined && email)
142
+ continue;
143
+ if (!login || !sameEmail(login.email, email)) {
144
+ // No login of that name carrying its address: gone, when the machine can tell.
145
+ if (judgeGone) {
146
+ plan.stays.push({ hub: '', email, apiKey: entry.apiKey, mintedAt: entry.mintedAt ?? '' });
147
+ }
148
+ continue;
149
+ }
150
+ const key = { hub: login.hub, email, apiKey: entry.apiKey, mintedAt: entry.mintedAt ?? now };
151
+ let rival;
152
+ for (const c of current)
153
+ if (sameSlot(c.key, key) && (!rival || c.time > rival.time))
154
+ rival = c;
155
+ if (rival && !(mintTime(entry.mintedAt) > rival.time)) {
156
+ plan.stays.push({ ...key, mintedAt: entry.mintedAt ?? '' });
157
+ continue;
158
+ }
159
+ current.push({ key, time: mintTime(key.mintedAt) });
160
+ plan.moved.push({ slot, key });
161
+ }
162
+ return plan;
163
+ }
164
+ /**
165
+ * Sort a profile's keys out against the logins in place and the hub the site
166
+ * names (`siteHub`: a string when it names one, null or undefined when it
167
+ * names none or was never reached), as they will stand once the old slots
168
+ * are moved. `judgeGone: false` (the hub file holds an entry whose hub cannot
169
+ * be told) judges no key gone for want of a login. Pure: nothing is written.
170
+ */
171
+ export function sortKeys(profile, logins, siteHub, now, opts = {}) {
172
+ if (!profile)
173
+ return { kept: [], stale: [] };
174
+ const judgeGone = opts.judgeGone !== false;
175
+ const move = planMove(profile, logins, now, judgeGone);
176
+ const winners = [];
177
+ const stale = [...move.stays];
178
+ for (const key of [...hubKeysOf(profile), ...move.moved.map((m) => m.key)]) {
179
+ const i = winners.findIndex((w) => sameSlot(w, key));
180
+ if (i < 0)
181
+ winners.push(key);
182
+ else if (mintTime(key.mintedAt) > mintTime(winners[i].mintedAt)) {
183
+ stale.push(winners[i]);
184
+ winners[i] = key;
185
+ }
186
+ else
187
+ stale.push(key);
188
+ }
189
+ const kept = [];
190
+ for (const key of winners) {
191
+ const otherHub = typeof siteHub === 'string' && !sameInstance(key.hub, siteHub);
192
+ // Gone: no login at its hub that may be its account (one carrying its address, or carrying none),
193
+ // whether nobody is signed in there or only other accounts are; judged only when every keyed
194
+ // entry of the hub file has a hub to tell.
195
+ const gone = judgeGone && !logins.some((l) => sameInstance(l.hub, key.hub) && mayBeItsLogin(l, key.email));
196
+ if (otherHub || gone)
197
+ stale.push(key);
198
+ else
199
+ kept.push(key);
200
+ }
201
+ // A key the profile keeps, or its own key, is never revoked, whatever else names it.
202
+ const keep = new Set(kept.map((k) => k.apiKey));
203
+ const own = text(profile.apiKey);
204
+ if (own)
205
+ keep.add(own);
206
+ const seen = new Set();
207
+ return {
208
+ kept,
209
+ stale: stale.filter((k) => {
210
+ const key = k.apiKey.trim();
211
+ if (keep.has(k.apiKey) || keep.has(key) || seen.has(key))
212
+ return false;
213
+ seen.add(key);
214
+ return true;
215
+ })
216
+ };
217
+ }
218
+ /** Whether a profile holds old slots (or an empty old map) the move would touch. */
219
+ export function hasOldSlots(profile) {
220
+ return profile?.connectKeys !== undefined;
221
+ }
222
+ /**
223
+ * The one move of the old slots of a profile, under the file's lock (the
224
+ * logins as `listLogins` read them): the matched slots move to `hubKeys`, a
225
+ * slot that duplicates a kept key is dropped, the stale ones stay until their
226
+ * revoke, and `connectKeys` goes once empty. A second run changes nothing and
227
+ * writes nothing. The caller has checked the profile is at its site.
228
+ */
229
+ export function moveOldSlots(env, tool, profileName, logins, now) {
230
+ return updateConfig(env, tool, (config) => {
231
+ const profile = config.profiles[profileName];
232
+ const raw = profile?.connectKeys;
233
+ if (!profile || !isObject(raw))
234
+ return;
235
+ const move = planMove(profile, logins, now);
236
+ const gone = new Set([...move.moved.map((m) => m.slot), ...move.dropped]);
237
+ if (move.moved.length > 0) {
238
+ const keys = profile.hubKeys;
239
+ profile.hubKeys = [
240
+ ...(Array.isArray(keys) ? keys : []),
241
+ ...move.moved.map((m) => m.key)
242
+ ];
243
+ }
244
+ const rest = Object.entries(raw).filter(([slot]) => !gone.has(slot));
245
+ if (rest.length === 0)
246
+ delete profile.connectKeys;
247
+ else if (gone.size > 0)
248
+ profile.connectKeys = Object.fromEntries(rest);
249
+ }).changed;
250
+ }
251
+ /**
252
+ * Store a key the exchange just minted on the profile of its site, in one
253
+ * `updateConfig`. FIRST STORED WINS: when the profile keeps a key for that
254
+ * `(hub, e-mail)` that ANOTHER command stored after this command's last read
255
+ * before its exchange (the re-read under the mint lock), that key is kept
256
+ * (the caller revokes its own). `held` lists the keys the profile held at
257
+ * that read: none of them is « first stored », so the entry is stored beside
258
+ * it, and the older of the two is a stale duplicate the next command revokes
259
+ * on its site (the same account signed in again: its newer key serves).
260
+ * Otherwise the entry is added; a profile not on disk is created with
261
+ * `baseUrl` and `site`, and made the default only when the tool had no
262
+ * profile at all. Either way an existing profile with no `baseUrl` takes this
263
+ * one, with `site` (a profile is never repointed), and one with a `baseUrl`
264
+ * takes `site` only when it holds none; nothing else is written. A profile
265
+ * with no site of its own (no `baseUrl`, and no `cloudUrl` to be at) that
266
+ * already holds a key (its own, a kept key, an old slot) answers
267
+ * `unknown_site` and is left as it is: keys of no known site are never handed
268
+ * to this one. `avoid` is a key never kept (the one a site just refused): it
269
+ * is dropped from the slot when it is still there. `lastHub`, the address of
270
+ * the hub the exchange went through in its normal form (`normalizeUrl`), is
271
+ * written on the profile of this site whichever key is kept (the exchange
272
+ * succeeded either way), and on no other.
273
+ */
274
+ export function storeHubKey(env, tool, profileName, entry, opts) {
275
+ let outcome = { kept: entry, ours: true };
276
+ const held = new Set((opts.held ?? []).map((k) => k.trim()));
277
+ updateConfig(env, tool, (config) => {
278
+ const first = Object.keys(config.profiles).length === 0;
279
+ const profile = config.profiles[profileName];
280
+ if (!profile) {
281
+ config.profiles[profileName] = {
282
+ baseUrl: opts.baseUrl,
283
+ ...(opts.site ? { site: opts.site } : {}),
284
+ hubKeys: [entry],
285
+ ...(opts.lastHub ? { lastHub: opts.lastHub } : {})
286
+ };
287
+ if (first)
288
+ config.activeProfile = profileName;
289
+ return;
290
+ }
291
+ const at = profileUrl(profile, opts.cloudUrl);
292
+ if (at !== undefined && !sameInstance(at, opts.baseUrl)) {
293
+ outcome = { elsewhere: at };
294
+ return;
295
+ }
296
+ if (at === undefined && keysOfProfile(profile).length > 0) {
297
+ outcome = { unknown_site: true };
298
+ return;
299
+ }
300
+ // First stored: another command's key, stored in this slot since this command's last read.
301
+ const there = newestKey(hubKeysOf(profile).filter((k) => k.apiKey !== opts.avoid && !held.has(k.apiKey.trim()) && sameSlot(k, entry)));
302
+ if (there) {
303
+ outcome = { kept: there, ours: there.apiKey === entry.apiKey };
304
+ }
305
+ else {
306
+ const keys = profile.hubKeys;
307
+ profile.hubKeys = [
308
+ ...(Array.isArray(keys) ? keys : []).filter((k) => !(isObject(k) && opts.avoid !== undefined && k.apiKey === opts.avoid)),
309
+ entry
310
+ ];
311
+ }
312
+ // A profile with no site of its own (and no key) takes this one: the next command then finds
313
+ // it at its site (and what a site-less profile remembered is no site's).
314
+ const founding = !text(profile.baseUrl);
315
+ if (founding)
316
+ profile.baseUrl = opts.baseUrl;
317
+ if (opts.site && (founding || profile.site === undefined))
318
+ profile.site = opts.site;
319
+ if (opts.lastHub)
320
+ profile.lastHub = opts.lastHub;
321
+ });
322
+ return outcome;
323
+ }
324
+ /**
325
+ * File a key the exchange minted, lost at the store (first stored wins), and
326
+ * could not revoke on its site: in its slot, UNDATED (`mintedAt: ''`, the
327
+ * oldest of the slot), so it is a stale duplicate that the next command on the
328
+ * profile revokes on its site, then forgets. One `updateConfig`, on a profile
329
+ * at that site only (`baseUrl`; one with no `baseUrl` is at `cloudUrl`).
330
+ * Answers whether the profile holds it now.
331
+ */
332
+ export function storeUnrevokedKey(env, tool, profileName, entry, opts) {
333
+ let filed = false;
334
+ updateConfig(env, tool, (config) => {
335
+ const profile = config.profiles[profileName];
336
+ const at = profile ? profileUrl(profile, opts.cloudUrl) : undefined;
337
+ if (!profile || at === undefined || !sameInstance(at, opts.baseUrl))
338
+ return;
339
+ filed = true;
340
+ if (hubKeysOf(profile).some((k) => k.apiKey === entry.apiKey))
341
+ return;
342
+ const keys = profile.hubKeys;
343
+ profile.hubKeys = [
344
+ ...(Array.isArray(keys) ? keys : []),
345
+ { ...entry, mintedAt: '' }
346
+ ];
347
+ });
348
+ return filed;
349
+ }
350
+ /** Remove from a profile every kept key (and old slot, and with `own` its own key) whose key is listed. */
351
+ function removeKeys(profile, apiKeys, own) {
352
+ const listed = (k) => {
353
+ const key = isObject(k) ? k.apiKey : undefined;
354
+ return typeof key === 'string' && (apiKeys.has(key) || apiKeys.has(key.trim()));
355
+ };
356
+ let removed = 0;
357
+ const keys = profile.hubKeys;
358
+ if (Array.isArray(keys)) {
359
+ const rest = keys.filter((k) => !listed(k));
360
+ removed += keys.length - rest.length;
361
+ if (rest.length === 0)
362
+ delete profile.hubKeys;
363
+ else if (rest.length !== keys.length)
364
+ profile.hubKeys = rest;
365
+ }
366
+ const slots = profile.connectKeys;
367
+ if (isObject(slots)) {
368
+ const entries = Object.entries(slots);
369
+ const rest = entries.filter(([, e]) => !listed(e));
370
+ removed += entries.length - rest.length;
371
+ if (rest.length === 0)
372
+ delete profile.connectKeys;
373
+ else if (rest.length !== entries.length) {
374
+ profile.connectKeys = Object.fromEntries(rest);
375
+ }
376
+ }
377
+ if (own && listed({ apiKey: profile.apiKey })) {
378
+ delete profile.apiKey;
379
+ removed += 1;
380
+ }
381
+ return removed;
382
+ }
383
+ /**
384
+ * COMPARE-AND-EVICT, after a site refused a kept key: removes the kept entry
385
+ * (or old slot) whose key IS `apiKey`, in one `updateConfig`; another key in
386
+ * the same slot (another command already replaced it) is left in place. The
387
+ * profile's own key is never touched. With `remember` (the refused key's hub,
388
+ * its address in its normal form, `normalizeUrl`), the same write gives the
389
+ * profile that hub as its `lastHub`
390
+ * when it is at `remember.site` (one with no `baseUrl` is at `cloudUrl`) and
391
+ * holds none of its own (a profile from before the field): the kept key that
392
+ * said which hub goes, the hub stays remembered. Answers whether a key was
393
+ * removed.
394
+ */
395
+ export function evictKey(env, tool, profileName, apiKey, remember) {
396
+ if (!loadConfig(env, tool).profiles[profileName])
397
+ return false;
398
+ let removed = 0;
399
+ updateConfig(env, tool, (config) => {
400
+ const profile = config.profiles[profileName];
401
+ if (!profile)
402
+ return;
403
+ removed = removeKeys(profile, new Set([apiKey]), false);
404
+ const at = remember ? profileUrl(profile, remember.cloudUrl) : undefined;
405
+ if (remember && at !== undefined && sameInstance(at, remember.site) && !text(profile.lastHub)) {
406
+ profile.lastHub = remember.lastHub;
407
+ }
408
+ });
409
+ return removed > 0;
410
+ }
411
+ /**
412
+ * Every key a profile holds, each once: its own key, its kept keys, its old
413
+ * slots. The list a logout or a profile removal revokes on the profile's own
414
+ * site; never printed, redacted or not.
415
+ */
416
+ export function keysOfProfile(profile) {
417
+ if (!profile)
418
+ return [];
419
+ const out = [];
420
+ const seen = new Set();
421
+ const add = (key) => {
422
+ const apiKey = key.apiKey.trim();
423
+ if (seen.has(apiKey))
424
+ return;
425
+ seen.add(apiKey);
426
+ out.push({ ...key, apiKey });
427
+ };
428
+ const own = text(profile.apiKey);
429
+ if (own)
430
+ add({ apiKey: own, kind: 'own' });
431
+ for (const k of hubKeysOf(profile))
432
+ add({ apiKey: k.apiKey, kind: 'kept', hub: k.hub, email: k.email });
433
+ for (const [, entry] of oldSlotsOf(profile)) {
434
+ const email = text(entry.email);
435
+ add({ apiKey: entry.apiKey, kind: 'old', ...(email ? { email } : {}) });
436
+ }
437
+ return out;
438
+ }
439
+ /**
440
+ * The one rule of every revoke (R2): a key is revoked on its site only when
441
+ * no other profile AT THAT SAME SITE still holds it; otherwise it is
442
+ * forgotten on this profile only, and a line says so. This answers which
443
+ * other profile holds what: each key (trimmed) that another profile of
444
+ * `config` holds (`keysOfProfile`: its own key, its kept keys, its old slots)
445
+ * mapped to the first such profile's name in the file's order, counting only
446
+ * the profiles whose site is the same instance as `site`, the two compared in
447
+ * `normalizeUrl`'s one form (a profile with no `baseUrl` is at `cloudUrl`; one
448
+ * with no site at all counts for no site). A profile at another site never
449
+ * counts: it can never use the key, its commands go to its own site, so
450
+ * counting it would leave the key live where no profile uses it (verifier
451
+ * round 4, finding 3). A key matches only exactly. Pure: nothing is read or
452
+ * written.
453
+ */
454
+ export function keysHeldElsewhere(config, profileName, site, cloudUrl) {
455
+ const held = new Map();
456
+ for (const [name, profile] of Object.entries(config.profiles)) {
457
+ const at = profileUrl(profile, cloudUrl);
458
+ if (name === profileName || at === undefined || !sameInstance(at, site))
459
+ continue;
460
+ for (const key of keysOfProfile(profile))
461
+ if (!held.has(key.apiKey))
462
+ held.set(key.apiKey, name);
463
+ }
464
+ return held;
465
+ }
466
+ /**
467
+ * Forget keys of a profile, COMPARE-AND-REMOVE, in one `updateConfig`: each
468
+ * kept key, old slot, and (when listed) the profile's own key whose key is
469
+ * one of `apiKeys` is removed; whatever another command added meanwhile
470
+ * stays. Revoke first, with no lock held, then forget. Answers how many
471
+ * entries were removed; nothing is written when none was.
472
+ */
473
+ export function forgetKeys(env, tool, profileName, apiKeys) {
474
+ if (apiKeys.length === 0 || !loadConfig(env, tool).profiles[profileName])
475
+ return 0;
476
+ let removed = 0;
477
+ updateConfig(env, tool, (config) => {
478
+ const profile = config.profiles[profileName];
479
+ if (profile)
480
+ removed = removeKeys(profile, new Set(apiKeys.map((k) => k.trim())), true);
481
+ });
482
+ return removed;
483
+ }
484
+ //# sourceMappingURL=kept-keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kept-keys.js","sourceRoot":"","sources":["../src/kept-keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,+FAA+F;AAC/F,MAAM,UAAU,IAAI,CAAC,KAAc;IACjC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,C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AAE,OAAO,CAAC,CAAC;IACnF,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,YAAY,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE;QACjC,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAC7C,IAAI,OAAO;YAAE,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1F,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/dist/lock.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * A synchronous, re-entrant, cross-process file lock: the guard every
3
+ * read-modify-write of a config file holds (`updateConfig`), so two commands
4
+ * that both add something both keep it.
5
+ *
6
+ * The lock is a file created exclusively beside the one it guards
7
+ * (`<file>.lock`, 0600) and holding `{ pid, host, token, at }`. A dead
8
+ * holder's lock is taken over instead of waited on: its pid is gone on this
9
+ * host, it is older than `staleMs`, or it is empty or partial (its holder
10
+ * died between creating and writing it) and older than `emptyStaleMs`. A
11
+ * live holder is waited on with a short synchronous back-off up to
12
+ * `timeoutMs`, then the wait fails with a `CliConfigError` naming the holder
13
+ * and the lock file. Release removes the lock only while it still holds this
14
+ * holder's token.
15
+ *
16
+ * A lock is judged on ONE file: a look opens it and takes its identity
17
+ * (device, inode, mtime) and its bytes from that one descriptor, so a lock
18
+ * released and created again between two calls is never judged on the old
19
+ * holder's pid and the new file's age. The takers of one dead lock take
20
+ * turns through markers named for that lock and their turn
21
+ * (`<lockPath>.break.<dev>-<ino>.<n>`, the same holder shape): the taker
22
+ * that creates the marker of its turn looks at the lock again and moves it
23
+ * aside only while it is still the very file it judged, still stale; the
24
+ * moved file is removed only when it is that file, and any other is put
25
+ * back. A live taker's marker (younger than 10 s) is waited on like any
26
+ * holder; a dead taker's is skipped, never moved, and the next turn taken.
27
+ * No taker ever moves, links or removes a marker it did not create, and a
28
+ * marker of another lock never blocks this one. What take-overs leave beside
29
+ * the lock is removed by a later holder once it is older than `staleMs`,
30
+ * never sooner.
31
+ *
32
+ * `withFileLockAsync` is the same lock file protocol for work that spans the
33
+ * network (the single-flight mint of a kept key): its waits are awaited
34
+ * instead of blocking the thread, and it is not re-entrant.
35
+ */
36
+ export interface FileLockOptions {
37
+ /** How long a live holder is waited on before the wait fails. Default 10 000 ms. */
38
+ timeoutMs?: number;
39
+ /** A lock older than this is a dead holder's, whoever it names. Default 30 000 ms. */
40
+ staleMs?: number;
41
+ /** An empty or partial lock older than this is a dead holder's. Default 2 000 ms. */
42
+ emptyStaleMs?: number;
43
+ }
44
+ /** Block this thread for `ms` milliseconds: the waits of a synchronous API. */
45
+ export declare function sleepSync(ms: number): void;
46
+ /** The `code` of a Node system error (`ENOENT`, `EEXIST`, …), if it has one. */
47
+ export declare function errorCode(e: unknown): string | undefined;
48
+ /**
49
+ * Run `fn` holding the lock file `lockPath`, created when free, waited on
50
+ * while a live holder has it, taken over when its holder is dead, and
51
+ * released when `fn` returns or throws. Re-entrant within one process: a
52
+ * nested call on a path this process holds runs `fn` at once. `fn` is
53
+ * synchronous; the lock is released as soon as it returns.
54
+ */
55
+ export declare function withFileLock<T>(lockPath: string, fn: () => T, opts?: FileLockOptions): T;
56
+ /**
57
+ * Run the asynchronous `fn` holding the lock file `lockPath`: the protocol of
58
+ * `withFileLock` (created when free, waited on while a live holder has it,
59
+ * taken over when its holder is dead, released by token when `fn` settles),
60
+ * with the waits awaited, so the lock may span network calls. NOT re-entrant:
61
+ * two calls of one process on one path take turns like two processes, and a
62
+ * nested call on a path this call holds waits for itself until `timeoutMs`.
63
+ */
64
+ export declare function withFileLockAsync<T>(lockPath: string, fn: () => Promise<T>, opts?: FileLockOptions): Promise<T>;
65
+ //# sourceMappingURL=lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,MAAM,WAAW,eAAe;IAC9B,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sFAAsF;IACtF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qFAAqF;IACrF,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAoCD,+EAA+E;AAC/E,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAE1C;AAED,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAGxD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,IAAI,GAAE,eAAoB,GAAG,CAAC,CAmB5F;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,CAAC,EACvC,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,IAAI,GAAE,eAAoB,GACzB,OAAO,CAAC,CAAC,CAAC,CAeZ"}