@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
package/src/config.ts CHANGED
@@ -1,5 +1,21 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
1
+ import { randomBytes } from 'node:crypto';
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ fsyncSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ openSync,
10
+ readFileSync,
11
+ realpathSync,
12
+ renameSync,
13
+ rmSync,
14
+ writeFileSync
15
+ } from 'node:fs';
16
+ import { basename, dirname, join } from 'node:path';
17
+ import { errorCode, sleepSync, withFileLock } from './lock.js';
18
+ import { CliUsageError } from './resolve.js';
3
19
 
4
20
  /**
5
21
  * The shared Antasphere CLI config home: `$XDG_CONFIG_HOME/antasphere/`
@@ -17,34 +33,60 @@ import { dirname, join } from 'node:path';
17
33
  * (e.g. tools/slideless.json)
18
34
  *
19
35
  * Each file holds one tool's `{ activeProfile?, profiles }`. A PROFILE IS AN
20
- * INSTANCE: it names the tool instance it talks to (`baseUrl`; absent = the
21
- * tool's cloud URL) and carries the credentials for that instance, either
22
- * the tool's own key (`apiKey`, the tool's login) or the keys the hub
23
- * exchange minted (`connectKeys`, one per hub profile). Profiles are named
24
- * for their host by default (`cloud` for the cloud instance,
25
- * `share.antasphere.com`, `localhost:3400`); the person may rename them and
26
- * chooses the active one with `<tool> use`. The hub profile additionally
27
- * carries `workspaceId`, the default organization at login (informational;
28
- * the hub's server-side default is what applies).
36
+ * INSTANCE (a site): it names the site it talks to (`baseUrl`; absent = the
37
+ * tool's cloud URL), remembers what that site last said of itself (`site`),
38
+ * and carries the credentials for it: the tool's own key (`apiKey`, the
39
+ * tool's login) and the KEPT KEYS the hub exchange minted (`hubKeys`, one
40
+ * per hub and account; `connectKeys` is their old shape, moved once), with
41
+ * the address of the hub its last exchange went through, in its normal form
42
+ * (`normalizeUrl`): `lastHub`. Profiles are named for their host by default
43
+ * (`cloud` for the cloud site, `share.example.com`, `localhost:3400`); the
44
+ * person may rename them and chooses the default with `<tool> use`. In the
45
+ * hub's own file, an entry
46
+ * that holds a key is a LOGIN (`listLogins`), which additionally carries
47
+ * `workspaceId`, the default organization at login (informational; the
48
+ * hub's server-side default is what applies).
29
49
  *
30
50
  * Files store API keys, so directories are created 0700 and files kept 0600
31
51
  * on every write. All I/O is synchronous and env-injected (no process.env
32
52
  * reads) so tests can point the whole config world at a temp dir via
33
53
  * XDG_CONFIG_HOME.
54
+ *
55
+ * Many commands share one file (agent sessions side by side on one
56
+ * machine), so a file is never left half written and never overwritten from
57
+ * a stale copy: a write goes to a temporary file in the same directory,
58
+ * renamed over the real one; every read-modify-write is one `updateConfig`,
59
+ * holding `<file>.lock` from its read to its rename; a file that exists and
60
+ * does not parse is a `CliConfigError` naming it, never an empty config; and
61
+ * nothing is written when nothing changed.
34
62
  */
35
63
 
36
64
  export type CliEnv = Record<string, string | undefined>;
37
65
 
