@agledger/cli 2.1.0 → 2.2.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 +64 -22
  2. package/SKILL.md +15 -14
  3. package/bin/run.js +2 -2
  4. package/dist/api-client.d.ts +7 -0
  5. package/dist/api-client.js +44 -8
  6. package/dist/base.d.ts +91 -22
  7. package/dist/base.js +76 -47
  8. package/dist/cli/command.d.ts +58 -0
  9. package/dist/cli/command.js +44 -0
  10. package/dist/cli/flags.d.ts +76 -0
  11. package/dist/cli/flags.js +12 -0
  12. package/dist/cli/help.d.ts +6 -0
  13. package/dist/cli/help.js +107 -0
  14. package/dist/cli/index.d.ts +3 -0
  15. package/dist/cli/index.js +3 -0
  16. package/dist/cli/main.d.ts +22 -0
  17. package/dist/cli/main.js +223 -0
  18. package/dist/cli/parse.d.ts +20 -0
  19. package/dist/cli/parse.js +138 -0
  20. package/dist/commands/api.d.ts +106 -18
  21. package/dist/commands/api.js +103 -12
  22. package/dist/commands/auth.d.ts +35 -6
  23. package/dist/commands/auth.js +1 -1
  24. package/dist/commands/config.d.ts +43 -8
  25. package/dist/commands/config.js +9 -8
  26. package/dist/commands/discover.d.ts +35 -6
  27. package/dist/commands/docs.d.ts +41 -7
  28. package/dist/commands/docs.js +4 -4
  29. package/dist/commands/help-json.d.ts +39 -7
  30. package/dist/commands/help-json.js +27 -45
  31. package/dist/commands/list-commands.d.ts +36 -7
  32. package/dist/commands/list-commands.js +2 -2
  33. package/dist/commands/login.d.ts +66 -10
  34. package/dist/commands/login.js +30 -9
  35. package/dist/commands/logout.d.ts +41 -7
  36. package/dist/commands/logout.js +8 -8
  37. package/dist/commands/verify.d.ts +97 -13
  38. package/dist/commands/verify.js +84 -27
  39. package/dist/oidc.d.ts +47 -0
  40. package/dist/oidc.js +162 -3
  41. package/dist/util/config.d.ts +16 -1
  42. package/dist/util/config.js +50 -14
  43. package/dist/util/field-parser.d.ts +3 -1
  44. package/dist/util/field-parser.js +11 -5
  45. package/package.json +9 -21
  46. package/dist/hooks/command-not-found.d.ts +0 -3
  47. package/dist/hooks/command-not-found.js +0 -63
  48. package/oclif.manifest.json +0 -872
@@ -1,7 +1,9 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
- import { Args, Flags } from '@oclif/core';
2
+ import { Args, Flags } from '../cli/index.js';
3
3
  import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, verifyAuditExport, normalizeFederationKey, } from '@agledger/verify-core';
4
4
  import { BaseCommand, ErrorCode, ExitCode } from '../base.js';
5
+ /** A --trust-anchor was given and the run did not anchor to it; the code `agledger-verify` gives. */
6
+ export const EXIT_NOT_ANCHORED = 3;
5
7
  /**
6
8
  * verify-core words a finding, note or failure for a library caller, so its
7
9
  * advice names options (`give distrustedKeys sha256:<hex>@<instant>`, `pin
@@ -21,6 +23,8 @@ const OPTION_FLAGS = [
21
23
  [/\bfederationKeys\[\d+\]\.history\b/g, '--federation-key-history'],
22
24
  [/\bfederationKeys\[\d+\]/g, '--federation-key'],
23
25
  [/\bfederationKeys\b/g, '--federation-key'],
26
+ [/\ballowAfterRetirement\b/g, '--allow-after-retirement'],
27
+ [/\bexpectedEntryCount\b/g, '--expected-entry-count'],
24
28
  ];
25
29
  /** One prose string from a result, its option names given as this command's flags. */
