@agledger/cli 2.0.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 +77 -25
  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 +97 -12
  7. package/dist/base.js +90 -37
  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 +131 -11
  38. package/dist/commands/verify.js +214 -25
  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 -857
@@ -1,7 +1,9 @@
1
- import { existsSync } from 'node:fs';
2
- import { Args, Flags } from '@oclif/core';
3
- import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, verifyAuditExport, } from '@agledger/verify-core';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { Args, Flags } from '../cli/index.js';
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
@@ -18,6 +20,11 @@ const OPTION_FLAGS = [
18
20
  [/\brequireSuppliedKeys\b/g, '--require-supplied-keys'],
19
21
  [/\brequireKeyId\b/g, '--require-key-id'],
20
22
  [/\bagentKeys\b/g, '--agent-keys'],
23
+ [/\bfederationKeys\[\d+\]\.history\b/g, '--federation-key-history'],
24
+ [/\bfederationKeys\[\d+\]/g, '--federation-key'],
25
+ [/\bfederationKeys\b/g, '--federation-key'],
26
+ [/\ballowAfterRetirement\b/g, '--allow-after-retirement'],
27
+ [/\bexpectedEntryCount\b/g, '--expected-entry-count'],
21
28
  ];
22
29
  /** One prose string from a result, its option names given as this command's flags. */