38
66
  /**
39
- * A tool-local key minted by the cross-tool connect exchange (binding
40
- * patterns §7), cached on the profile of the instance it was minted for,
41
- * under the HUB PROFILE whose `antasphere login` credential minted it. The
42
- * key is USER-scoped (hub ADR 014): one key serves every org — the org is a
43
- * per-request parameter, never part of the credential or of this cache's
44
- * slot. Every field beyond the key itself is informational.
67
+ * A config file this package will not read or write: it does not parse, it
68
+ * cannot be read, or another command holds its lock and never lets go. The
69
+ * message names the file and what to do; nothing on disk was changed. A
70
+ * `CliUsageError`, so a runner prints it and exits 1.
71
+ */
72
+ export class CliConfigError extends CliUsageError {
73
+ constructor(message: string) {
74
+ super(message, { exitCode: 1 });
75
+ this.name = 'CliConfigError';
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The OLD shape of a kept key (cli-core 0.3 to 0.6): a tool-local key the
81
+ * hub exchange minted, filed in `connectKeys` under the NAME of the hub
82
+ * login that minted it. A name strands its key when the login is renamed or
83
+ * re-created, so the first command that resolves a credential on the
84
+ * profile moves each such slot once into `hubKeys` (its login still in
85
+ * place with the same address), or revokes it on the profile's own site and
86
+ * forgets it. Nothing writes this shape any more.
45
87
  */
46
88
  export interface CliConnectKey {
47
- /** Full tool-local API key (`slk_`-style) — shown once at mint, cached here. */
89
+ /** Full tool-local API key (`slk_`-style). */
48
90
  apiKey: string;
49
91
  /** The signed-in account's email at mint. */
50
92
  email?: string;
@@ -52,6 +94,45 @@ export interface CliConnectKey {
52
94
  mintedAt?: string;
53
95
  }
54
96
 
97
+ /**
98
+ * What a site said of itself in its unauthenticated discovery
99
+ * (`GET /api/v1/instance`), remembered on its profile so a command with a
100
+ * kept key costs zero network: read again on every exchange, on `login`, on
101
+ * `profiles --check`, and once a day before a kept key is served.
102
+ */
103
+ export interface CliSiteFacts {
104
+ /** The Antasphere hub the site names (`auth.hub`, `normalizeUrl`'d); null = it names none. */
105
+ hub: string | null;
106
+ /** Whether it signs in through an Antasphere hub (the probe's `cloud`). */
107
+ federated: boolean;
108
+ /** Its discovery `name`. */
109
+ name: string | null;
110
+ /** The CLI version it announces (discovery `cli.version`). */
111
+ cliVersion: string | null;
112
+ /** ISO time these facts were read. */
113
+ seenAt: string;
114
+ }
115
+
116
+ /**
117
+ * A KEPT KEY: a tool-local key the hub exchange minted for the profile's
118
+ * site, filed by the hub's address and the account's e-mail, never by a
119
+ * login's name, so renaming a login or signing out and in again strands
120
+ * nothing. USER-scoped (hub ADR 014): one key serves every org. A profile
121
+ * holds one per `(hub, e-mail)` (the hub compared by `sameInstance`, the
122
+ * e-mail case-folded); a second one for the same pair is a key waiting for
123
+ * its revoke, never served.
124
+ */
125
+ export interface CliHubKey {
126
+ /** The hub whose login minted it, `normalizeUrl`'d. */
127
+ hub: string;
128
+ /** The account's e-mail, as the hub answered it at mint. */
129
+ email: string;
130
+ /** Full tool-local API key (`slk_`-style). */
131
+ apiKey: string;
132
+ /** ISO time of the exchange that minted it. */
133
+ mintedAt: string;
134
+ }
135
+
55
136
  export interface CliProfile {
56
137
  /** `<prefix>_...` API key for this profile (the tool's own login). */
57
138
  apiKey?: string;
@@ -64,10 +145,21 @@ export interface CliProfile {
64
145
  * command). Tool profiles from a tool's own login may carry the
65
146
  * workspace that login bound. */
66
147
  workspaceId?: string;
67
- /** Tool profiles only: exchange-minted USER-scoped keys, ONE per hub
68
- * profile — the (tool profile, hub profile) cache of the cross-tool
69
- * connect flow. Org-independent: a cached key serves every org. */
148
+ /** Tool profiles only: what the site last said of itself. */
149
+ site?: CliSiteFacts;
150
+ /** Tool profiles only: the kept keys, one per (hub, e-mail). */
151
+ hubKeys?: CliHubKey[];
152
+ /** Tool profiles only: kept keys of the OLD shape, filed by a login's
153
+ * name; moved once into `hubKeys` by the first command that resolves a
154
+ * credential on the profile. */
70
155
  connectKeys?: Record<string, CliConnectKey>;
156
+ /** Tool profiles only: the address of the hub the profile's last successful
157
+ * exchange went through, in its normal form (`normalizeUrl`, its path
158
+ * kept; no key, no e-mail), written by every exchange
159
+ * with the key it minted. For a site that names no hub, the hub to sign in
160
+ * at again while a login is in place there. A value that is not a string
161
+ * is ignored. */
162
+ lastHub?: string;
71
163
  }
72
164
 
73
165
  export interface CliConfig {
@@ -98,7 +190,14 @@ export function configPath(env: CliEnv, tool: string): string | null {
98
190
 
99
191
  const EMPTY: CliConfig = { profiles: {} };
100
192
 
101
- /** Tolerant parse (shared with the migrator): corrupt or foreign shapes → empty. */
193
+ const NO_HOME =
194
+ 'Cannot locate a config directory — set HOME or XDG_CONFIG_HOME, or pass --api-key/--api-url explicitly.';
195
+
196
+ /**
197
+ * Tolerant parse, kept for foreign files (the legacy migrator reads a
198
+ * pre-cli-core file with it): corrupt or foreign shapes → empty. A tool's
199
+ * own file is read strictly by `loadConfig`.
200
+ */
102
201
  export function parseConfig(raw: string): CliConfig {
103
202
  try {
104
203
  const parsed = JSON.parse(raw) as Partial<CliConfig>;
@@ -112,166 +211,212 @@ export function parseConfig(raw: string): CliConfig {
112
211
  }
113
212
  }
114
213
 
115
- /** Load a tool's config; a missing/unreadable/corrupt file is an empty config. */
116
- export function loadConfig(env: CliEnv, tool: string): CliConfig {
117
- const path = configPath(env, tool);
118
- if (!path || !existsSync(path)) return { ...EMPTY, profiles: {} };
119
- try {
120
- return parseConfig(readFileSync(path, 'utf8'));
121
- } catch {
122
- return { ...EMPTY, profiles: {} };
123
- }
124
- }
214
+ /** What one read of a config file found: its config, no file, or why it is refused. */
215
+ type ConfigRead = { config: CliConfig } | { missing: true } | { invalid: string };
125
216
 
126
- /** Persist a tool's config (0700 dirs / 0600 file). Throws when no home is known. */
127
- export function saveConfig(env: CliEnv, tool: string, config: CliConfig): string {
128
- const path = configPath(env, tool);
129
- if (!path) {
130
- throw new Error(
131
- 'Cannot locate a config directory — set HOME or XDG_CONFIG_HOME, or pass --api-key/--api-url explicitly.'
132
- );
133
- }
134
- const dir = dirname(path);
135
- mkdirSync(dir, { recursive: true, mode: 0o700 });
136
- // mkdir's mode only applies on creation — re-assert on every write, on
137
- // every directory level we own (tools/ AND the antasphere home itself).
138
- chmodSync(dir, 0o700);
139
- const home = dirname(configPath(env, HUB_TOOL) as string);
140
- if (dir !== home) chmodSync(home, 0o700);
141
- writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
142
- chmodSync(path, 0o600);
143
- return path;
217
+ function isObject(value: unknown): value is Record<string, unknown> {
218
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
144
219
  }
145
220
 
146
- /** Delete a tool's config file (config clear). No-op when absent. */
147
- export function clearConfig(env: CliEnv, tool: string): void {
148
- const path = configPath(env, tool);
149
- if (path && existsSync(path)) rmSync(path);
221
+ /**
222
+ * Why a parsed config file is refused, or undefined when it reads as one: a
223
+ * JSON object whose `profiles`, when present, is an object of objects. The
224
+ * checks of the strict loader, and of `updateConfig` before it writes.
225
+ */
226
+ function invalidReason(parsed: unknown): string | undefined {
227
+ if (!isObject(parsed)) return 'its top level is not an object';
228
+ const profiles = parsed.profiles === undefined ? {} : parsed.profiles;
229
+ if (!isObject(profiles)) return '"profiles" is not an object';
230
+ for (const [name, profile] of Object.entries(profiles)) {
231
+ if (!isObject(profile)) return `profile "${name}" is not an object`;
232
+ }
233
+ return undefined;
150
234
  }
151
235
 
152
- /** `ant_abcd1234_…` → `ant_abcd1234_…c3f9` — safe for terminals and logs. */
153
- export function redactKey(key: string): string {
154
- if (key.length <= 16) return '****';
155
- return `${key.slice(0, 13)}…${key.slice(-4)}`;
236
+ function readConfigFile(path: string): ConfigRead {
237
+ let raw: string;
238
+ try {
239
+ raw = readFileSync(path, 'utf8');
240
+ } catch (e) {
241
+ const code = errorCode(e);
242
+ if (code === 'ENOENT') return { missing: true };
243
+ throw new CliConfigError(
244
+ `The config file ${path} cannot be read (${code ?? 'unknown error'}). Nothing was changed; ` +
245
+ 'fix it or move it aside, then retry.'
246
+ );
247
+ }
248
+ let parsed: unknown;
249
+ try {
250
+ parsed = JSON.parse(raw);
251
+ } catch {
252
+ return { invalid: 'it is not JSON' };
253
+ }
254
+ const invalid = invalidReason(parsed);
255
+ if (invalid !== undefined) return { invalid };
256
+ // An object of objects, `invalidReason` says so.
257
+ const file = parsed as Record<string, unknown>;
258
+ const profiles = file.profiles === undefined ? {} : file.profiles;
259
+ // The two known keys in the file's own order (a non-string activeProfile
260
+ // and unknown keys are dropped), so a file this package wrote serializes
261
+ // back to its very bytes: a change that changes nothing writes nothing.
262
+ const known: { activeProfile?: string; profiles?: Record<string, CliProfile> } = {};
263
+ for (const key of Object.keys(file)) {
264
+ if (key === 'profiles') known.profiles = profiles as Record<string, CliProfile>;
265
+ else if (key === 'activeProfile' && typeof file.activeProfile === 'string') {
266
+ known.activeProfile = file.activeProfile;
267
+ }
268
+ }
269
+ return { config: { ...known, profiles: known.profiles ?? {} } };
156
270
  }
157
271
 
158
272
  /**
159
- * The cached user-scoped connect key a HUB PROFILE minted for this tool
160
- * profile, if any. The slot is the hub profile NAME — stable across runs
161
- * and orgs (the key identifies the user; selecting a different org between
162
- * runs never misses the cache).
273
+ * Load a tool's config. A missing file (or no config home) is an empty
274
+ * config; a file that exists must be a JSON object whose `profiles`, when
275
+ * present, is an object of objects, else it is read twice more over 150 ms
276
+ * (an older CLI may be rewriting it in place) and then throws a
277
+ * `CliConfigError` naming it. Reading takes no lock: a write is a rename.
163
278
  */
164
- export function lookupConnectKey(
165
- profile: CliProfile | undefined,
166
- hubProfileName: string
167
- ): string | undefined {
168
- return profile?.connectKeys?.[hubProfileName]?.apiKey;
279
+ export function loadConfig(env: CliEnv, tool: string): CliConfig {
280
+ const path = configPath(env, tool);
281
+ if (!path) return { ...EMPTY, profiles: {} };
282
+ let read = readConfigFile(path);
283
+ for (const pause of [50, 100]) {
284
+ if (!('invalid' in read)) break;
285
+ sleepSync(pause);
286
+ read = readConfigFile(path);
287
+ }
288
+ if ('invalid' in read) {
289
+ throw new CliConfigError(
290
+ `The config file ${path} is not valid: ${read.invalid}. Nothing was changed; fix it or move it aside, ` +
291
+ 'then retry.'
292
+ );
293
+ }
294
+ return 'missing' in read ? { ...EMPTY, profiles: {} } : read.config;
169
295
  }
170
296
 
171
- /**
172
- * The cached connect key the connect-on-demand flow may SERVE: the slot's
173
- * key, only when the hub profile carries an e-mail address, the cached
174
- * entry carries one too, and the two are the same address (trimmed,
175
- * case-insensitive). A key is the credential of the person who minted it
176
- * (PRDCT-3032), so the cache serves only that person; a hub profile with no
177
- * address is someone unknown, and an entry with no address was minted by
178
- * someone unknown: neither is served (PRDCT-3046 F7). `lookupConnectKey`
179
- * stays the plain slot read.
180
- */
181
- export function cachedConnectKey(
182
- profile: CliProfile | undefined,
183
- hubProfileName: string,
184
- hubEmail: string | undefined
185
- ): string | undefined {
186
- const entry = profile?.connectKeys?.[hubProfileName];
187
- const hub = hubEmail?.trim().toLowerCase();
188
- const minted = entry?.email?.trim().toLowerCase();
189
- if (!hub || !minted || hub !== minted) return undefined;
190
- return entry?.apiKey;
297
+ /** Rename over the target, retried for up to 1 s while Windows (a reader holding the file) refuses it. */
298
+ function renameOver(from: string, to: string): void {
299
+ const deadline = Date.now() + 1_000;
300
+ for (;;) {
301
+ try {
302
+ renameSync(from, to);
303
+ return;
304
+ } catch (e) {
305
+ const code = errorCode(e);
306
+ if ((code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') || Date.now() >= deadline) throw e;
307
+ sleepSync(10);
308
+ }
309
+ }
191
310
  }
192
311
 
193
- /** How a profile signs in, for a `profiles`-style listing. */
194
- export type ProfileCredential = 'key' | 'hub' | 'none';
195
-
196
312
  /**
197
- * What a profile signs in with, in the order the tool resolves it: its own
198
- * `apiKey` (`key`, the tool's login), else a key the hub exchange minted
199
- * (`hub`: under the named hub profile, or under any when none is named),
200
- * else `none`. A listing can then say which profiles ride the hub login.
313
+ * Write a config file's bytes (`data`): nothing when it already holds them
314
+ * (`false`); otherwise a temporary file beside the target (0600, synced)
315
+ * renamed over it, so a reader sees the old file or the new one, never half
316
+ * of one (`true`). A symlinked file stays a symlink: its target is replaced.
201
317
  */
202
- export function profileCredential(
203
- profile: CliProfile | undefined,
204
- hubProfileName?: string
205
- ): ProfileCredential {
206
- if (!profile) return 'none';
207
- if (profile.apiKey) return 'key';
208
- const slots = profile.connectKeys ?? {};
209
- const connected = hubProfileName
210
- ? Boolean(slots[hubProfileName]?.apiKey)
211
- : Object.values(slots).some((k) => k.apiKey);
212
- return connected ? 'hub' : 'none';
213
- }
318
+ function writeConfigFile(path: string, data: string, home: string): boolean {
319
+ let current: Buffer | undefined;
320
+ try {
321
+ current = readFileSync(path);
322
+ } catch (e) {
323
+ if (errorCode(e) !== 'ENOENT') throw e;
324
+ }
325
+ if (current?.equals(Buffer.from(data))) return false;
214
326
 
215
- export interface StoreConnectKeyOptions {
216
- /**
217
- * The instance the key was minted for. Written on the profile when it is
218
- * created here or has no `baseUrl` of its own (a blank one counts as
219
- * none); a `baseUrl` that is there is never overwritten (a profile is
220
- * never repointed).
221
- */
222
- baseUrl?: string;
327
+ const dir = dirname(path);
328
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
329
+ // mkdir's mode only applies on creation — re-assert on every write, on
330
+ // every directory level we own (tools/ AND the antasphere home itself).
331
+ chmodSync(dir, 0o700);
332
+ if (dir !== home) chmodSync(home, 0o700);
333
+
334
+ let symlink = false;
335
+ try {
336
+ symlink = lstatSync(path).isSymbolicLink();
337
+ } catch (e) {
338
+ if (errorCode(e) !== 'ENOENT') throw e;
339
+ }
340
+ const target = symlink ? realpathSync(path) : path;
341
+ const tmp = join(
342
+ dirname(target),
343
+ `.${basename(target)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
344
+ );
345
+ const fd = openSync(tmp, 'wx', 0o600);
346
+ let open = true;
347
+ try {
348
+ writeFileSync(fd, data);
349
+ fsyncSync(fd);
350
+ closeSync(fd);
351
+ open = false;
352
+ chmodSync(tmp, 0o600);
353
+ renameOver(tmp, target);
354
+ } catch (e) {
355
+ if (open) {
356
+ try {
357
+ closeSync(fd);
358
+ } catch {
359
+ // The write's own error is the one to report.
360
+ }
361
+ }
362
+ rmSync(tmp, { force: true });
363
+ throw e;
364
+ }
365
+ return true;
223
366
  }
224
367
 
225
368
  /**
226
- * Cache an exchange-minted tool key on the SELECTED profile under the hub
227
- * profile's name. A profile not on disk yet is created (with `baseUrl` when
228
- * given) and made active only when the tool had NO profile at all: the
229
- * first cloud connect on a fresh machine. An existing profile is never
230
- * renamed, repointed or made active; every other field is preserved.
231
- * Returns the file written.
369
+ * The one way to change a tool's config: a read-modify-write holding
370
+ * `<file>.lock` for its whole span, so two commands that both change
371
+ * something both keep it. `mutate` gets a draft of the file as it is now
372
+ * (strict `loadConfig`) and changes it in place, or returns the config to
373
+ * write; nothing is written when the result is the file's current bytes.
374
+ * Answers the file, whether it changed, and the config it now holds. Throws
375
+ * when no config home is known, and a `CliConfigError` when the file does
376
+ * not parse, when its lock is never released, or when the config to write is
377
+ * one the strict loader would refuse (nothing is written then).
232
378
  */
233
- export function storeConnectKey(
379
+ export function updateConfig(
234
380
  env: CliEnv,
235
381
  tool: string,
236
- profileName: string,
237
- hubProfileName: string,
238
- entry: CliConnectKey,
239
- opts: StoreConnectKeyOptions = {}
240
- ): string {
241
- const config = loadConfig(env, tool);
242
- const first = Object.keys(config.profiles).length === 0;
243
- const profile = config.profiles[profileName] ?? {};
244
- config.profiles[profileName] = {
245
- ...profile,
246
- ...(!profile.baseUrl?.trim() && opts.baseUrl ? { baseUrl: opts.baseUrl } : {}),
247
- connectKeys: { ...profile.connectKeys, [hubProfileName]: entry }
248
- };
249
- if (first) config.activeProfile = profileName;
250
- return saveConfig(env, tool, config);
382
+ mutate: (config: CliConfig) => CliConfig | void
383
+ ): { path: string; changed: boolean; config: CliConfig } {
384
+ const path = configPath(env, tool);
385
+ if (!path) throw new Error(NO_HOME);
386
+ const home = dirname(configPath(env, HUB_TOOL) as string);
387
+ return withFileLock(`${path}.lock`, () => {
388
+ const draft = structuredClone(loadConfig(env, tool));
389
+ const config = mutate(draft) ?? draft;
390
+ const data = `${JSON.stringify(config, null, 2)}\n`;
391
+ // What is written is read back by the strict loader: never write a file it would refuse.
392
+ let invalid: string | undefined;
393
+ try {
394
+ invalid = invalidReason(JSON.parse(data));
395
+ } catch {
396
+ invalid = 'it is not JSON';
397
+ }
398
+ if (invalid !== undefined) {
399
+ throw new CliConfigError(
400
+ `refusing to write an invalid config: ${invalid}. Nothing was written to ${path}.`
401
+ );
402
+ }
403
+ return { path, changed: writeConfigFile(path, data, home), config };
404
+ });
405
+ }
406
+
407
+ /** Delete a tool's config file (config clear), under its lock. No-op when absent. */
408
+ export function clearConfig(env: CliEnv, tool: string): void {
409
+ const path = configPath(env, tool);
410
+ if (!path || !existsSync(path)) return;
411
+ withFileLock(`${path}.lock`, () => rmSync(path, { force: true }));
251
412
  }
252
413
 
253
414
  /**
254
- * Drop one hub profile's cached connect key from a profile (disconnect this
255
- * tool from the hub account, or evict a key the hub revoked). Returns
256
- * whether anything was removed; the tool's own `apiKey` is never touched —
257
- * it belongs to the tool's own login flow.
415
+ * `ant_abcd1234_…` → `ant_abcd1234_…c3f9`.
416
+ *
417
+ * @deprecated No listing prints any part of a key any more, redacted or not.
258
418
  */
259
- export function removeConnectKey(
260
- env: CliEnv,
261
- tool: string,
262
- profileName: string,
263
- hubProfileName: string
264
- ): boolean {
265
- const config = loadConfig(env, tool);
266
- const profile = config.profiles[profileName];
267
- if (!profile?.connectKeys || !(hubProfileName in profile.connectKeys)) return false;
268
- const { [hubProfileName]: _dropped, ...rest } = profile.connectKeys;
269
- if (Object.keys(rest).length === 0) {
270
- const { connectKeys: _empty, ...bare } = profile;
271
- config.profiles[profileName] = bare;
272
- } else {
273
- config.profiles[profileName] = { ...profile, connectKeys: rest };
274
- }
275
- saveConfig(env, tool, config);
276
- return true;
419
+ export function redactKey(key: string): string {
420
+ if (key.length <= 16) return '****';
421
+ return `${key.slice(0, 13)}…${key.slice(-4)}`;
277
422
  }