@agledger/cli 1.4.1 → 2.0.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.
@@ -1,6 +1,50 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { Args, Flags } from '@oclif/core';
2
- import { verifyAuditExport, } from '@agledger/verify-core';
3
+ import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, verifyAuditExport, } from '@agledger/verify-core';
3
4
  import { BaseCommand, ErrorCode, ExitCode } from '../base.js';
5
+ /**
6
+ * verify-core words a finding, note or failure for a library caller, so its
7
+ * advice names options (`give distrustedKeys sha256:<hex>@<instant>`, `pin
8
+ * sha256:<hex> in trustAnchors`). Here they are flags, so the report names the flag, in the
9
+ * words `@agledger/verify` prints; verify-core's own result is left as it is.
10
+ */
11
+ const OPTION_FLAGS = [
12
+ [/\badd (sha256:[0-9a-f]{64}) to distrustedKeys\b/g, 'add --distrusted-key $1'],
13
+ [/\bis in distrustedKeys\b/g, 'is given as a --distrusted-key'],
14
+ [/\bin trustAnchors\b/g, 'with --trust-anchor'],
15
+ [/\bNo trustAnchors were given\b/g, 'No --trust-anchor was given'],
16
+ [/\bdistrustedKeys\b/g, '--distrusted-key'],
17
+ [/\btrustAnchors\b/g, '--trust-anchor'],
18
+ [/\brequireSuppliedKeys\b/g, '--require-supplied-keys'],
19
+ [/\brequireKeyId\b/g, '--require-key-id'],
20
+ [/\bagentKeys\b/g, '--agent-keys'],
21
+ ];
22
+ /** One prose string from a result, its option names given as this command's flags. */
23
+ export function flagWording(text) {
24
+ return OPTION_FLAGS.reduce((s, [pattern, flag]) => s.replace(pattern, flag), text);
25
+ }
26
+ /**
27
+ * A result with its prose worded by {@link flagWording}: `brokenAt.detail`,
28
+ * each entry's detail, and the key-trust detail and each finding, note and
29
+ * accounted-for detail. Ids, digests and instants are data and pass through.
30
+ */
31
+ export function resultWithFlags(result) {
32
+ const detail = (item) => item.detail === undefined ? item : { ...item, detail: flagWording(item.detail) };
33
+ const prose = (item) => ({ ...item, detail: flagWording(item.detail) });
34
+ const trust = result.keyTrust;
35
+ return {
36
+ ...result,
37
+ ...(result.brokenAt ? { brokenAt: detail(result.brokenAt) } : {}),
38
+ entries: result.entries.map(detail),
39
+ keyTrust: {
40
+ ...trust,
41
+ detail: flagWording(trust.detail),
42
+ findings: trust.findings.map(prose),
43
+ notes: trust.notes.map(prose),
44
+ accounted: trust.accounted.map(prose),
45
+ },
46
+ };
47
+ }
4
48
  /**
5
49
  * Offline verification of a record audit export (format 2.0, COSE_Sign1).
6
50
  * Runs entirely offline: no network calls, no API key required. The
@@ -11,39 +55,129 @@ import { BaseCommand, ErrorCode, ExitCode } from '../base.js';
11
55
  export default class Verify extends BaseCommand {
12
56
  static description = 'Verify a record audit export offline (COSE_Sign1 envelope, RFC 9052; Ed25519 or ES256).';
13
57
  static examples = [
58
+ '<%= config.bin %> verify audit-export.json --trust-anchor sha256:<64 hex>',
14
59
  '<%= config.bin %> verify audit-export.json',
15
60
  '<%= config.bin %> verify audit-export.json --keys vault-keys.json',
61
+ '<%= config.bin %> verify audit-export.json --agent-keys agent-jwks.json',
16
62
  '<%= config.bin %> verify audit-export.json --json',
17
63
  'cat audit-export.json | <%= config.bin %> verify -',
18
64
  ];
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]';
19
70
  static args = {
20
71
  file: Args.string({
21
72
  description: 'Path to the audit export JSON file (or "-" for stdin).',
22
- required: true,
23
73
  }),
24
74
  };
25
75
  static flags = {
26
76
  json: BaseCommand.baseFlags.json,
27
77
  quiet: BaseCommand.baseFlags.quiet,
28
78
  keys: Flags.string({
29
- description: 'Path to a JSON file holding out-of-band public keys. Accepts a ' +
79
+ description: 'Path to a JSON file holding public keys you supply. Accepts a ' +
30
80
  '{keyId: SPKI-DER-base64} map, a [{keyId, publicKey, ...}] list, or the ' +
31
81
  'raw GET /v1/verification-keys response envelope ({data:[...], ...}, the ' +
32
- '.data array is unwrapped automatically). Merged over any keys embedded ' +
33
- 'in the export.',
82
+ '.data array is unwrapped automatically, and each key\'s signed statements ' +
83
+ 'are walked with --trust-anchor). Merged over any keys embedded in the export. ' +
84
+ 'Where a key came from is not whether it is trusted: that is --trust-anchor.',
85
+ }),
86
+ 'trust-anchor': Flags.string({
87
+ multiple: true,
88
+ multipleNonGreedy: true,
89
+ description: 'sha256:<64 hex> SPKI digest of a vault key you took out of band (the installer prints the ' +
90
+ 'first vault key\'s; the Server\'s signing-key-digest.js derives one from any key you hold). ' +
91
+ 'The signed key statements the export carries are walked from it: an entry signed by a key ' +
92
+ 'the walk does not reach fails CHAIN_SIGNING_KEY_UNANCHORED, and a statement that does not ' +
93
+ 'hold fails KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID or CHAIN_KEY_WINDOW_DRIFT. Without ' +
94
+ 'one, a pass rests on keys nobody pinned. Repeatable.',
95
+ }),
96
+ 'distrusted-key': Flags.string({
97
+ multiple: true,
98
+ multipleNonGreedy: true,
99
+ description: 'sha256:<64 hex>, optionally @<RFC 3339 instant>: a key the operator distrusts, as in the ' +
100
+ 'Server\'s VAULT_DISTRUSTED_KEYS. What it signed from that instant (with none, from its ' +
101
+ 'retirement) counts for nothing in the walk. Requires --trust-anchor. A dated entry may name a ' +
102
+ 'key also given to --trust-anchor, which then vouches for what it signed before the instant. Where an ' +
103
+ 'export lists a key retired at the instant the Server distrusts it from (distrustedFrom), earlier than ' +
104
+ 'its signed retirement, a run without the same entry fails on that window, and the finding names the ' +
105
+ '--distrusted-key to confirm with the Server\'s operator. Repeatable.',
106
+ }),
107
+ 'agent-keys': Flags.string({
108
+ description: 'Path to a JSON file holding Ed25519 public keys of agent certs: a JWK, a list of JWKs, ' +
109
+ 'or a {keys:[...]} JWK Set (an entry may wrap its key as {publicKeyJwk:{...}}). Each is the publicKeyJwk an agent sent at cert exchange ' +
110
+ '(also the cnf.jwk claim in its certJws). An entry whose sealed agent signature names one ' +
111
+ 'of them by thumbprint has that signature re-verified offline, and fails ' +
112
+ 'CHAIN_AGENT_SIGNATURE_INVALID if it does not verify.',
34
113
  }),
35
114
  'require-key-id': Flags.string({
36
115
  description: 'Require every entry to reference this keyId. Rejects otherwise-valid exports ' +
37
116
  'signed by a retired or unexpected key.',
38
117
  }),
39
- 'require-out-of-band-keys': Flags.boolean({
40
- description: 'High-assurance: refuse keys embedded in the export. Verifying the engine against ' +
41
- 'its own embedded key is not an independent audit, so supply keys via --keys instead.',
118
+ // Refused by name, as @agledger/verify and the Python agledger-verify
119
+ // refuse them, rather than as an unknown flag.
120
+ 'distrusted-keys': Flags.string({ hidden: true }),
121
+ 'require-out-of-band-keys': Flags.boolean({ hidden: true, default: false }),
122
+ 'require-supplied-keys': Flags.boolean({
123
+ description: 'Refuse keys embedded in the export: an entry whose only key is export-embedded fails ' +
124
+ 'CHAIN_KEY_POLICY_VIOLATION, so every signature is checked against a key from --keys.',
42
125
  default: false,
43
126
  }),
44
127
  };
45
128
  async run() {
46
129
  const { args, flags } = await this.parse(Verify);
130
+ if (flags['distrusted-keys'] !== undefined) {
131
+ this.failWith(ErrorCode.INVALID_FIELD, '--distrusted-keys is now --distrusted-key, given once per key: --distrusted-key sha256:<hex>[@<RFC 3339 instant>].', ExitCode.USAGE_ERROR);
132
+ }
133
+ if (flags['require-out-of-band-keys']) {
134
+ this.failWith(ErrorCode.INVALID_FIELD, '--require-out-of-band-keys is now --require-supplied-keys: a key fetched from the Server is supplied, not independent of it. Pin --trust-anchor for that.', ExitCode.USAGE_ERROR);
135
+ }
136
+ // Checked in the order @agledger/verify and the Python agledger-verify
137
+ // check them, with the same messages and exit code, and before the export
138
+ // is read: a mistyped pin is a usage error, never a verdict.
139
+ const trustAnchors = flags['trust-anchor'] ?? [];
140
+ const distrustedKeys = flags['distrusted-key'] ?? [];
141
+ try {
142
+ parseTrustAnchors(trustAnchors);
143
+ parseDistrustedKeys(distrustedKeys);
144
+ }
145
+ catch (err) {
146
+ if (err instanceof TypeError) {
147
+ this.failWith(ErrorCode.INVALID_FIELD, err.message
148
+ .replace(/^trustAnchors entry /, '--trust-anchor ')
149
+ .replace(/^distrustedKeys entry /, '--distrusted-key ')
150
+ .replace(/^distrustedKeys names /, '--distrusted-key names '), ExitCode.USAGE_ERROR, 'Pass --trust-anchor sha256:<64 hex> and --distrusted-key sha256:<64 hex>[@<RFC 3339 instant>], once per key.');
151
+ }
152
+ throw err;
153
+ }
154
+ // verify-core reads distrusted keys only during the walk, so without an
155
+ // anchor they would be dropped without a word.
156
+ if (distrustedKeys.length > 0 && trustAnchors.length === 0) {
157
+ this.failWith(ErrorCode.MISSING_INPUT, '--distrusted-key acts only inside the key-statement walk, which runs from --trust-anchor; pass the pin as well.', ExitCode.USAGE_ERROR, 'Pass --trust-anchor sha256:<64 hex> with the digest of a vault key you took out of band.');
158
+ }
159
+ // The Server refuses to start with a key in VAULT_TRUST_ANCHORS that
160
+ // VAULT_DISTRUSTED_KEYS names with no instant, so that pair is a usage
161
+ // error. A dated entry beside a pin is taken.
162
+ try {
163
+ assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys);
164
+ }
165
+ catch (err) {
166
+ if (err instanceof TypeError) {
167
+ this.failWith(ErrorCode.INVALID_FIELD, err.message.replace(/^(sha256:[0-9a-f]{64}) is a trust anchor and a distrusted key with no instant,/, '$1 is a --trust-anchor and a --distrusted-key with no instant,'), ExitCode.USAGE_ERROR, 'Keep the pin and give the leaked key its instant: --distrusted-key sha256:<64 hex>@<RFC 3339 instant>. Or, if you vouch for nothing it signed, drop its --trust-anchor.');
168
+ }
169
+ throw err;
170
+ }
171
+ if (args.file === undefined) {
172
+ 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
+ }
174
+ if (args.file !== '-' && !existsSync(args.file)) {
175
+ this.failWith(ErrorCode.FILE_READ_ERROR, `Cannot read ${args.file}: no such file or directory.`, ExitCode.USAGE_ERROR, 'Pass the path to an audit-export JSON file, or `-` to read it from stdin. ' +
176
+ 'Obtain one with `agledger api GET /v1/records/{id}/audit-export`.');
177
+ }
178
+ const agentKeys = flags['agent-keys']
179
+ ? 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
+ : undefined;
47
181
  const exportData = this.readJsonSource(args.file, 'audit export', 'Pass the path to an audit-export JSON file, or `-` to read it from stdin. ' +
48
182
  'Obtain one with `agledger api GET /v1/records/{id}/audit-export`.');
49
183
  if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
@@ -53,31 +187,40 @@ export default class Verify extends BaseCommand {
53
187
  ? this.unwrapKeys(this.readJsonSource(flags.keys, 'public keys', 'The --keys file must be a {keyId: SPKI-DER-base64} map or the .data list from ' +
54
188
  '`agledger api GET /v1/verification-keys`.'))
55
189
  : undefined;
56
- // verify-core throws TypeError at the OOB-key boundary when the file's
57
- // shape is wrong (e.g. {keyId: 42}, [null], "..."). Catch it so the CLI
58
- // emits its structured-error envelope rather than oclif's raw exception
59
- // trace; agents parsing stderr need {code, message, suggestion}, not a
60
- // stack frame. See verify-core/audit-export.ts normalizeOutOfBandKeys.
190
+ // verify-core throws TypeError at the supplied-key boundary when the
191
+ // file's shape is wrong (e.g. {keyId: 42}, [null], "...") or a key window
192
+ // 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
194
+ // exception trace; agents parsing stderr need {code, message, suggestion},
195
+ // not a stack frame.
61
196
  let result;
62
197
  try {
63
198
  result = verifyAuditExport(exportData, {
64
199
  publicKeys,
65
200
  requireKeyId: flags['require-key-id'],
66
- requireOutOfBandKeys: flags['require-out-of-band-keys'],
201
+ requireSuppliedKeys: flags['require-supplied-keys'],
202
+ ...(trustAnchors.length > 0 ? { trustAnchors, distrustedKeys } : {}),
203
+ agentKeys,
67
204
  });
68
205
  }
69
206
  catch (err) {
70
207
  if (err instanceof TypeError) {
71
- this.failWith(ErrorCode.INVALID_JSON_INPUT, err.message, ExitCode.USAGE_ERROR, 'The --keys file must be a {keyId: SPKI-DER-base64} map or a list of ' +
72
- '{keyId, publicKey, ...} entries (the .data list from /v1/verification-keys).');
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 ' +
209
+ '{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":"..."}).');
73
211
  }
74
212
  throw err;
75
213
  }
214
+ // Findings, notes and suggestions name the flags, in JSON and text alike.
215
+ result = resultWithFlags(result);
76
216
  if (this.isJson) {
77
- this.output(result);
217
+ // verify-core's result, plus the verdict @agledger/verify reports:
218
+ // `valid` alone is true on a run that anchored nothing.
219
+ const { verdict, ...rest } = result;
220
+ this.output({ verdict, ...rest });
78
221
  }
79
222
  else {
80
- this.renderHuman(result);
223
+ this.renderHuman(result, agentKeys !== undefined);
81
224
  }
82
225
  if (!result.valid)
83
226
  this.exit(ExitCode.GENERAL_ERROR);
@@ -99,15 +242,92 @@ export default class Verify extends BaseCommand {
99
242
  }
100
243
  return raw;
101
244
  }
102
- renderHuman(result) {
245
+ /**
246
+ * A single JWK, a list of JWKs, or a `{keys: [...]}` JWK Set, as a list. An
247
+ * entry that wraps its key as `{ publicKeyJwk: {...} }` (how an agent records
248
+ * the key it sent at cert exchange) is unwrapped. verify-core validates each.
249
+ */
250
+ unwrapAgentKeys(raw) {
251
+ const list = Array.isArray(raw)
252
+ ? raw
253
+ : raw && typeof raw === 'object' && Array.isArray(raw.keys)
254
+ ? raw.keys
255
+ : [raw];
256
+ return list.map((entry) => entry && typeof entry === 'object' && 'publicKeyJwk' in entry
257
+ ? entry.publicKeyJwk
258
+ : entry);
259
+ }
260
+ renderHuman(result, agentKeysGiven) {
103
261
  if (this.isQuiet)
104
262
  return;
105
263
  const out = process.stdout;
106
- const icon = result.valid ? 'PASS' : 'FAIL';
264
+ const trust = result.keyTrust;
265
+ // PASS only when the walk from a pinned anchor verified at least one
266
+ // signature. A chain that verifies against keys nobody pinned, or whose
267
+ // anchors verified no signature at all, is not a clean result whatever
268
+ // `valid` says, so it gets its own verdict word.
269
+ const verdict = result.verdict;
270
+ const anchored = trust.status === 'walked';
271
+ // The same headline words as @agledger/verify and the Python agledger-verify.
272
+ const icon = verdict === 'failed' ? 'FAIL' : verdict === 'trusted' ? 'PASS' : 'VERIFIED, NOT ANCHORED';
107
273
  out.write(`${icon} Record: ${result.recordId}\n`);
108
274
  out.write(` Entries: ${result.verifiedEntries}/${result.totalEntries} verified\n`);
275
+ if (verdict === 'unanchored') {
276
+ out.write(trust.status === 'no_anchored_signature'
277
+ ? ' Nothing failed, but this is NOT a trusted verdict: the --trust-anchor was walked, but no ' +
278
+ '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'
280
+ : ' 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 ' +
283
+ 'installer prints it; signing-key-digest.js derives it from any key) and re-run with ' +
284
+ '--trust-anchor sha256:<hex>.\n');
285
+ }
286
+ if (anchored) {
287
+ out.write(` Keys: ${trust.anchoredKeyIds.length} anchored to --trust-anchor ${trust.anchors.join(', ')}` +
288
+ (trust.unanchoredKeyIds.length > 0 ? `; not anchored: ${trust.unanchoredKeyIds.join(', ')}` : '') +
289
+ (trust.undecidedKeyIds.length > 0 ? `; undecided on this host: ${trust.undecidedKeyIds.join(', ')}` : '') +
290
+ '.\n');
291
+ }
292
+ else if (trust.status === 'no_anchored_signature') {
293
+ out.write(` Keys: walked from --trust-anchor ${trust.anchors.join(', ')}; no signature verified under an anchored key.\n`);
294
+ }
295
+ else {
296
+ out.write(' Keys: not anchored (no --trust-anchor given), checked against keys nobody pinned.\n');
297
+ if (trust.anchoredFrom) {
298
+ out.write(` The export names its Server's key as ${trust.anchoredFrom}: its own claim, not an anchor.\n`);
299
+ }
300
+ }
301
+ for (const f of trust.findings) {
302
+ out.write(` Key finding: ${f.code}${f.keyId ? ` (${f.keyId})` : ''}: ${f.detail}\n`);
303
+ }
304
+ for (const n of trust.notes) {
305
+ out.write(` Key note: ${n.keyId ? `(${n.keyId}) ` : ''}${n.detail}\n`);
306
+ }
307
+ // Agent signatures are checked only against keys the caller supplies, so
308
+ // the lines below say exactly how many were, and the PASS line speaks for
309
+ // the Server's signatures alone.
310
+ const { present, verified } = result.agentSignatures;
311
+ const unchecked = present - verified;
312
+ if (present > 0 && unchecked === 0) {
313
+ out.write(` Agent signatures: ${verified}/${present} re-verified offline against --agent-keys.\n`);
314
+ }
315
+ else if (present > 0 && agentKeysGiven) {
316
+ out.write(` Agent signatures: ${verified}/${present} re-verified offline; ${unchecked} name a key that is not in --agent-keys and were not checked.\n`);
317
+ }
318
+ else if (present > 0) {
319
+ out.write(` Agent signatures: ${present} sealed on the chain, not checked. Pass --agent-keys with the agents' public keys to re-verify them.\n`);
320
+ }
321
+ const { skipped } = result.signatureCoverage;
322
+ if (result.valid && skipped > 0) {
323
+ out.write(` Unsigned: ${skipped} of ${result.totalEntries} entries carry no signature (written before the install registered its first key), so they are covered by the hash chain only.\n`);
324
+ }
109
325
  if (result.valid) {
110
- out.write(' Hash chain contiguous, every signature verified.\n');
326
+ out.write(verdict === 'trusted'
327
+ ? ' Hash chain contiguous, every Server signature verified under a key linked to your trust anchor.\n'
328
+ : trust.status === 'no_anchored_signature'
329
+ ? ' Hash chain contiguous, but no Server signature verified under a key your trust anchor reaches.\n'
330
+ : ' Hash chain contiguous and every Server signature verifies, against keys nobody pinned.\n');
111
331
  return;
112
332
  }
113
333
  if (result.brokenAt) {
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * OIDC cert credential: exchanges a customer IdP token for a short-lived,
3
+ * Server-signed cert (`POST /v1/auth/oidc/cert`) and signs request bodies with
4
+ * the key bound to it.
5
+ *
6
+ * Nothing here touches disk except reading a token file the operator named.
7
+ * The Ed25519 key pair lives in memory for the life of one credential (one CLI
8
+ * invocation), and the cert is cached in memory only. The token source is
9
+ * called for EVERY exchange: the Server refuses a token id it has already
10
+ * exchanged (409), so a token is never reused.
11
+ */
12
+ /** Env vars the CLI reads a token source from. The MCP server reads the same names. */
13
+ export declare const OIDC_ENV: {
14
+ readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
15
+ readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
16
+ readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
17
+ };
18
+ /**
19
+ * Env vars naming an RFC 8693 delegation token, sent as `AGLedger-On-Behalf-Of`
20
+ * when the work is done for a person or another party. The MCP server reads
21
+ * the same names.
22
+ */
23
+ export declare const ON_BEHALF_OF_ENV: {
24
+ readonly CMD: 'AGLEDGER_ON_BEHALF_OF_CMD';
25
+ readonly FILE: 'AGLEDGER_ON_BEHALF_OF_FILE';
26
+ };
27
+ export type OidcTokenSource = {
28
+ kind: 'command';
29
+ command: string; /** Where the command came from, for errors and --verbose. */
30
+ origin: string;
31
+ } | {
32
+ kind: 'file';
33
+ path: string;
34
+ origin: string;
35
+ };
36
+ /** The token source could not produce a token. `origin` names the variable or profile. */
37
+ export declare class OidcTokenSourceError extends Error {
38
+ readonly origin: string;
39
+ readonly kind: OidcTokenSource['kind'];
40
+ constructor(message: string, origin: string, kind: OidcTokenSource['kind']);
41
+ }
42
+ /** The Server refused the exchange. `body` is its error response with the token scrubbed out. */
43
+ export declare class OidcExchangeError extends Error {
44
+ readonly status: number;
45
+ readonly body: unknown;
46
+ readonly origin: string;
47
+ constructor(message: string, status: number, body: unknown, origin: string);
48
+ }
49
+ /** The `cert` object from a 201 exchange response. Carried verbatim; the CLI reads only the times. */
50
+ export type CertInfo = Record<string, unknown> & {
51
+ issuedAt?: string;
52
+ expiresAt?: string;
53
+ };
54
+ export interface OidcCertCredentialOptions {
55
+ source: OidcTokenSource;
56
+ agentId?: string;
57
+ /** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
58
+ refreshFraction?: number;
59
+ /** Diagnostics sink for --verbose. Never receives a token, cert or key. */
60
+ log?: (event: Record<string, unknown>) => void;
61
+ /** Injectable for tests. */
62
+ now?: () => number;
63
+ fetch?: typeof fetch;
64
+ userAgent?: string;
65
+ timeoutMs?: number;
66
+ }
67
+ /** Bounds on a token command. Mutable so tests can shorten the timeout. */
68
+ export declare const TOKEN_COMMAND_LIMITS: {
69
+ timeoutMs: number;
70
+ /** A JWT is a few KiB at most; anything past this is not one token. */
71
+ stdoutBytes: number;
72
+ };
73
+ /** Replace anything shaped like a JWT with a placeholder. Token command stderr
74
+ * and Server error bodies are surfaced to the user, and either can carry one. */
75
+ export declare function redactTokens(text: string): string;
76
+ /** Deep-copy a JSON value with every string passed through `redactTokens`,
77
+ * and any string equal to or containing `token` replaced. The Server's
78
+ * validation errors echo the offending input back, which for this route is
79
+ * the OIDC token. */
80
+ export declare function scrub(value: unknown, token?: string): unknown;
81
+ /** What a token is for, so a missing `sub` is explained in the right terms. */
82
+ export type TokenPurpose = 'cert-exchange' | 'delegation';
83
+ /** Call the token source once and return a validated compact JWT plus its `sub` and payload. */
84
+ export declare function fetchOidcToken(source: OidcTokenSource, purpose?: TokenPurpose): Promise<{
85
+ token: string;
86
+ sub: string;
87
+ payload: Record<string, unknown>;
88
+ }>;
89
+ /**
90
+ * One cert credential. Generates its key pair on construction, exchanges on
91
+ * first use, re-exchanges past the refresh point or when forced (a 401), and
92
+ * shares one in-flight exchange between concurrent callers.
93
+ */
94
+ export declare class OidcCertCredential {
95
+ readonly source: OidcTokenSource;
96
+ private readonly agentId;
97
+ private readonly refreshFraction;
98
+ private readonly log;
99
+ private readonly now;
100
+ private readonly fetchImpl;
101
+ private readonly userAgent;
102
+ private readonly timeoutMs;
103
+ private readonly privateKey;
104
+ private readonly publicKeyX;
105
+ private certJws;
106
+ private certInfo;
107
+ /** Local clock times, from when the cert was received: the Server's clock may differ. */
108
+ private refreshAt;
109
+ private expiresAt;
110
+ private inflight;
111
+ private exchanges;
112
+ constructor(options: OidcCertCredentialOptions);
113
+ /** The cert from the most recent exchange, as the Server returned it. */
114
+ get cert(): CertInfo | null;
115
+ /** How many exchanges this credential has performed. */
116
+ get exchangeCount(): number;
117
+ /**
118
+ * A bearer for the next request: the cached cert, or a fresh one when none
119
+ * is held or the refresh point has passed. Pass `rejected` (the bearer the
120
+ * Server just refused with 401) to force a re-exchange; when a concurrent
121
+ * request has already replaced that cert, the replacement is returned
122
+ * instead of exchanging again.
123
+ */
124
+ getToken(baseUrl: string, rejected?: string): Promise<string>;
125
+ /** The agent signature headers for a request body, over the exact bytes sent. */
126
+ signBody(body: string): Record<string, string>;
127
+ private exchange;
128
+ }
129
+ /**
130
+ * The delegation token for one invocation, read from its source on first use.
131
+ * Unlike the cert exchange, the Server never deduplicates a delegation token,
132
+ * so one is reused until shortly before its `exp` and then read again. A token
133
+ * with no `exp` is read again for every request, since nothing says how long
134
+ * it stays good.
135
+ */
136
+ export declare class DelegationToken {
137
+ readonly source: OidcTokenSource;
138
+ private readonly now;
139
+ private cached;
140
+ constructor(source: OidcTokenSource, now?: () => number);
141
+ /** The token to send. `reread` skips the cache: the Server just refused the last one. */
142
+ get(reread?: boolean): Promise<string>;
143
+ }