23
30
  export function flagWording(text) {
@@ -55,18 +62,18 @@ export function resultWithFlags(result) {
55
62
  export default class Verify extends BaseCommand {
56
63
  static description = 'Verify a record audit export offline (COSE_Sign1 envelope, RFC 9052; Ed25519 or ES256).';
57
64
  static examples = [
58
- '<%= config.bin %> verify audit-export.json --trust-anchor sha256:<64 hex>',
59
- '<%= config.bin %> verify audit-export.json',
60
- '<%= config.bin %> verify audit-export.json --keys vault-keys.json',
61
- '<%= config.bin %> verify audit-export.json --agent-keys agent-jwks.json',
62
- '<%= config.bin %> verify audit-export.json --json',
63
- '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 -',
64
73
  ];
65
- // FILE is required, but checked in run() rather than by oclif: oclif's own
66
- // missing-arg error tells the caller to put arguments before every
67
- // repeatable flag, which is not true of non-greedy ones, and lists hidden
68
- // flags with them.
69
- static usage = 'verify FILE [--trust-anchor <value>...] [--distrusted-key <value>...] [--keys <value>] [--agent-keys <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]';
70
77
  static args = {
71
78
  file: Args.string({
72
79
  description: 'Path to the audit export JSON file (or "-" for stdin).',
@@ -111,6 +118,39 @@ export default class Verify extends BaseCommand {
111
118
  'of them by thumbprint has that signature re-verified offline, and fails ' +
112
119
  'CHAIN_AGENT_SIGNATURE_INVALID if it does not verify.',
113
120
  }),
121
+ 'federation-key': Flags.string({
122
+ multiple: true,
123
+ multipleNonGreedy: true,
124
+ description: '<hubId>=<key>: a peer Server\'s Ed25519 federation key as its operator gives it (base64 SPKI DER, ' +
125
+ 'or base64 of the raw 32 bytes the handshake registered). A receiving Server seals each peer message ' +
126
+ 'it accepts on the chain entry it writes (payload.wire), as the peer signed it. Every sealed message is ' +
127
+ 'held to its body hash and to its entry; one from a hub given here also has its signature re-verified ' +
128
+ 'under that key, which checks what the peer asserted from this export alone. A failure is ' +
129
+ 'CHAIN_FEDERATION_WIRE_INVALID. Repeatable, once per peer; name a hub twice to pin a second key ' +
130
+ 'no succession links to the first: one its history lists linked: false, or one it does not list at all.',
131
+ }),
132
+ 'federation-key-history': Flags.string({
133
+ multiple: true,
134
+ multipleNonGreedy: true,
135
+ description: 'Path to a peer\'s federation key history, the JSON its GET /.well-known/agledger-federation-keys.json serves ' +
136
+ '(no auth). Needs a --federation-key for the same hub: every key the history links to that key through ' +
137
+ 'successions both keys signed is trusted inside its window, so entries sealed before the peer changed its ' +
138
+ 'federation key verify. Each message is placed by its signed wire.timestamp, never by the unsigned ' +
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.',
153
+ }),
114
154
  'require-key-id': Flags.string({
115
155
  description: 'Require every entry to reference this keyId. Rejects otherwise-valid exports ' +
116
156
  'signed by a retired or unexpected key.',
@@ -168,6 +208,14 @@ export default class Verify extends BaseCommand {
168
208
  }
169
209
  throw err;
170
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
+ }
171
219
  if (args.file === undefined) {
172
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.');
173
221
  }
@@ -178,6 +226,7 @@ export default class Verify extends BaseCommand {
178
226
  const agentKeys = flags['agent-keys']
179
227
  ? this.unwrapAgentKeys(this.readJsonSource(flags['agent-keys'], 'agent keys', 'The --agent-keys file must be an Ed25519 JWK, a list of them, or a {keys:[...]} JWK Set.'))
180
228
  : undefined;
229
+ const federationKeys = this.attachFederationKeyHistories(this.parseFederationKeys(flags['federation-key'] ?? []), flags['federation-key-history'] ?? []);
181
230
  const exportData = this.readJsonSource(args.file, 'audit export', 'Pass the path to an audit-export JSON file, or `-` to read it from stdin. ' +
182
231
  'Obtain one with `agledger api GET /v1/records/{id}/audit-export`.');
183
232
  if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
@@ -190,7 +239,7 @@ export default class Verify extends BaseCommand {
190
239
  // verify-core throws TypeError at the supplied-key boundary when the
191
240
  // file's shape is wrong (e.g. {keyId: 42}, [null], "...") or a key window
192
241
  // in it is not RFC 3339: valid JSON, a value refused. Catch it so the
193
- // CLI emits its structured-error envelope rather than oclif's raw
242
+ // CLI emits its structured-error envelope rather than a raw
194
243
  // exception trace; agents parsing stderr need {code, message, suggestion},
195
244
  // not a stack frame.
196
245
  let result;
@@ -201,13 +250,17 @@ export default class Verify extends BaseCommand {
201
250
  requireSuppliedKeys: flags['require-supplied-keys'],
202
251
  ...(trustAnchors.length > 0 ? { trustAnchors, distrustedKeys } : {}),
203
252
  agentKeys,
253
+ federationKeys,
254
+ allowAfterRetirement: flags['allow-after-retirement'],
255
+ ...(expectedEntryCount !== undefined ? { expectedEntryCount } : {}),
204
256
  });
205
257
  }
206
258
  catch (err) {
207
259
  if (err instanceof TypeError) {
208
- this.failWith(ErrorCode.INVALID_FIELD, err.message, ExitCode.USAGE_ERROR, 'The --keys file must be a {keyId: SPKI-DER-base64} map or a list of ' +
260
+ this.failWith(ErrorCode.INVALID_FIELD, flagWording(err.message), ExitCode.USAGE_ERROR, 'The --keys file must be a {keyId: SPKI-DER-base64} map or a list of ' +
209
261
  '{keyId, publicKey, activatedAt?, retiredAt?} entries with RFC 3339 windows (the /v1/verification-keys body works as is); ' +
210
- 'the --agent-keys file must hold Ed25519 JWKs ({"kty":"OKP","crv":"Ed25519","x":"..."}).');
262
+ 'the --agent-keys file must hold Ed25519 JWKs ({"kty":"OKP","crv":"Ed25519","x":"..."}); ' +
263
+ 'a --federation-key-history file must be the peer\'s served document, unaltered, and reach the --federation-key given for its hub.');
211
264
  }
212
265
  throw err;
213
266
  }
@@ -220,10 +273,16 @@ export default class Verify extends BaseCommand {
220
273
  this.output({ verdict, ...rest });
221
274
  }
222
275
  else {
223
- this.renderHuman(result, agentKeys !== undefined);
276
+ this.renderHuman(result, agentKeys !== undefined, federationKeys !== undefined, expectedEntryCount);
224
277
  }
225
- 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')
226
283
  this.exit(ExitCode.GENERAL_ERROR);
284
+ if (result.verdict === 'unanchored' && trustAnchors.length > 0)
285
+ this.exit(EXIT_NOT_ANCHORED);
227
286
  }
228
287
  /**
229
288
  * Accept the raw `GET /v1/verification-keys` response shape. That endpoint
@@ -247,6 +306,60 @@ export default class Verify extends BaseCommand {
247
306
  * entry that wraps its key as `{ publicKeyJwk: {...} }` (how an agent records
248
307
  * the key it sent at cert exchange) is unwrapped. verify-core validates each.
249
308
  */
309
+ /**
310
+ * `--federation-key` values into the `[{ hubId, publicKey }]` list
311
+ * verify-core takes, each checked here so a bad key is a usage error, not a
312
+ * verdict. A hub named twice pins two keys.
313
+ */
314
+ parseFederationKeys(values) {
315
+ const out = [];
316
+ const shape = 'Each --federation-key is <hubId>=<key>: the peer\'s hub id, then its Ed25519 federation key as base64 SPKI DER or base64 of the raw 32 bytes, as its operator gives it.';
317
+ for (const value of values) {
318
+ const at = value.indexOf('=');
319
+ const hubId = at === -1 ? '' : value.slice(0, at).trim();
320
+ const key = at === -1 ? '' : value.slice(at + 1).trim();
321
+ if (hubId === '' || key === '') {
322
+ this.failWith(ErrorCode.INVALID_FIELD, `Invalid --federation-key ${JSON.stringify(value)}.`, ExitCode.USAGE_ERROR, shape);
323
+ }
324
+ if (normalizeFederationKey(key) === null) {
325
+ this.failWith(ErrorCode.INVALID_FIELD, `Invalid --federation-key for hub ${hubId}: the key is not an Ed25519 public key.`, ExitCode.USAGE_ERROR, shape);
326
+ }
327
+ out.push({ hubId, publicKey: key });
328
+ }
329
+ return out;
330
+ }
331
+ /**
332
+ * Each `--federation-key-history` file attached to the `--federation-key`
333
+ * entry for the hub it names, or undefined when neither flag was given. A
334
+ * history needs a key for its hub: alone it is the peer's word.
335
+ */
336
+ attachFederationKeyHistories(keys, paths) {
337
+ if (keys.length === 0 && paths.length === 0)
338
+ return undefined;
339
+ const out = keys.map((k) => ({ ...k }));
340
+ for (const path of paths) {
341
+ let doc;
342
+ try {
343
+ doc = JSON.parse(readFileSync(path, 'utf8'));
344
+ }
345
+ catch (err) {
346
+ this.failWith(ErrorCode.INVALID_FIELD, `Cannot read --federation-key-history ${path}: ${err.message}`, ExitCode.USAGE_ERROR, 'Pass the JSON the peer serves at GET /.well-known/agledger-federation-keys.json.');
347
+ }
348
+ const hubId = doc !== null && typeof doc === 'object' ? doc.hubId : undefined;
349
+ if (typeof hubId !== 'string' || hubId === '') {
350
+ this.failWith(ErrorCode.INVALID_FIELD, `--federation-key-history ${path} is not a key-history document naming its hub.`, ExitCode.USAGE_ERROR, 'Pass the JSON the peer serves at GET /.well-known/agledger-federation-keys.json, with federation configured on the peer.');
351
+ }
352
+ const entry = out.find((k) => k.hubId === hubId && k.history === undefined) ?? out.find((k) => k.hubId === hubId);
353
+ if (entry === undefined) {
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.');
355
+ }
356
+ if (entry.history !== undefined)
357
+ out.push({ hubId, publicKey: entry.publicKey, history: doc });
358
+ else
359
+ entry.history = doc;
360
+ }
361
+ return out;
362
+ }
250
363
  unwrapAgentKeys(raw) {
251
364
  const list = Array.isArray(raw)
252
365
  ? raw
@@ -257,7 +370,7 @@ export default class Verify extends BaseCommand {
257
370
  ? entry.publicKeyJwk
258
371
  : entry);
259
372
  }
260
- renderHuman(result, agentKeysGiven) {
373
+ renderHuman(result, agentKeysGiven, federationKeysGiven, expectedEntryCount) {
261
374
  if (this.isQuiet)
262
375
  return;
263
376
  const out = process.stdout;
@@ -269,17 +382,24 @@ export default class Verify extends BaseCommand {
269
382
  const verdict = result.verdict;
270
383
  const anchored = trust.status === 'walked';
271
384
  // The same headline words as @agledger/verify and the Python agledger-verify.
272
- 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';
273
387
  out.write(`${icon} Record: ${result.recordId}\n`);
274
388
  out.write(` Entries: ${result.verifiedEntries}/${result.totalEntries} verified\n`);
275
- 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') {
276
396
  out.write(trust.status === 'no_anchored_signature'
277
397
  ? ' Nothing failed, but this is NOT a trusted verdict: the --trust-anchor was walked, but no ' +
278
398
  'signature here verified under a key it anchors. An entry written before the install began ' +
279
- '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'
280
400
  : ' Nothing failed, but this is NOT a trusted verdict: no --trust-anchor was given, so every ' +
281
- "signing key was taken on the word of the export itself, and a key written into the Server's " +
282
- '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 ' +
283
403
  'installer prints it; signing-key-digest.js derives it from any key) and re-run with ' +
284
404
  '--trust-anchor sha256:<hex>.\n');
285
405
  }
@@ -307,6 +427,13 @@ export default class Verify extends BaseCommand {
307
427
  // Agent signatures are checked only against keys the caller supplies, so
308
428
  // the lines below say exactly how many were, and the PASS line speaks for
309
429
  // the Server's signatures alone.
430
+ out.write(` ${entryCountLine(result.entryCount, result.totalEntries, expectedEntryCount)}\n`);
431
+ const peerLine = peerMessagesLine(result.federationWire, federationKeysGiven);
432
+ if (peerLine)
433
+ out.write(` ${peerLine}\n`);
434
+ const evidenceLine = evidenceBodiesLine(result.evidenceBinding);
435
+ if (evidenceLine)
436
+ out.write(` ${evidenceLine}\n`);
310
437
  const { present, verified } = result.agentSignatures;
311
438
  const unchecked = present - verified;
312
439
  if (present > 0 && unchecked === 0) {
@@ -342,3 +469,65 @@ export default class Verify extends BaseCommand {
342
469
  }
343
470
  }
344
471
  }
472
+ /**
473
+ * The human line on the evidence bodies an `?evidence=true` export inlines,
474
+ * or null when it carries none. Each is hashed against the evidenceHash or
475
+ * payloadHash its entry signs; an encrypted-mode completion cannot be.
476
+ */
477
+ export function evidenceBodiesLine(counts) {
478
+ if (counts.present === 0)
479
+ return null;
480
+ const parts = [`${counts.verified}/${counts.present} inlined evidence bodies hash (RFC 8785, SHA-256) to the hash their entry signs`];
481
+ if (counts.failed > 0)
482
+ parts.push(`${counts.failed} failed CHAIN_EVIDENCE_BINDING_MISMATCH`);
483
+ if (counts.clientHashed > 0) {
484
+ parts.push(`${counts.clientHashed} on an encrypted-mode completion, whose signed hash covers a cleartext the export does not carry, so not re-bound`);
485
+ }
486
+ return `Evidence: ${parts.join('; ')}.`;
487
+ }
488
+ /**
489
+ * The human line on the sealed federation messages, or null when the chain
490
+ * carries none. `failed` messages failed a check and are reported as
491
+ * failures; the rest of the unverified ones came from a hub with no key.
492
+ */
493
+ export function peerMessagesLine(wire, federationKeysGiven) {
494
+ if (wire.present === 0)
495
+ return null;
496
+ const retired = wire.afterRetirement > 0
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.`
498
+ : '';
499
+ if (wire.present === wire.verified) {
500
+ return `Peer messages: ${wire.verified}/${wire.present} sealed federation messages re-verified under --federation-key.${retired}`;
501
+ }
502
+ if (!federationKeysGiven && wire.failed === 0) {
503
+ return `Peer messages: ${wire.present} sealed on the chain, hashed and matched to their entry; the peer signatures were not checked. Pass --federation-key <hubId>=<key> for each peer to re-verify them.`;
504
+ }
505
+ const noKey = wire.present - wire.verified - wire.failed;
506
+ const parts = [`${wire.verified}/${wire.present} re-verified`];
507
+ if (wire.failed > 0)
508
+ parts.push(`${wire.failed} failed CHAIN_FEDERATION_WIRE_INVALID`);
509
+ if (noKey > 0) {
510
+ parts.push(federationKeysGiven
511
+ ? `${noKey} come from a hub with no --federation-key and were hashed and matched to their entry only`
512
+ : `${noKey} were hashed and matched to their entry only; pass --federation-key <hubId>=<key> for each peer to re-verify them`);
513
+ }
514
+ return `Peer messages: ${parts.join('; ')}.${retired}`;
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
  }