26
30
  export function flagWording(text) {
@@ -58,19 +62,18 @@ export function resultWithFlags(result) {
58
62
  export default class Verify extends BaseCommand {
59
63
  static description = 'Verify a record audit export offline (COSE_Sign1 envelope, RFC 9052; Ed25519 or ES256).';
60
64
  static examples = [
61
- '<%= config.bin %> verify audit-export.json --trust-anchor sha256:<64 hex>',
62
- '<%= config.bin %> verify audit-export.json',
63
- '<%= config.bin %> verify audit-export.json --keys vault-keys.json',
64
- '<%= config.bin %> verify audit-export.json --agent-keys agent-jwks.json',
65
- '<%= config.bin %> verify audit-export.json --federation-key hub-b=MCowBQYDK2VwAyEA...',
66
- '<%= config.bin %> verify audit-export.json --json',
67
- 'cat audit-export.json | <%= config.bin %> verify -',
65
+ 'agledger verify audit-export.json --trust-anchor sha256:<64 hex>',
66
+ 'agledger verify audit-export.json',
67
+ 'agledger verify audit-export.json --keys vault-keys.json',
68
+ 'agledger verify audit-export.json --agent-keys agent-jwks.json',
69
+ 'agledger verify audit-export.json --federation-key hub-b=MCowBQYDK2VwAyEA...',
70
+ 'agledger verify audit-export.json --trust-anchor sha256:<64 hex> --expected-entry-count 12',
71
+ 'agledger verify audit-export.json --json',
72
+ 'cat audit-export.json | agledger verify -',
68
73
  ];
69
- // FILE is required, but checked in run() rather than by oclif: oclif's own
70
- // missing-arg error tells the caller to put arguments before every
71
- // repeatable flag, which is not true of non-greedy ones, and lists hidden
72
- // flags with them.
73
- static usage = 'verify FILE [--trust-anchor <value>...] [--distrusted-key <value>...] [--keys <value>] [--agent-keys <value>] [--federation-key <value>...] [--require-key-id <value>] [--require-supplied-keys] [--json] [--quiet]';
74
+ // FILE is required, but checked in run() rather than by the parser, which
75
+ // would name the missing argument without the stdin form.
76
+ static usage = 'verify FILE [--trust-anchor <value>...] [--distrusted-key <value>...] [--keys <value>] [--agent-keys <value>] [--federation-key <value>...] [--federation-key-history <value>...] [--allow-after-retirement] [--expected-entry-count <value>] [--require-key-id <value>] [--require-supplied-keys] [--json] [--quiet]';
74
77
  static args = {
75
78
  file: Args.string({
76
79
  description: 'Path to the audit export JSON file (or "-" for stdin).',
@@ -122,7 +125,7 @@ export default class Verify extends BaseCommand {
122
125
  'or base64 of the raw 32 bytes the handshake registered). A receiving Server seals each peer message ' +
123
126
  'it accepts on the chain entry it writes (payload.wire), as the peer signed it. Every sealed message is ' +
124
127
  'held to its body hash and to its entry; one from a hub given here also has its signature re-verified ' +
125
- 'under that key, which proves what the peer asserted from this export alone. A failure is ' +
128
+ 'under that key, which checks what the peer asserted from this export alone. A failure is ' +
126
129
  'CHAIN_FEDERATION_WIRE_INVALID. Repeatable, once per peer; name a hub twice to pin a second key ' +
127
130
  'no succession links to the first: one its history lists linked: false, or one it does not list at all.',
128
131
  }),
@@ -133,8 +136,20 @@ export default class Verify extends BaseCommand {
133
136
  '(no auth). Needs a --federation-key for the same hub: every key the history links to that key through ' +
134
137
  'successions both keys signed is trusted inside its window, so entries sealed before the peer changed its ' +
135
138
  'federation key verify. Each message is placed by its signed wire.timestamp, never by the unsigned ' +
136
- 'createdAt: one signed under a key before the key\'s activation fails; one signed after its retirement is ' +
137
- 'reported as after retirement. Repeatable.',
139
+ 'createdAt, with 300 seconds allowed at each edge of the window: one signed under a key earlier than that ' +
140
+ 'before the key\'s activation fails, and so does one signed later than that after its retirement unless ' +
141
+ '--allow-after-retirement is given. Repeatable.',
142
+ }),
143
+ 'allow-after-retirement': Flags.boolean({
144
+ description: 'A sealed peer message signed under a key after that key\'s retirement fails CHAIN_FEDERATION_WIRE_INVALID ' +
145
+ 'by default. This flag accepts it and counts it as after retirement, for a peer that kept signing briefly ' +
146
+ 'after rotating because its process had not restarted.',
147
+ default: false,
148
+ }),
149
+ 'expected-entry-count': Flags.string({
150
+ description: 'The number of entries the export must hold, taken out of band (the record\'s entry count from the Server ' +
151
+ 'or an earlier export). The counts an export states about itself are unsigned, so a chain cut from the end ' +
152
+ 'with them deleted verifies; with this flag it fails CHAIN_POSITION_GAP.',
138
153
  }),
139
154
  'require-key-id': Flags.string({
140
155
  description: 'Require every entry to reference this keyId. Rejects otherwise-valid exports ' +
@@ -193,6 +208,14 @@ export default class Verify extends BaseCommand {
193
208
  }
194
209
  throw err;
195
210
  }
211
+ let expectedEntryCount;
212
+ const countFlag = flags['expected-entry-count'];
213
+ if (countFlag !== undefined) {
214
+ if (!/^\d+$/.test(countFlag) || !Number.isSafeInteger(Number(countFlag))) {
215
+ this.failWith(ErrorCode.INVALID_FIELD, `--expected-entry-count must be a non-negative integer (got ${countFlag})`, ExitCode.USAGE_ERROR, 'Pass the number of entries the record holds, as a whole number.');
216
+ }
217
+ expectedEntryCount = Number(countFlag);
218
+ }
196
219
  if (args.file === undefined) {
197
220
  this.failWith(ErrorCode.MISSING_INPUT, 'Missing the audit export to verify.', ExitCode.USAGE_ERROR, 'Pass the path to an audit-export JSON file, or `-` to read it from stdin, before or after the flags.');
198
221
  }
@@ -216,7 +239,7 @@ export default class Verify extends BaseCommand {
216
239
  // verify-core throws TypeError at the supplied-key boundary when the
217
240
  // file's shape is wrong (e.g. {keyId: 42}, [null], "...") or a key window
218
241
  // in it is not RFC 3339: valid JSON, a value refused. Catch it so the
219
- // CLI emits its structured-error envelope rather than oclif's raw
242
+ // CLI emits its structured-error envelope rather than a raw
220
243
  // exception trace; agents parsing stderr need {code, message, suggestion},
221
244
  // not a stack frame.
222
245
  let result;
@@ -228,6 +251,8 @@ export default class Verify extends BaseCommand {
228
251
  ...(trustAnchors.length > 0 ? { trustAnchors, distrustedKeys } : {}),
229
252
  agentKeys,
230
253
  federationKeys,
254
+ allowAfterRetirement: flags['allow-after-retirement'],
255
+ ...(expectedEntryCount !== undefined ? { expectedEntryCount } : {}),
231
256
  });
232
257
  }
233
258
  catch (err) {
@@ -248,10 +273,16 @@ export default class Verify extends BaseCommand {
248
273
  this.output({ verdict, ...rest });
249
274
  }
250
275
  else {
251
- this.renderHuman(result, agentKeys !== undefined, federationKeys !== undefined);
276
+ this.renderHuman(result, agentKeys !== undefined, federationKeys !== undefined, expectedEntryCount);
252
277
  }
253
- if (!result.valid)
278
+ // The exit codes of @agledger/verify and the Python agledger-verify: 1
279
+ // only for a failed verdict, and 3 when a pin was given and not met
280
+ // (nothing fails without it). This command makes no network call, so 3
281
+ // here never means an auth failure.
282
+ if (result.verdict === 'failed')
254
283
  this.exit(ExitCode.GENERAL_ERROR);
284
+ if (result.verdict === 'unanchored' && trustAnchors.length > 0)
285
+ this.exit(EXIT_NOT_ANCHORED);
255
286
  }
256
287
  /**
257
288
  * Accept the raw `GET /v1/verification-keys` response shape. That endpoint
@@ -320,7 +351,7 @@ export default class Verify extends BaseCommand {
320
351
  }
321
352
  const entry = out.find((k) => k.hubId === hubId && k.history === undefined) ?? out.find((k) => k.hubId === hubId);
322
353
  if (entry === undefined) {
323
- this.failWith(ErrorCode.INVALID_FIELD, `--federation-key-history ${path} is hub ${hubId}'s, and no --federation-key names that hub.`, ExitCode.USAGE_ERROR, 'Give the key you hold for it with --federation-key <hubId>=<key> (the signingPublicKey your peer row holds, or one its operator confirmed): the history is trusted only from a key you pinned.');
354
+ this.failWith(ErrorCode.INVALID_FIELD, `--federation-key-history ${path} is hub ${hubId}'s, and no --federation-key names that hub.`, ExitCode.USAGE_ERROR, 'Give the key you hold for it with --federation-key <hubId>=<key> (the signingPublicKey your peer record holds, or one its operator confirmed): the history is trusted only from a key you pinned.');
324
355
  }
325
356
  if (entry.history !== undefined)
326
357
  out.push({ hubId, publicKey: entry.publicKey, history: doc });
@@ -339,7 +370,7 @@ export default class Verify extends BaseCommand {
339
370
  ? entry.publicKeyJwk
340
371
  : entry);
341
372
  }
342
- renderHuman(result, agentKeysGiven, federationKeysGiven) {
373
+ renderHuman(result, agentKeysGiven, federationKeysGiven, expectedEntryCount) {
343
374
  if (this.isQuiet)
344
375
  return;
345
376
  const out = process.stdout;
@@ -351,17 +382,24 @@ export default class Verify extends BaseCommand {
351
382
  const verdict = result.verdict;
352
383
  const anchored = trust.status === 'walked';
353
384
  // The same headline words as @agledger/verify and the Python agledger-verify.
354
- const icon = verdict === 'failed' ? 'FAIL' : verdict === 'trusted' ? 'PASS' : 'VERIFIED, NOT ANCHORED';
385
+ const pinNotMet = verdict === 'unanchored' && !result.valid;
386
+ const icon = verdict === 'failed' ? 'FAIL' : verdict === 'trusted' ? 'PASS' : pinNotMet ? 'NOT ANCHORED' : 'VERIFIED, NOT ANCHORED';
355
387
  out.write(`${icon} Record: ${result.recordId}\n`);
356
388
  out.write(` Entries: ${result.verifiedEntries}/${result.totalEntries} verified\n`);
357
- if (verdict === 'unanchored') {
389
+ if (pinNotMet) {
390
+ out.write(' The --trust-anchor you gave reaches none of the signing keys here, so every signed entry reads as ' +
391
+ 'unanchored. Without the pin, nothing fails: this is the result for an export from another Server than ' +
392
+ 'the one pinned, and equally for one re-signed wholesale under keys of its own. NOT a trusted verdict. ' +
393
+ "Check that the pin is this Server's vault key.\n");
394
+ }
395
+ else if (verdict === 'unanchored') {
358
396
  out.write(trust.status === 'no_anchored_signature'
359
397
  ? ' Nothing failed, but this is NOT a trusted verdict: the --trust-anchor was walked, but no ' +
360
398
  'signature here verified under a key it anchors. An entry written before the install began ' +
361
- 'signing carries no signature, and proves nothing about who wrote it.\n'
399
+ 'signing carries no signature, and says nothing about who wrote it.\n'
362
400
  : ' Nothing failed, but this is NOT a trusted verdict: no --trust-anchor was given, so every ' +
363
- "signing key was taken on the word of the export itself, and a key written into the Server's " +
364
- 'database alone would verify. Ask the operator for the SPKI digest of a vault key (the ' +
401
+ "signing key was taken on the word of the export itself, and a key planted on the Server " +
402
+ 'alone would verify. Ask the operator for the SPKI digest of a vault key (the ' +
365
403
  'installer prints it; signing-key-digest.js derives it from any key) and re-run with ' +
366
404
  '--trust-anchor sha256:<hex>.\n');
367
405
  }
@@ -389,6 +427,7 @@ export default class Verify extends BaseCommand {
389
427
  // Agent signatures are checked only against keys the caller supplies, so
390
428
  // the lines below say exactly how many were, and the PASS line speaks for
391
429
  // the Server's signatures alone.
430
+ out.write(` ${entryCountLine(result.entryCount, result.totalEntries, expectedEntryCount)}\n`);
392
431
  const peerLine = peerMessagesLine(result.federationWire, federationKeysGiven);
393
432
  if (peerLine)
394
433
  out.write(` ${peerLine}\n`);
@@ -455,7 +494,7 @@ export function peerMessagesLine(wire, federationKeysGiven) {
455
494
  if (wire.present === 0)
456
495
  return null;
457
496
  const retired = wire.afterRetirement > 0
458
- ? ` ${wire.afterRetirement} of them signed by the peer under a key it had already retired: in order when the receiver's federation.peer_revoked row for the peer comes after them.`
497
+ ? ` ${wire.afterRetirement} of them signed by the peer under a key it had already retired, accepted because --allow-after-retirement was given: in order when the receiver's federation.peer_revoked entry for the peer comes after them.`
459
498
  : '';
460
499
  if (wire.present === wire.verified) {
461
500
  return `Peer messages: ${wire.verified}/${wire.present} sealed federation messages re-verified under --federation-key.${retired}`;
@@ -474,3 +513,21 @@ export function peerMessagesLine(wire, federationKeysGiven) {
474
513
  }
475
514
  return `Peer messages: ${parts.join('; ')}.${retired}`;
476
515
  }
516
+ /**
517
+ * What the export's entry count was held to. A chain cut from the end still
518
+ * verifies entry by entry, so the report names the stated count, if any, that
519
+ * stood behind the number of entries it verified.
520
+ */
521
+ export function entryCountLine(count, held, supplied) {
522
+ if (supplied !== undefined) {
523
+ return held === supplied
524
+ ? `Entry count: held to the ${supplied} given with --expected-entry-count.`
525
+ : `Entry count: ${held ?? 'the chain'} where --expected-entry-count gives ${supplied}.`;
526
+ }
527
+ if (count.expectedEntries !== null)
528
+ return `Entry count: held to the checkpoint at position ${count.expectedEntries}.`;
529
+ if (count.statedEntries !== null) {
530
+ return `Entry count: held to the ${count.statedEntries} the export states; it names no checkpoint for this record yet.`;
531
+ }
532
+ return "Entry count: the file's own; the export states no count and names no checkpoint, so a chain cut from the end would pass. Hold it to a count you took out of band with --expected-entry-count.";
533
+ }
package/dist/oidc.d.ts CHANGED
@@ -14,6 +14,8 @@ export declare const OIDC_ENV: {
14
14
  readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
15
15
  readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
16
16
  readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
17
+ /** A JWK Set file every cert exchange adds its public key to, for `agledger verify --agent-keys`. */
18
+ readonly AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE';
17
19
  };
18
20
  /**
19
21
  * Env vars naming an RFC 8693 delegation token, sent as `AGLedger-On-Behalf-Of`
@@ -46,6 +48,38 @@ export declare class OidcExchangeError extends Error {
46
48
  readonly origin: string;
47
49
  constructor(message: string, status: number, body: unknown, origin: string);
48
50
  }
51
+ /** The agent keys file could not be read or written; nothing was signed under the new key. */
52
+ export declare class AgentKeysFileError extends Error {
53
+ readonly path: string;
54
+ constructor(message: string, path: string);
55
+ }
56
+ /** An Ed25519 public key as the cert exchange sends it. */
57
+ export interface AgentPublicKeyJwk {
58
+ kty: 'OKP';
59
+ crv: 'Ed25519';
60
+ x: string;
61
+ }
62
+ /**
63
+ * Add one exchanged cert's public key to the JWK Set at `path`, creating the
64
+ * file if needed. The file is `{ keys: [{ publicKeyJwk, certId, agentId,
65
+ * issuedAt, expiresAt }, ...] }`, the shape `agledger verify --agent-keys`,
66
+ * `agledger-verify --agent-keys` and the SDKs' `agentKeys` read. A key already
67
+ * listed is not added twice. Written through a temp file and a rename, so a
68
+ * crash never leaves half a file; a file that does not hold a `keys` list is
69
+ * refused rather than overwritten. The read and the write happen under
70
+ * `<path>.lock` (see {@link withKeysFileLock}), so commands running at once
71
+ * against one file each add their key.
72
+ */
73
+ export declare function recordAgentKey(path: string, entry: {
74
+ publicKeyJwk: AgentPublicKeyJwk;
75
+ } & Record<string, unknown>): Promise<void>;
76
+ /** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
77
+ export declare const KEYS_FILE_LOCK: {
78
+ /** How long to wait for another process to release the lock. */
79
+ waitMs: number;
80
+ /** A lock older than this was left by a process that died holding it. */
81
+ staleMs: number;
82
+ };
49
83
  /** The `cert` object from a 201 exchange response. Carried verbatim; the CLI reads only the times. */
50
84
  export type CertInfo = Record<string, unknown> & {
51
85
  issuedAt?: string;
@@ -54,6 +88,12 @@ export type CertInfo = Record<string, unknown> & {
54
88
  export interface OidcCertCredentialOptions {
55
89
  source: OidcTokenSource;
56
90
  agentId?: string;
91
+ /**
92
+ * A JWK Set file each exchanged cert's public key is added to before the
93
+ * cert is used (see {@link recordAgentKey}), so the agent signatures this
94
+ * CLI seals can be re-verified offline with `--agent-keys`.
95
+ */
96
+ agentKeysFile?: string;
57
97
  /** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
58
98
  refreshFraction?: number;
59
99
  /** Diagnostics sink for --verbose. Never receives a token, cert or key. */
@@ -94,6 +134,7 @@ export declare function fetchOidcToken(source: OidcTokenSource, purpose?: TokenP
94
134
  export declare class OidcCertCredential {
95
135
  readonly source: OidcTokenSource;
96
136
  private readonly agentId;
137
+ private readonly agentKeysFile;
97
138
  private readonly refreshFraction;
98
139
  private readonly log;
99
140
  private readonly now;
@@ -112,6 +153,12 @@ export declare class OidcCertCredential {
112
153
  constructor(options: OidcCertCredentialOptions);
113
154
  /** The cert from the most recent exchange, as the Server returned it. */
114
155
  get cert(): CertInfo | null;
156
+ /**
157
+ * The public half of this credential's key pair, as sent at the exchange.
158
+ * The Server's cert carries only its thumbprint; this is the key
159
+ * `agledger verify --agent-keys` needs to re-verify what the agent signed.
160
+ */
161
+ get publicKeyJwk(): AgentPublicKeyJwk;
115
162
  /** How many exchanges this credential has performed. */
116
163
  get exchangeCount(): number;
117
164
  /**
package/dist/oidc.js CHANGED
@@ -11,12 +11,15 @@
11
11
  */
12
12
  import { spawn } from 'node:child_process';
13
13
  import { createHash, generateKeyPairSync, sign } from 'node:crypto';
14
- import { readFile } from 'node:fs/promises';
14
+ import { link, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
15
+ import { dirname, join } from 'node:path';
15
16
  /** Env vars the CLI reads a token source from. The MCP server reads the same names. */
16
17
  export const OIDC_ENV = {
17
18
  TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD',
18
19
  TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE',
19
20
  AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID',
21
+ /** A JWK Set file every cert exchange adds its public key to, for `agledger verify --agent-keys`. */
22
+ AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE',
20
23
  };
21
24
  /**
22
25
  * Env vars naming an RFC 8693 delegation token, sent as `AGLedger-On-Behalf-Of`
@@ -51,6 +54,140 @@ export class OidcExchangeError extends Error {
51
54
  this.name = 'OidcExchangeError';
52
55
  }
53
56
  }
57
+ /** The agent keys file could not be read or written; nothing was signed under the new key. */
58
+ export class AgentKeysFileError extends Error {
59
+ path;
60
+ constructor(message, path) {
61
+ super(message);
62
+ this.path = path;
63
+ this.name = 'AgentKeysFileError';
64
+ }
65
+ }
66
+ /**
67
+ * Add one exchanged cert's public key to the JWK Set at `path`, creating the
68
+ * file if needed. The file is `{ keys: [{ publicKeyJwk, certId, agentId,
69
+ * issuedAt, expiresAt }, ...] }`, the shape `agledger verify --agent-keys`,
70
+ * `agledger-verify --agent-keys` and the SDKs' `agentKeys` read. A key already
71
+ * listed is not added twice. Written through a temp file and a rename, so a
72
+ * crash never leaves half a file; a file that does not hold a `keys` list is
73
+ * refused rather than overwritten. The read and the write happen under
74
+ * `<path>.lock` (see {@link withKeysFileLock}), so commands running at once
75
+ * against one file each add their key.
76
+ */
77
+ export async function recordAgentKey(path, entry) {
78
+ await withKeysFileLock(path, () => appendAgentKey(path, entry));
79
+ }
80
+ /** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
81
+ export const KEYS_FILE_LOCK = {
82
+ /** How long to wait for another process to release the lock. */
83
+ waitMs: 15_000,
84
+ /** A lock older than this was left by a process that died holding it. */
85
+ staleMs: 10_000,
86
+ };
87
+ /**
88
+ * Run `fn` holding `<path>.lock`, an exclusively created file. The holder
89
+ * deletes it when done. A lock older than `KEYS_FILE_LOCK.staleMs` is taken
90
+ * over: it is renamed aside (atomic, so only one waiter wins) and the rename
91
+ * is undone if what moved was a fresh lock rather than the stale one. The
92
+ * MCP server takes the same lock on the same file.
93
+ */
94
+ async function withKeysFileLock(path, fn) {
95
+ const lock = `${path}.lock`;
96
+ const deadline = Date.now() + KEYS_FILE_LOCK.waitMs;
97
+ for (let delay = 5;; delay = Math.min(delay * 2, 100)) {
98
+ try {
99
+ await (await open(lock, 'wx')).close();
100
+ break;
101
+ }
102
+ catch (err) {
103
+ const code = err.code;
104
+ if (code !== 'EEXIST') {
105
+ throw new AgentKeysFileError(`Cannot create the agent keys file lock ${lock} (${code ?? String(err)}).`, path);
106
+ }
107
+ }
108
+ if (await breakStaleLock(lock))
109
+ continue;
110
+ if (Date.now() >= deadline) {
111
+ throw new AgentKeysFileError(`The agent keys file ${path} stayed locked by another process for ${KEYS_FILE_LOCK.waitMs / 1000}s. If no agledger process is running, delete ${lock}.`, path);
112
+ }
113
+ await new Promise((r) => setTimeout(r, delay + Math.random() * delay));
114
+ }
115
+ try {
116
+ return await fn();
117
+ }
118
+ finally {
119
+ await rm(lock, { force: true });
120
+ }
121
+ }
122
+ /** Remove `lock` if it is stale. True when the caller should try to take it again. */
123
+ async function breakStaleLock(lock) {
124
+ let seen;
125
+ try {
126
+ seen = await stat(lock);
127
+ }
128
+ catch {
129
+ return true; // Released between our open and stat.
130
+ }
131
+ if (Date.now() - seen.mtimeMs <= KEYS_FILE_LOCK.staleMs)
132
+ return false;
133
+ const aside = `${lock}.${process.pid}.${Date.now()}.stale`;
134
+ try {
135
+ await rename(lock, aside);
136
+ }
137
+ catch {
138
+ return true; // Another waiter moved it first.
139
+ }
140
+ const moved = await stat(aside).catch(() => null);
141
+ if (moved !== null && moved.ino !== seen.ino) {
142
+ // A waiter replaced the stale lock between our stat and rename: put its
143
+ // lock back. If the path was taken again meanwhile, that holder keeps it.
144
+ await link(aside, lock).catch(() => { });
145
+ }
146
+ await rm(aside, { force: true });
147
+ return true;
148
+ }
149
+ async function appendAgentKey(path, entry) {
150
+ let doc = { keys: [] };
151
+ let text = null;
152
+ try {
153
+ text = await readFile(path, 'utf8');
154
+ }
155
+ catch (err) {
156
+ if (err.code !== 'ENOENT') {
157
+ throw new AgentKeysFileError(`Cannot read the agent keys file ${path} (${err.code ?? String(err)}).`, path);
158
+ }
159
+ }
160
+ if (text !== null && text.trim() !== '') {
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(text);
164
+ }
165
+ catch {
166
+ throw new AgentKeysFileError(`The agent keys file ${path} is not JSON; it was left as it is.`, path);
167
+ }
168
+ if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.keys)) {
169
+ throw new AgentKeysFileError(`The agent keys file ${path} does not hold a {"keys": [...]} JWK Set; it was left as it is.`, path);
170
+ }
171
+ doc = parsed;
172
+ }
173
+ const x = entry.publicKeyJwk.x;
174
+ const listed = doc.keys.some((k) => {
175
+ const jwk = k !== null && typeof k === 'object' && 'publicKeyJwk' in k ? k.publicKeyJwk : k;
176
+ return jwk !== null && typeof jwk === 'object' && jwk.x === x;
177
+ });
178
+ if (listed)
179
+ return;
180
+ doc.keys.push(entry);
181
+ const temp = join(dirname(path), `.${process.pid}.${Date.now()}.agent-keys.tmp`);
182
+ try {
183
+ await writeFile(temp, JSON.stringify(doc, null, 2) + '\n');
184
+ await rename(temp, path);
185
+ }
186
+ catch (err) {
187
+ await rm(temp, { force: true });
188
+ throw new AgentKeysFileError(`Cannot write the agent keys file ${path} (${err.code ?? String(err)}).`, path);
189
+ }
190
+ }
54
191
  /** Bounds on a token command. Mutable so tests can shorten the timeout. */
55
192
  export const TOKEN_COMMAND_LIMITS = {
56
193
  timeoutMs: 60_000,
@@ -63,7 +200,7 @@ const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
63
200
  /** Replace anything shaped like a JWT with a placeholder. Token command stderr
64
201
  * and Server error bodies are surfaced to the user, and either can carry one. */
65
202
  export function redactTokens(text) {
66
- return text.replace(JWT_PATTERN, '<redacted-token>');
203
+ return text.replaceAll(JWT_PATTERN, '<redacted-token>');
67
204
  }
68
205
  /** Deep-copy a JSON value with every string passed through `redactTokens`,
69
206
  * and any string equal to or containing `token` replaced. The Server's
@@ -188,6 +325,7 @@ export async function fetchOidcToken(source, purpose = 'cert-exchange') {
188
325
  export class OidcCertCredential {
189
326
  source;
190
327
  agentId;
328
+ agentKeysFile;
191
329
  refreshFraction;
192
330
  log;
193
331
  now;
@@ -206,6 +344,7 @@ export class OidcCertCredential {
206
344
  constructor(options) {
207
345
  this.source = options.source;
208
346
  this.agentId = options.agentId || undefined;
347
+ this.agentKeysFile = options.agentKeysFile || undefined;
209
348
  this.refreshFraction = options.refreshFraction ?? 0.5;
210
349
  this.log = options.log ?? (() => { });
211
350
  this.now = options.now ?? Date.now;
@@ -221,6 +360,14 @@ export class OidcCertCredential {
221
360
  get cert() {
222
361
  return this.certInfo;
223
362
  }
363
+ /**
364
+ * The public half of this credential's key pair, as sent at the exchange.
365
+ * The Server's cert carries only its thumbprint; this is the key
366
+ * `agledger verify --agent-keys` needs to re-verify what the agent signed.
367
+ */
368
+ get publicKeyJwk() {
369
+ return { kty: 'OKP', crv: 'Ed25519', x: this.publicKeyX };
370
+ }
224
371
  /** How many exchanges this credential has performed. */
225
372
  get exchangeCount() {
226
373
  return this.exchanges;
@@ -281,7 +428,7 @@ export class OidcCertCredential {
281
428
  const proofOfPossession = sign(null, Buffer.from(`agledger.oidc.cert.v1\n${sub}`, 'utf8'), this.privateKey).toString('base64');
282
429
  const body = {
283
430
  oidcToken: token,
284
- publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: this.publicKeyX },
431
+ publicKeyJwk: this.publicKeyJwk,
285
432
  proofOfPossession,
286
433
  ...(this.agentId ? { agentId: this.agentId } : {}),
287
434
  };
@@ -334,6 +481,17 @@ export class OidcCertCredential {
334
481
  // receipt, so a local clock that disagrees with the Server's neither
335
482
  // re-exchanges on every request nor holds a cert past its end. A cert
336
483
  // whose times do not parse is used for this request and re-exchanged next time.
484
+ // Recorded before the cert is used, so nothing is signed under a key the
485
+ // file does not list. A write that fails stops the command here.
486
+ if (this.agentKeysFile !== undefined) {
487
+ await recordAgentKey(this.agentKeysFile, {
488
+ publicKeyJwk: this.publicKeyJwk,
489
+ certId: out.cert.id,
490
+ agentId: out.cert.agentId,
491
+ issuedAt: out.cert.issuedAt,
492
+ expiresAt: out.cert.expiresAt,
493
+ });
494
+ }
337
495
  const received = this.now();
338
496
  this.refreshAt = lifetime > 0 ? received + this.refreshFraction * lifetime : 0;
339
497
  this.expiresAt = lifetime > 0 ? received + lifetime : 0;
@@ -349,6 +507,7 @@ export class OidcCertCredential {
349
507
  oidcSub: out.cert.oidcSub,
350
508
  issuedAt: out.cert.issuedAt,
351
509
  expiresAt: out.cert.expiresAt,
510
+ ...(this.agentKeysFile !== undefined ? { agentKeysFile: this.agentKeysFile } : {}),
352
511
  });
353
512
  return out.certJws;
354
513
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Profile storage at ~/.agledger/config.json. Credential-sensitive: directory 0700,
3
- * file 0600, chmodSync belt-and-braces for pre-existing files.
3
+ * file 0600, both enforced on every write, not only when they are created.
4
4
  */
5
5
  /**
6
6
  * Where `agledger login --oidc` finds an OIDC token. The source is stored,
@@ -11,6 +11,8 @@ export interface OidcProfileSource {
11
11
  tokenCommand?: string;
12
12
  tokenFile?: string;
13
13
  agentId?: string;
14
+ /** A JWK Set file each cert exchange adds its public key to (absolute). */
15
+ agentKeysFile?: string;
14
16
  }
15
17
  /** A profile holds an API key or an OIDC token source. */
16
18
  export interface Profile {
@@ -24,5 +26,18 @@ export interface Config {
24
26
  }
25
27
  export declare function configDir(): string;
26
28
  export declare function configPath(): string;
29
+ /** The config file exists but cannot be read as a profile store. Never replaced silently. */
30
+ export declare class ConfigFileError extends Error {
31
+ readonly path: string;
32
+ constructor(message: string, path: string);
33
+ }
34
+ /** A profile by name, own entries only: `toString` and `__proto__` name no profile. */
35
+ export declare function getProfile(config: Config, name: string): Profile | undefined;
36
+ /**
37
+ * Read the stored profiles. A missing file is an empty store. A file that is
38
+ * not valid JSON, or not the profile shape, throws: returning an empty store
39
+ * there let the next `login` overwrite the file and lose every profile.
40
+ */
27
41
  export declare function readConfig(): Config;
42
+ /** Write the store through a temp file in the same directory and a rename, so a crash never leaves half a file. */
28
43
  export declare function writeConfig(config: Config): void;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Profile storage at ~/.agledger/config.json. Credential-sensitive: directory 0700,
3
- * file 0600, chmodSync belt-and-braces for pre-existing files.
3
+ * file 0600, both enforced on every write, not only when they are created.
4
4
  */
5
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { homedir } from 'node:os';
8
8
  export function configDir() {
@@ -11,26 +11,62 @@ export function configDir() {
11
11
  export function configPath() {
12
12
  return join(configDir(), 'config.json');
13
13
  }
14
+ /** The config file exists but cannot be read as a profile store. Never replaced silently. */
15
+ export class ConfigFileError extends Error {
16
+ path;
17
+ constructor(message, path) {
18
+ super(message);
19
+ this.path = path;
20
+ this.name = 'ConfigFileError';
21
+ }
22
+ }
23
+ /** A profile by name, own entries only: `toString` and `__proto__` name no profile. */
24
+ export function getProfile(config, name) {
25
+ return Object.hasOwn(config.profiles, name) ? config.profiles[name] : undefined;
26
+ }
27
+ function isRecord(value) {
28
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
29
+ }
30
+ /**
31
+ * Read the stored profiles. A missing file is an empty store. A file that is
32
+ * not valid JSON, or not the profile shape, throws: returning an empty store
33
+ * there let the next `login` overwrite the file and lose every profile.
34
+ */
14
35
  export function readConfig() {
15
36
  const path = configPath();
16
37
  if (!existsSync(path))
17
- return { profiles: {} };
38
+ return { profiles: Object.create(null) };
39
+ let parsed;
18
40
  try {
19
- const parsed = JSON.parse(readFileSync(path, 'utf-8'));
20
- return {
21
- profiles: parsed.profiles ?? {},
22
- activeProfile: parsed.activeProfile,
23
- };
41
+ parsed = JSON.parse(readFileSync(path, 'utf-8'));
42
+ }
43
+ catch (err) {
44
+ throw new ConfigFileError(`The config file ${path} cannot be read: ${err instanceof Error ? err.message : String(err)}`, path);
24
45
  }
25
- catch {
26
- return { profiles: {} };
46
+ if (!isRecord(parsed) || (parsed.profiles !== undefined && !isRecord(parsed.profiles))) {
47
+ throw new ConfigFileError(`The config file ${path} is not a profile store (expected an object with a "profiles" object).`, path);
27
48
  }
49
+ const activeProfile = typeof parsed.activeProfile === 'string' ? parsed.activeProfile : undefined;
50
+ return {
51
+ profiles: Object.assign(Object.create(null), parsed.profiles ?? {}),
52
+ activeProfile,
53
+ };
28
54
  }
55
+ /** Write the store through a temp file in the same directory and a rename, so a crash never leaves half a file. */
29
56
  export function writeConfig(config) {
30
57
  const dir = configDir();
31
- if (!existsSync(dir))
32
- mkdirSync(dir, { recursive: true, mode: 0o700 });
58
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
59
+ // The mode above applies only when the directory is created.
60
+ chmodSync(dir, 0o700);
33
61
  const path = configPath();
34
- writeFileSync(path, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
35
- chmodSync(path, 0o600);
62
+ const temp = join(dir, `.config.json.${process.pid}.tmp`);
63
+ try {
64
+ writeFileSync(temp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
65
+ chmodSync(temp, 0o600);
66
+ renameSync(temp, path);
67
+ }
68
+ catch (err) {
69
+ rmSync(temp, { force: true });
70
+ throw err;
71
+ }
36
72
  }