@agledger/cli 1.5.0 → 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.
package/README.md CHANGED
@@ -96,15 +96,86 @@ Reach for `-f` rather than quoting. Shell quotes that survive into the value
96
96
  characters inside it, and the Server accepts that: the Record is notarized,
97
97
  signed and immutable, with an identifier no other system will match.
98
98
 
99
+ ## Verifying an export offline
100
+
101
+ `agledger verify` checks a Record's audit export with no network and no API
102
+ key: the hash chain, every COSE_Sign1 envelope signature (Ed25519 or ES256),
103
+ and the bindings between the signed bytes and the columns beside them.
104
+
105
+ ```bash
106
+ # Save a Record's audit export
107
+ agledger api GET /v1/records/<record-id>/audit-export > audit-export.json
108
+
109
+ # Verify it against a vault key you pinned
110
+ agledger verify audit-export.json --trust-anchor sha256:<digest>
111
+ ```
112
+
113
+ The keys an export embeds, and the ones `GET /v1/verification-keys` serves,
114
+ come from the Server's database, so a key written into the database alone
115
+ would verify against them. `--trust-anchor` takes the SPKI digest of a vault
116
+ key you took out of band (the installer prints the first vault key's) and walks
117
+ the signed key statements the export carries from it:
118
+
119
+ - `PASS` means the chain verifies, every key is linked to your anchor, and at
120
+ least one signature verified under an anchored key.
121
+ - `VERIFIED, NOT ANCHORED` means nothing failed, but it is not a trusted
122
+ verdict. Either no `--trust-anchor` was given, so nothing links the keys to
123
+ one you trust (`keyTrust.status` is `no_anchor`), or the anchor was walked
124
+ but no signature verified under a key it anchors, as for an export of
125
+ unsigned history (`no_anchored_signature`). It exits 0, and `--json` output
126
+ carries `verdict: "unanchored"` for both. Treat it as unverified
127
+ provenance, not as a clean pass.
128
+ - `FAIL` exits 1. An entry signed by a key the walk does not reach is
129
+ `CHAIN_SIGNING_KEY_UNANCHORED`; a key statement that does not hold is
130
+ `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`.
131
+ Those are listed under `keyTrust.findings`, and are `brokenAt` at position 0
132
+ only when the chain itself is intact; when the chain also breaks, `brokenAt`
133
+ is the chain failure.
134
+
135
+ `--distrusted-key sha256:<digest>[@<RFC 3339 instant>]` mirrors the operator's
136
+ `VAULT_DISTRUSTED_KEYS` and needs `--trust-anchor`: what such a key signed from
137
+ that instant counts for nothing, and a key statement it signed counts for
138
+ nothing at any instant, because the write times an export carries are not
139
+ signed. A dated `--distrusted-key` may name a key also given to
140
+ `--trust-anchor`, as the Server's key-compromise runbook does: the pin then
141
+ vouches for what the key signed before the instant. An export accounts for
142
+ nothing a distrusted key signed; such entries fail here, and only a full dump
143
+ verified with `@agledger/verify` lists them as accounted for. An API 2.0
144
+ export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with
145
+ `distrustedFrom`, the entry's instant, and where that instant is earlier than
146
+ the retirement the key's closures sign, lists the key retired at it. A run
147
+ not given the same entry still fails `CHAIN_KEY_WINDOW_DRIFT` on that window
148
+ (`KEY_CLOSURE_INVALID` where no closure retires the key), but the finding names
149
+ the entry, as `--distrusted-key sha256:<digest>@<distrustedFrom>`, and says so
150
+ when the entry you gave carries another instant; one at an earlier instant
151
+ draws no finding on the window and is a `Key note:`, though entries the key
152
+ signed after that instant still fail. The listing is the Server's unsigned word, so confirm the instant
153
+ with its operator before passing that entry. Findings and notes name the flags
154
+ in human and `--json` output alike. `--keys <file>` supplies
155
+ keys (a saved `GET /v1/verification-keys` response works as is, and its
156
+ statements are walked too), `--require-supplied-keys` refuses the export's
157
+ embedded keys, and `--agent-keys <file>` re-verifies the agent signatures an
158
+ OIDC cert sealed on the chain. `--trust-anchor` and `--distrusted-key` are
159
+ given once per key. A malformed value, a distrusted key named twice,
160
+ `--distrusted-key` without `--trust-anchor`, a pinned key distrusted with no
161
+ instant (the Server refuses to start with that pair), and a
162
+ file that does not exist are each a usage error (exit 2), refused before the
163
+ export is read. A `--keys` file whose shape or key window (RFC 3339) is wrong
164
+ is `INVALID_FIELD`, exit 2. The flags,
165
+ these refusals and their messages, the headline words and the exit codes are
166
+ the same as `@agledger/verify`'s `agledger-verify` and the Python
167
+ `agledger-verify`'s, and `--json` output carries their `verdict` (`trusted`,
168
+ `unanchored` or `failed`).
169
+
99
170
  ## Agent-native DX
100
171
 
101
172
  - `--json` on every command (auto when stdout is piped)
102
173
  - `--quiet` suppresses output (exit code only)
103
174
  - `--dry-run` on `agledger api` shows the request without sending
104
- - `--verbose` on every command reports which credential was used, and each OIDC cert exchange, as JSON lines on stderr; it never prints a key, token or cert
175
+ - `--verbose` on every command reports which credential was used, and each OIDC cert exchange, as JSON lines on stderr; it never prints a key, token or cert. A POST also reports the `Idempotency-Key` it goes out under (`{"event":"request",...}`)
105
176
  - `--paginate` on GET follows cursor pagination and streams NDJSON
106
- - Every POST carries a generated `Idempotency-Key`, so one invocation is replay-safe on its own. Retrying a call that may already have reached the Server? Pass `--idempotency-key` with the first attempt's key and the Server replays the original result instead of recording the work twice
107
- - Structured errors on stderr: `{error: true, code, message, suggestion, ...}`; API errors pass through verbatim
177
+ - Every POST carries a generated `Idempotency-Key`, so one invocation is replay-safe on its own. Retrying a call that may already have reached the Server? Pass `--idempotency-key` with the first attempt's key and the Server replays the original result instead of recording the work twice. When a POST times out (exit 10, `TIMEOUT`) or its connection drops after the request went out (exit 9, `NETWORK_ERROR`), the error carries the key it sent as `idempotencyKey` and the suggestion is the rerun: `agledger api POST ... --idempotency-key <key>`. A plain rerun mints a new key and can record the work twice. A GET has no key, and neither does a connection that was refused or never resolved, since nothing was sent
178
+ - Structured errors on stderr: the CLI's own are `{error: true, code, message, suggestion, ...}`; an API error passes through verbatim as the Server's RFC 9457 body, whose human-readable text is `detail`
108
179
  - Semantic exit codes: 0 (OK), 1 (general), 2 (usage), 3 (auth), 4 (forbidden), 5 (not found), 6 (conflict), 7 (rate limit), 8 (server), 9 (network), 10 (timeout). **1 is the catch-all**: an API error whose status maps to nothing more specific (a 400, for example) exits 1, as does a chain that fails `agledger verify`. Read the `code` field on stderr to tell them apart, and treat any non-zero as failure rather than keying on 1 alone.
109
180
  - `NO_COLOR` supported per [no-color.org](https://no-color.org)
110
181
 
@@ -124,10 +195,10 @@ agledger api GET /openapi.json # Full API route catalog
124
195
  | `api` | Call any API endpoint |
125
196
  | `discover` | Health + identity + scopes + quickstart |
126
197
  | `login` | Verify an API key (or, with `--oidc`, an OIDC token source) and store it in `~/.agledger/config.json` (0600) |
127
- | `logout` | Remove profile(s) |
198
+ | `logout` | Remove the active profile, the one named by `--profile`, or all of them with `--all`; exits 2 `MISSING_INPUT` when there is no such profile to remove. Removing the active profile leaves none active (`activeProfile: null` in the output): pick another with `config use` |
128
199
  | `auth` | Check current login state and show the identity, including the OIDC cert (exit 0 when nothing is configured) |
129
200
  | `config` | `list` / `get` / `use <profile>` / `path` |
130
- | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network). `--agent-keys <file>` re-verifies the agent signatures sealed on the chain against the cert keys you supply |
201
+ | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network). `--trust-anchor sha256:<digest>` anchors the keys to one you pinned; see [Verifying an export offline](#verifying-an-export-offline) |
131
202
  | `docs` | Fetch the API's agent-oriented narrative (`llms.txt` / `--full`) |
132
203
  | `list-commands` | Inventory (this list) |
133
204
  | `help-json` | Per-command schema |
@@ -156,11 +227,22 @@ of an API key. The CLI runs a token source you name, exchanges the token at
156
227
  that cert as the bearer. Your operator first registers the IdP as a trusted
157
228
  issuer on the Server.
158
229
 
230
+ **The token decides which agent the cert binds to**, never the CLI. An
231
+ administrator binds an agent to the token's identity in one of two ways:
232
+ `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's issuer and
233
+ subject), or a `claimMapping` of `agent_id` on the trusted issuer, which reads
234
+ the agent id from a claim in the token. An issuer that auto-provisions agents
235
+ creates one for an unbound subject instead. A token that binds no agent is
236
+ refused, and the Server's `recoveryHint` says which binding is missing. A
237
+ token bound to a federation shadow agent (one listed at `GET /v1/peer-agents`)
238
+ is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that agent authenticates on
239
+ its own Server.
240
+
159
241
  | Variable | What it holds |
160
242
  |---|---|
161
243
  | `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT, run on every exchange: `gcloud auth print-identity-token`, `az account get-access-token`, `vault`, `kubectl create token`, or your own script |
162
244
  | `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, read on every exchange, such as a projected service-account token that Kubernetes rotates on disk. The Server exchanges each token once, so one file token serves one CLI run until the file rotates; for repeated runs, prefer a command that mints a new token |
163
- | `AGLEDGER_OIDC_AGENT_ID` | Optional. The agent the cert binds to, when the token does not map to one itself |
245
+ | `AGLEDGER_OIDC_AGENT_ID` | Optional. An assertion of the agent id the token binds to, sent on the exchange. It never chooses the agent: when it names a different one, or the token binds none, the Server refuses the exchange with 403 `CERT_AGENT_BINDING_MISMATCH` rather than issue a cert for an agent you did not expect. Leave it unset unless you want that check |
164
246
 
165
247
  ```bash
166
248
  unset AGLEDGER_API_KEY # an API key outranks a token source
@@ -204,8 +286,9 @@ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='e
204
286
 
205
287
  **Credential precedence** (highest first), applied per command:
206
288
 
207
- - **Credential:** `--api-key` flag → `AGLEDGER_API_KEY` env → `AGLEDGER_OIDC_TOKEN_CMD` → `AGLEDGER_OIDC_TOKEN_FILE` → stored profile (`--profile <name>`, else the active profile), whose API key or OIDC token source is used. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's stored agent id.
208
- - **API URL:** `--api-url` flag → `AGLEDGER_API_URL` env → stored profile URL. There is no default: AGLedger is self-hosted, so a call with no URL from any of those three sources exits 2 with `CONFIG_ERROR` rather than guessing a host.
289
+ - **Credential:** `--api-key` flag → `AGLEDGER_API_KEY` env → `AGLEDGER_OIDC_TOKEN_CMD` → `AGLEDGER_OIDC_TOKEN_FILE` → stored profile (`--profile <name>`, else the active profile), whose API key or OIDC token source is used. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's stored agent id (an assertion, as above).
290
+ - **Timeout:** `AGLEDGER_TIMEOUT`, in seconds (default 30), is how long each API response is awaited. It must be a positive number up to 2147483, or the call exits 2 `CONFIG_ERROR` naming the variable. A POST that times out may still have been applied: see the `idempotencyKey` its `TIMEOUT` error carries, above.
291
+ - **API URL:** `--api-url` flag → `AGLEDGER_API_URL` env → stored profile URL. There is no default: AGLedger is self-hosted, so a call with no URL from any of those three sources exits 2 with `CONFIG_ERROR` rather than guessing a host. A URL that is not an absolute `http` or `https` URL (`not-a-url`, or `localhost:3000` with no scheme) also exits 2 with `CONFIG_ERROR`, naming where it came from. The URL is checked before the credential, so a call with neither exits 2 `CONFIG_ERROR`, not 3 `AUTH_REQUIRED`. The one check that comes earlier is a `--profile` naming no stored profile, which exits 3 `AUTH_REQUIRED` and says the profile was not found, on every command but `login`, whose `--profile` names the profile it writes.
209
292
 
210
293
  So once you `agledger login`, plain `agledger api ...` calls authenticate from the stored profile with no flags or env. `--dry-run` echoes the resolved auth (URL, source, masked key, or the name of the OIDC token source, which it does not run) so you can confirm which credentials a call would use without sending it; when no URL is configured it reports `apiUrl: null` and names the error the real call would raise.
211
294
 
package/SKILL.md CHANGED
@@ -5,9 +5,9 @@ Thin cover over the AGLedger API. The CLI passes your call through to the API an
5
5
  ## Setup
6
6
  Credentials resolve per command with this precedence: `--api-key` flag > `AGLEDGER_API_KEY` env > `AGLEDGER_OIDC_TOKEN_CMD` > `AGLEDGER_OIDC_TOKEN_FILE` > stored profile (after `agledger login`). API URL: `--api-url` flag > `AGLEDGER_API_URL` env > stored profile URL.
7
7
 
8
- OIDC instead of an API key: set `AGLEDGER_OIDC_TOKEN_CMD` to a command that prints an OIDC JWT from your identity provider, or `AGLEDGER_OIDC_TOKEN_FILE` to a file holding one (optional `AGLEDGER_OIDC_AGENT_ID`). The CLI exchanges a fresh token for a short-lived cert on each invocation, signs request bodies with a key held only in memory, and re-exchanges on expiry or a 401. `agledger auth` shows the cert identity; `--verbose` names the credential source on stderr. Failures: `OIDC_TOKEN_SOURCE_FAILED` (exit 3, names the variable, carries the command's stderr) and `OIDC_EXCHANGE_FAILED` (forwards the Server error and its `recoveryHint`).
8
+ OIDC instead of an API key: set `AGLEDGER_OIDC_TOKEN_CMD` to a command that prints an OIDC JWT from your identity provider, or `AGLEDGER_OIDC_TOKEN_FILE` to a file holding one (optional `AGLEDGER_OIDC_AGENT_ID`, an assertion only: the token decides the agent, and a different id, or any id on a token bound to no agent, is 403 `CERT_AGENT_BINDING_MISMATCH`; bind the agent with `PATCH /v1/agents/{id}` and `oidcIss`/`oidcSub`, or `claimMapping.agent_id` on the trusted issuer). The CLI exchanges a fresh token for a short-lived cert on each invocation, signs request bodies with a key held only in memory, and re-exchanges on expiry or a 401. `agledger auth` shows the cert identity; `--verbose` names the credential source on stderr. Failures: `OIDC_TOKEN_SOURCE_FAILED` (exit 3, names the variable, carries the command's stderr) and `OIDC_EXCHANGE_FAILED` (forwards the Server error and its `recoveryHint`).
9
9
 
10
- **There is no default API URL, and it is not optional.** AGLedger is self-hosted, so the CLI has no server to guess. If none of those three sources supplies one, the command exits 2 with `CONFIG_ERROR` rather than calling a placeholder host.
10
+ **There is no default API URL, and it is not optional.** AGLedger is self-hosted, so the CLI has no server to guess. If none of those three sources supplies one, or the one it supplies is not an absolute `http(s)` URL, the command exits 2 with `CONFIG_ERROR` rather than calling a placeholder host. The URL is checked before the credential.
11
11
 
12
12
  ## Primary command: `agledger api`
13
13
  Call any API endpoint:
@@ -37,16 +37,18 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
37
37
  - `agledger api GET /openapi.json`: full API route catalog
38
38
 
39
39
  ## Offline audit verification
40
- - `agledger verify <audit-export.json>`: verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network, no API key. Exit 0 if valid, 1 if broken; `--json` for structured output; `--keys <file>` supplies keys out of band (merged over any embedded in the export); `--require-key-id <id>` rejects exports signed by an unexpected key; `--require-out-of-band-keys` refuses the export's own embedded keys for an independent audit.
40
+ - `agledger verify <audit-export.json> --trust-anchor sha256:<digest>`: verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network, no API key. `--trust-anchor` (repeatable) is the SPKI digest of a vault key taken out of band (the installer prints the first one); the signed key statements in the export are walked from it. Exit 0 if valid, 1 if broken, 2 on a usage error; `--json` for structured output, with `verdict` (`trusted`, `unanchored`, `failed`). `--distrusted-key sha256:<digest>[@<instant>]` (repeatable, needs `--trust-anchor`) mirrors the operator's `VAULT_DISTRUSTED_KEYS`; `--keys <file>` supplies keys (a saved `GET /v1/verification-keys` response works as is); `--require-key-id <id>` rejects exports signed by an unexpected key; `--require-supplied-keys` refuses the export's own embedded keys.
41
+
42
+ **Read the verdict, not just the exit code.** Without `--trust-anchor` a chain that verifies prints `VERIFIED, NOT ANCHORED`, exits 0, and its JSON carries `keyTrust.status: "no_anchor"`: the signatures were checked against keys nobody pinned, and a key written into the Server's database alone would pass. A run with `--trust-anchor` that verified no signature under an anchored key (unsigned history) is also `VERIFIED, NOT ANCHORED`, with `keyTrust.status: "no_anchored_signature"`. Both carry `verdict: "unanchored"`. Only `PASS` (`verdict: "trusted"`, `keyTrust.status: "walked"`) says the keys are linked to one you trust.
41
43
 
42
44
  **What verification proves:**
43
- - Every entry was signed by a key listed in the export (or supplied via `--keys`) at the moment the vault wrote it.
45
+ - Every entry was signed by a key listed in the export (or supplied via `--keys`) at the moment the vault wrote it, and, with `--trust-anchor`, that key is linked by signed key statements to the one you pinned (else `CHAIN_SIGNING_KEY_UNANCHORED`).
44
46
  - Payloads have not been altered since signing (SHA-256 recomputation matches the stored `payload_hash` over the signed COSE_Sign1 bytes).
45
47
  - The hash chain is contiguous: no entries were inserted, removed, or reordered between positions.
46
- - On failure, `brokenAt.code` is a canonical SCREAMING_SNAKE failure code (e.g. `CHAIN_HASH_MISMATCH`, `CHAIN_SIGNATURE_INVALID`).
48
+ - On failure, `brokenAt.code` is a canonical SCREAMING_SNAKE failure code (e.g. `CHAIN_HASH_MISMATCH`, `CHAIN_SIGNATURE_INVALID`, `CHAIN_SIGNING_KEY_UNANCHORED`, and `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID`, `CHAIN_KEY_WINDOW_DRIFT`, which are listed under `keyTrust.findings` and are `brokenAt` at position 0 only when the chain itself is intact). A `CHAIN_KEY_WINDOW_DRIFT` whose detail names a `--distrusted-key sha256:<digest>@<instant>` is the export saying the Server distrusts that key from that instant (`distrustedFrom`): its unsigned word, so confirm the instant with the operator before rerunning with that flag.
47
49
 
48
50
  **What verification does NOT prove:**
49
- - That the signing key is *legitimate*. Obtain the key out of band from `/.well-known/scitt-keys` on the issuing instance (or the `/v1/verification-keys` API) and pass it via `--keys --require-out-of-band-keys`.
51
+ - That the signing key is *legitimate* without `--trust-anchor`. `/v1/verification-keys` and `/.well-known/scitt-keys` are served from the same database; the export's `exportMetadata.anchoredFrom` is the Server's own claim. Pin a digest you took out of band.
50
52
  - That the export is *complete*. A vault operator can still truncate the export at either end.
51
53
  - That the *content* the payload describes actually happened. Payloads record what the agent notarized (declared intent and reported result); the verifier checks tamper-evidence, not whether the work occurred.
52
54
 
@@ -55,13 +57,13 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
55
57
  - `--quiet` for exit-code-only operation
56
58
  - `--dry-run` on `agledger api` shows the request without sending
57
59
  - `--paginate` on GET follows cursors, streams NDJSON
58
- - Structured errors on stderr: `{code, message, suggestion, ...}`
60
+ - Structured errors on stderr: the CLI's own are `{code, message, suggestion, ...}`; an API error is the Server's RFC 9457 body, verbatim, with its text in `detail`
59
61
  - Semantic exit codes (0-10)
60
62
 
61
63
  ## Credentials
62
64
  - `agledger login --api-key <key> [--profile NAME]`: verifies key, stores in `~/.agledger/config.json` (0600). After login, plain `agledger api ...` calls authenticate from the stored profile (no flag/env needed).
63
65
  - `agledger login --oidc --oidc-token-cmd <command> | --oidc-token-file <path> [--oidc-agent-id ID] [--profile NAME]`: stores the source (never a token, cert or key). A command is verified first with one exchange; a file is only checked to hold a JWT, since exchanging it would spend the token until the file rotates.
64
66
  - `agledger config use <profile>`: set the active profile; `agledger api ... --profile NAME` uses a specific one per-invocation.
65
- - `agledger logout [--profile NAME | --all]`
67
+ - `agledger logout [--profile NAME | --all]`: removes the active profile unless `--profile` names another; exits 2 `MISSING_INPUT` when there is no such profile (`--all` with nothing stored included). Removing the active profile leaves none active (`activeProfile: null`); choose another with `config use`
66
68
  - `agledger config list | get | use <profile> | path`
67
69
  - `agledger auth`: check login state and identity, including the OIDC cert (exit 0 when nothing is configured)
@@ -42,7 +42,7 @@ function appendQueryParam(search, key, value) {
42
42
  */
43
43
  export function classify401(body) {
44
44
  const b = (body ?? {});
45
- const text = [b.message, b.detail].filter((v) => typeof v === 'string').join(' ');
45
+ const text = typeof b.detail === 'string' ? b.detail : '';
46
46
  if (/x-agent-signature/i.test(text))
47
47
  return 'agent-signature';
48
48
  if (/on-behalf-of|delegation/i.test(text))
package/dist/base.d.ts CHANGED
@@ -38,8 +38,8 @@ export declare const ErrorCode: {
38
38
  readonly OIDC_TOKEN_SOURCE_FAILED: 'OIDC_TOKEN_SOURCE_FAILED';
39
39
  /** The Server refused `POST /v1/auth/oidc/cert`; its error body rides along as `apiError`. */
40
40
  readonly OIDC_EXCHANGE_FAILED: 'OIDC_EXCHANGE_FAILED';
41
- /** Required configuration (currently the API URL) is absent. Exits as a
42
- * usage error rather than claiming a new exit code. */
41
+ /** Required configuration (currently the API URL) is absent or unusable.
42
+ * Exits as a usage error rather than claiming a new exit code. */
43
43
  readonly CONFIG_ERROR: 'CONFIG_ERROR';
44
44
  readonly COMMAND_NOT_FOUND: 'COMMAND_NOT_FOUND';
45
45
  readonly MISSING_INPUT: 'MISSING_INPUT';
@@ -81,12 +81,25 @@ export declare function envOnBehalfOfSource(): OidcTokenSource | undefined;
81
81
  /** Whether a flag was passed on the command line (`--flag value` or `--flag=value`),
82
82
  * as opposed to reaching oclif through its `env` binding. */
83
83
  export declare function argvHasFlag(flag: string): boolean;
84
+ /**
85
+ * Why an API URL cannot be used, or undefined when it can. Only an absolute
86
+ * http(s) URL can be: `new URL` alone takes `localhost:3100` as a URL whose
87
+ * scheme is `localhost:`, which then fails at request time as a fetch error.
88
+ */
89
+ export declare function apiUrlProblem(url: string): string | undefined;
84
90
  export declare abstract class BaseCommand extends Command {
85
91
  /** The URL the most recent client was built for, so a network failure can
86
92
  * name the host it actually tried. */
87
93
  private lastApiUrl?;
88
94
  /** The client `callApi` built for this invocation, reused by every later call. */
89
95
  private client?;
96
+ /** True on a command whose --profile names the profile it is about to write
97
+ * (`login`), so a profile that does not exist yet is not an error there. */
98
+ protected readonly createsProfile: boolean;
99
+ /** The Idempotency-Key the most recent POST went out under, so a timeout or a
100
+ * dropped connection can hand it back for the retry. Undefined for any other
101
+ * method: the API ignores the header there, so there is no key to claim. */
102
+ private sentIdempotencyKey?;
90
103
  static baseFlags: {
91
104
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
92
105
  quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
@@ -113,7 +126,8 @@ export declare abstract class BaseCommand extends Command {
113
126
  *
114
127
  * Explicit per-invocation sources outrank stored ones, which is the rule the
115
128
  * API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
116
- * stored agent id.
129
+ * stored agent id. That id is only an assertion sent on the exchange: the
130
+ * token decides the agent, and the Server refuses a mismatch.
117
131
  */
118
132
  protected resolveCredential(flags: AuthFlags): {
119
133
  credential: ResolvedCredential;
@@ -130,6 +144,12 @@ export declare abstract class BaseCommand extends Command {
130
144
  protected createApiClient(flags: AuthFlags, options?: {
131
145
  allowAnonymous?: boolean;
132
146
  }): ApiClient;
147
+ /** Exit 3 when `--profile` names a profile that is not stored. */
148
+ protected requireNamedProfile(flags: {
149
+ profile?: string;
150
+ }, profile: Profile | undefined): void;
151
+ /** Refuse an API URL that is not an absolute http(s) URL, naming where it came from. */
152
+ protected requireUsableApiUrl(apiUrl: string, origin: string): void;
133
153
  /** Build a cert credential for one invocation. Its key pair never leaves memory. */
134
154
  protected oidcCredential(flags: {
135
155
  verbose?: boolean;
@@ -180,7 +200,7 @@ export declare abstract class BaseCommand extends Command {
180
200
  protected parseJsonInput(source: string, fieldName: string, suggestion?: string): unknown;
181
201
  /** Read and parse a JSON file with structured errors. `-` reads from stdin. */
182
202
  protected readJsonSource(path: string, fieldName: string, suggestion?: string): unknown;
183
- protected failWith(code: string, message: string, exitCode: number, suggestion?: string): never;
203
+ protected failWith(code: string, message: string, exitCode: number, suggestion?: string, extra?: Record<string, unknown>): never;
184
204
  /**
185
205
  * Forward the full API error body to stderr verbatim. The API owns error
186
206
  * guidance (code, message, suggestion, validationErrors, nextSteps); the CLI
package/dist/base.js CHANGED
@@ -38,8 +38,8 @@ export const ErrorCode = {
38
38
  OIDC_TOKEN_SOURCE_FAILED: 'OIDC_TOKEN_SOURCE_FAILED',
39
39
  /** The Server refused `POST /v1/auth/oidc/cert`; its error body rides along as `apiError`. */
40
40
  OIDC_EXCHANGE_FAILED: 'OIDC_EXCHANGE_FAILED',
41
- /** Required configuration (currently the API URL) is absent. Exits as a
42
- * usage error rather than claiming a new exit code. */
41
+ /** Required configuration (currently the API URL) is absent or unusable.
42
+ * Exits as a usage error rather than claiming a new exit code. */
43
43
  CONFIG_ERROR: 'CONFIG_ERROR',
44
44
  COMMAND_NOT_FOUND: 'COMMAND_NOT_FOUND',
45
45
  MISSING_INPUT: 'MISSING_INPUT',
@@ -108,6 +108,45 @@ export function envOnBehalfOfSource() {
108
108
  export function argvHasFlag(flag) {
109
109
  return process.argv.some((a) => a === flag || a.startsWith(`${flag}=`));
110
110
  }
111
+ /**
112
+ * Why an API URL cannot be used, or undefined when it can. Only an absolute
113
+ * http(s) URL can be: `new URL` alone takes `localhost:3100` as a URL whose
114
+ * scheme is `localhost:`, which then fails at request time as a fetch error.
115
+ */
116
+ export function apiUrlProblem(url) {
117
+ let parsed;
118
+ try {
119
+ parsed = new URL(url);
120
+ }
121
+ catch {
122
+ return 'is not a URL';
123
+ }
124
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
125
+ return `has scheme '${parsed.protocol}', and only http: and https: are supported`;
126
+ }
127
+ return undefined;
128
+ }
129
+ /** Where the API URL in use came from, for a CONFIG_ERROR that has to name it. */
130
+ function apiUrlOrigin(fromFlagOrEnv, profileName) {
131
+ if (!fromFlagOrEnv)
132
+ return `profile '${profileName ?? ''}' apiUrl`;
133
+ return argvHasFlag('--api-url') ? '--api-url' : 'AGLEDGER_API_URL';
134
+ }
135
+ /** The longest delay setTimeout takes; a larger one fires at once, which would time every call out. */
136
+ const MAX_TIMEOUT_SECONDS = 2_147_483;
137
+ /** Why `AGLEDGER_TIMEOUT` cannot be used, or undefined when it can. */
138
+ function timeoutProblem(raw) {
139
+ const seconds = raw.trim() === '' ? NaN : Number(raw);
140
+ if (!Number.isFinite(seconds) || seconds <= 0)
141
+ return 'is not a positive number of seconds';
142
+ if (seconds > MAX_TIMEOUT_SECONDS)
143
+ return `is more than ${MAX_TIMEOUT_SECONDS} seconds`;
144
+ return undefined;
145
+ }
146
+ /** The advice for a write whose outcome is unknown: replay it under the key it carried. */
147
+ function retryWithKey(key) {
148
+ return `Rerun the same command with --idempotency-key ${key}: the Server then replays the first attempt's result instead of recording the work twice, where a rerun without it mints a new key and can create a duplicate.`;
149
+ }
111
150
  function isPublicPath(method, path) {
112
151
  if (method.toUpperCase() !== 'GET')
113
152
  return false;
@@ -120,6 +159,13 @@ export class BaseCommand extends Command {
120
159
  lastApiUrl;
121
160
  /** The client `callApi` built for this invocation, reused by every later call. */
122
161
  client;
162
+ /** True on a command whose --profile names the profile it is about to write
163
+ * (`login`), so a profile that does not exist yet is not an error there. */
164
+ createsProfile = false;
165
+ /** The Idempotency-Key the most recent POST went out under, so a timeout or a
166
+ * dropped connection can hand it back for the retry. Undefined for any other
167
+ * method: the API ignores the header there, so there is no key to claim. */
168
+ sentIdempotencyKey;
123
169
  static baseFlags = {
124
170
  json: Flags.boolean({ description: 'Force JSON output (default when stdout is piped)', default: false }),
125
171
  quiet: Flags.boolean({ description: 'Suppress output (exit code only)', default: false }),
@@ -156,7 +202,8 @@ export class BaseCommand extends Command {
156
202
  *
157
203
  * Explicit per-invocation sources outrank stored ones, which is the rule the
158
204
  * API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
159
- * stored agent id.
205
+ * stored agent id. That id is only an assertion sent on the exchange: the
206
+ * token decides the agent, and the Server refuses a mismatch.
160
207
  */
161
208
  resolveCredential(flags) {
162
209
  const config = readConfig();
@@ -204,21 +251,15 @@ export class BaseCommand extends Command {
204
251
  * AGLedger is self-hosted.
205
252
  */
206
253
  createApiClient(flags, options) {
207
- const { credential, profile } = this.resolveCredential(flags);
254
+ const { credential, profileName, profile } = this.resolveCredential(flags);
208
255
  const flagUrl = flags['api-url'] || undefined;
209
- // A profile is only consulted when nothing more explicit supplied a
210
- // credential. If the caller explicitly named a missing profile AND has
211
- // nothing else to fall back on, that's an error worth surfacing (rather
212
- // than a generic no-credential one).
213
- if (flags.profile && !profile && credential.kind === 'none') {
214
- this.failWith(ErrorCode.AUTH_REQUIRED, `Profile '${flags.profile}' not found.`, ExitCode.AUTH_ERROR, 'Run `agledger config list` to see profiles, or `agledger login --profile <name>` to create one.');
215
- }
216
- // Discovery surfaces answer without auth, so a credential-less invocation
217
- // proceeds anonymously rather than being refused before any request is
218
- // made. The Server, not the CLI, decides what needs a key.
219
- if (credential.kind === 'none' && !options?.allowAnonymous) {
220
- this.failWith(ErrorCode.AUTH_REQUIRED, 'No credential configured.', ExitCode.AUTH_ERROR, CREDENTIAL_SOURCES);
221
- }
256
+ // A --profile that names nothing is a mistake whatever else is set: an
257
+ // env key or --api-key would otherwise run the call as a credential the
258
+ // caller did not mean, with no sign that the profile was ignored.
259
+ this.requireNamedProfile(flags, profile);
260
+ // The URL is checked before the credential: without a usable URL there is
261
+ // no Server to authenticate to, so a missing or malformed one is the first
262
+ // thing to fix, and it is a configuration error (exit 2), not an auth one.
222
263
  // No placeholder: a default of agledger.example.com resolved nowhere and
223
264
  // turned a missing config into a DNS failure the user could not read.
224
265
  // Every deployment is self-hosted, so there is no sane default.
@@ -226,7 +267,23 @@ export class BaseCommand extends Command {
226
267
  if (!apiUrl) {
227
268
  this.failWith(ErrorCode.CONFIG_ERROR, 'No API URL configured. AGLedger is self-hosted, so there is no default server to call.', ExitCode.USAGE_ERROR, 'Pass --api-url <url>, set AGLEDGER_API_URL, or run `agledger login --api-url <url> --api-key <key>`.');
228
269
  }
270
+ this.requireUsableApiUrl(apiUrl, apiUrlOrigin(flagUrl !== undefined, profileName));
271
+ // Discovery surfaces answer without auth, so a credential-less invocation
272
+ // proceeds anonymously rather than being refused before any request is
273
+ // made. The Server, not the CLI, decides what needs a key.
274
+ if (credential.kind === 'none' && !options?.allowAnonymous) {
275
+ this.failWith(ErrorCode.AUTH_REQUIRED, 'No credential configured.', ExitCode.AUTH_ERROR, CREDENTIAL_SOURCES);
276
+ }
229
277
  this.lastApiUrl = apiUrl;
278
+ const timeoutRaw = process.env.AGLEDGER_TIMEOUT;
279
+ let timeoutMs;
280
+ if (timeoutRaw !== undefined) {
281
+ const problem = timeoutProblem(timeoutRaw);
282
+ if (problem) {
283
+ this.failWith(ErrorCode.CONFIG_ERROR, `The timeout from AGLEDGER_TIMEOUT (${JSON.stringify(timeoutRaw)}) ${problem}.`, ExitCode.USAGE_ERROR, 'Give the seconds to wait for each API response, for example AGLEDGER_TIMEOUT=60.');
284
+ }
285
+ timeoutMs = Math.round(Number(timeoutRaw) * 1000);
286
+ }
230
287
  const onBehalfOfSource = envOnBehalfOfSource();
231
288
  this.verboseLog(flags, {
232
289
  event: 'auth',
@@ -236,9 +293,22 @@ export class BaseCommand extends Command {
236
293
  });
237
294
  const onBehalfOf = onBehalfOfSource ? new DelegationToken(onBehalfOfSource) : null;
238
295
  if (credential.kind === 'oidc') {
239
- return new ApiClient(apiUrl, this.oidcCredential(flags, credential), this.config.version, undefined, onBehalfOf);
296
+ return new ApiClient(apiUrl, this.oidcCredential(flags, credential), this.config.version, timeoutMs, onBehalfOf);
297
+ }
298
+ return new ApiClient(apiUrl, credential.kind === 'api-key' ? credential.key : null, this.config.version, timeoutMs, onBehalfOf);
299
+ }
300
+ /** Exit 3 when `--profile` names a profile that is not stored. */
301
+ requireNamedProfile(flags, profile) {
302
+ if (flags.profile && !profile && !this.createsProfile) {
303
+ this.failWith(ErrorCode.AUTH_REQUIRED, `Profile '${flags.profile}' not found.`, ExitCode.AUTH_ERROR, 'Run `agledger config list` to see profiles, or `agledger login --profile <name>` to create one.');
304
+ }
305
+ }
306
+ /** Refuse an API URL that is not an absolute http(s) URL, naming where it came from. */
307
+ requireUsableApiUrl(apiUrl, origin) {
308
+ const problem = apiUrlProblem(apiUrl);
309
+ if (problem) {
310
+ this.failWith(ErrorCode.CONFIG_ERROR, `The API URL from ${origin} (${JSON.stringify(apiUrl)}) ${problem}.`, ExitCode.USAGE_ERROR, 'Give the full base URL of your AGLedger Server, scheme included, for example https://agledger.internal or http://localhost:3000.');
240
311
  }
241
- return new ApiClient(apiUrl, credential.kind === 'api-key' ? credential.key : null, this.config.version, undefined, onBehalfOf);
242
312
  }
243
313
  /** Build a cert credential for one invocation. Its key pair never leaves memory. */
244
314
  oidcCredential(flags, credential) {
@@ -273,6 +343,7 @@ export class BaseCommand extends Command {
273
343
  */
274
344
  resolvedAuth(flags) {
275
345
  const { credential, profileName, profile } = this.resolveCredential(flags);
346
+ this.requireNamedProfile(flags, profile);
276
347
  const flagUrl = flags['api-url'] || undefined;
277
348
  // Null, not a placeholder. `agledger.example.com` was removed from
278
349
  // `createApiClient`, which now refuses to build a client without a URL, but
@@ -281,6 +352,7 @@ export class BaseCommand extends Command {
281
352
  // use: the unconfigured case printed agledger.example.com and exited 0
282
353
  // while the same invocation without --dry-run exited 2 with CONFIG_ERROR.
283
354
  const apiUrl = flagUrl ?? profile?.apiUrl ?? null;
355
+ const problem = apiUrl === null ? undefined : apiUrlProblem(apiUrl);
284
356
  const mask = (k) => (k.length <= 4 ? '****' : `****${k.slice(-4)}`);
285
357
  const source = credential.kind === 'none' ? 'none' : credential.from;
286
358
  return {
@@ -296,6 +368,11 @@ export class BaseCommand extends Command {
296
368
  apiUrlSource: 'unconfigured: this call would fail with CONFIG_ERROR (exit 2). Pass --api-url <url>, set AGLEDGER_API_URL, or run `agledger login --api-url <url> --api-key <key>`.',
297
369
  }
298
370
  : {}),
371
+ ...(problem
372
+ ? {
373
+ apiUrlSource: `unusable: the API URL from ${apiUrlOrigin(flagUrl !== undefined, profileName)} ${problem}, so this call would fail with CONFIG_ERROR (exit 2).`,
374
+ }
375
+ : {}),
299
376
  ...(source === 'profile' && profileName ? { profile: profileName } : {}),
300
377
  };
301
378
  }
@@ -316,7 +393,17 @@ export class BaseCommand extends Command {
316
393
  // Same refusal a fresh client would give for a path that needs a credential.
317
394
  this.createApiClient(flags, { allowAnonymous });
318
395
  }
319
- return this.client.request(method, path, options);
396
+ // The key is minted here rather than inside the client so the CLI knows it:
397
+ // a timeout must be able to say which key the lost request carried.
398
+ let sent = options;
399
+ this.sentIdempotencyKey = undefined;
400
+ if (method.toUpperCase() === 'POST') {
401
+ const idempotencyKey = options?.idempotencyKey ?? crypto.randomUUID();
402
+ sent = { ...options, idempotencyKey };
403
+ this.sentIdempotencyKey = idempotencyKey;
404
+ this.verboseLog(flags, { event: 'request', method: 'POST', path, idempotencyKey });
405
+ }
406
+ return this.client.request(method, path, sent);
320
407
  }
321
408
  output(data) {
322
409
  if (this.isQuiet)
@@ -384,10 +471,12 @@ export class BaseCommand extends Command {
384
471
  }
385
472
  return this.parseJsonInput(content, path === '-' ? 'stdin' : `${fieldName} ${path}`, suggestion);
386
473
  }
387
- failWith(code, message, exitCode, suggestion) {
474
+ failWith(code, message, exitCode, suggestion, extra) {
388
475
  const error = { error: true, code, message };
389
476
  if (suggestion)
390
477
  error.suggestion = suggestion;
478
+ if (extra)
479
+ Object.assign(error, extra);
391
480
  process.stderr.write(JSON.stringify(error) + '\n');
392
481
  this.exit(exitCode);
393
482
  throw new Error('unreachable');
@@ -429,7 +518,10 @@ export class BaseCommand extends Command {
429
518
  throw new Error('unreachable');
430
519
  }
431
520
  if (err instanceof DOMException && err.name === 'AbortError') {
432
- this.failWith(ErrorCode.TIMEOUT, 'Request timed out.', ExitCode.TIMEOUT, 'Retry the same command. If it persists, run `agledger discover` to check API connectivity.');
521
+ const key = this.sentIdempotencyKey;
522
+ this.failWith(ErrorCode.TIMEOUT, 'Request timed out.', ExitCode.TIMEOUT, key
523
+ ? `The Server may have processed the request before the timeout. ${retryWithKey(key)} If the instance is simply slow, raise the wait with AGLEDGER_TIMEOUT=<seconds> (default 30).`
524
+ : 'Retry the same command. If the instance is slow, raise the wait with AGLEDGER_TIMEOUT=<seconds> (default 30). If it persists, run `agledger discover` to check API connectivity.', key ? { idempotencyKey: key } : undefined);
433
525
  }
434
526
  if (err instanceof TypeError && String(err.message).includes('fetch')) {
435
527
  // "fetch failed" is undici's generic message: DNS failure, connection
@@ -440,11 +532,17 @@ export class BaseCommand extends Command {
440
532
  const causeMessage = typeof cause?.message === 'string' ? cause.message : undefined;
441
533
  const target = this.lastApiUrl ? ` connecting to ${this.lastApiUrl}` : '';
442
534
  const detail = causeCode ?? causeMessage;
535
+ // Refused and unresolved connections never carried the request, so a
536
+ // retry cannot duplicate it. Anything else (a reset, a closed socket)
537
+ // may have dropped the connection after the Server had the body.
538
+ const key = causeCode === 'ENOTFOUND' || causeCode === 'ECONNREFUSED' ? undefined : this.sentIdempotencyKey;
443
539
  this.failWith(ErrorCode.NETWORK_ERROR, `${String(err.message)}${target}${detail ? ` (${detail})` : ''}`, ExitCode.NETWORK_ERROR, causeCode === 'ENOTFOUND'
444
540
  ? 'The host does not resolve. Check the API URL for a typo, and that DNS can see it from here.'
445
541
  : causeCode === 'ECONNREFUSED'
446
542
  ? 'The host resolved but refused the connection. Check the Server is running and the port is right.'
447
- : 'Check the API URL and that the Server is reachable from here.');
543
+ : key
544
+ ? `The connection failed after the request may have been sent. ${retryWithKey(key)}`
545
+ : 'Check the API URL and that the Server is reachable from here.', key ? { idempotencyKey: key } : undefined);
448
546
  }
449
547
  this.failWith(ErrorCode.UNKNOWN_ERROR, err instanceof Error ? err.message : String(err), ExitCode.GENERAL_ERROR, 'Run `agledger api --help` to see usage.');
450
548
  }
@@ -19,7 +19,7 @@ export default class Api extends BaseCommand {
19
19
  'agledger api GET /v1/records -F status=ACTIVE -F limit=50',
20
20
  'agledger api POST /v1/records --data \'{"type":"notarize-generic-v1","criteria":{"summary":"..."}}\'',
21
21
  'agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary="summarize Q3 filings"',
22
- 'agledger api POST /v1/records -F type=notarize-generic-v1 -f externalTaskId=4821 # -f keeps a digit-only id a string',
22
+ 'agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary="file Q3 report" -f externalTaskId=4821 # -f keeps a digit-only id a string',
23
23
  'agledger api POST /v1/records --input payload.json',
24
24
  'cat payload.json | agledger api POST /v1/records --input -',
25
25
  'agledger api GET /v1/records --paginate # streams all pages as NDJSON',
@@ -60,7 +60,7 @@ export default class Api extends BaseCommand {
60
60
  default: false,
61
61
  }),
62
62
  'idempotency-key': Flags.string({
63
- description: 'Dedup key for POST, max 256 chars. One is generated per call, so pass this only when retrying a call that may already have reached the Server: reuse the first attempt\'s key and it replays the original result instead of creating a second record. Bound to method, route and body, so a retry with a changed body is rejected.',
63
+ description: 'Dedup key for POST, max 256 chars. One is generated per call and shown by --verbose, and a TIMEOUT or dropped-connection error carries it as `idempotencyKey`. Pass this only when retrying a call that may already have reached the Server: reuse the first attempt\'s key and it replays the original result instead of creating a second record, where a rerun without it can create a duplicate. Bound to method, route and body, so a retry with a changed body is rejected.',
64
64
  }),
65
65
  'dry-run': Flags.boolean({
66
66
  description: 'Show the request that would be sent without calling the API.',
@@ -109,7 +109,8 @@ export default class Api extends BaseCommand {
109
109
  path: args.path,
110
110
  ...options,
111
111
  // A generated key is minted inside the client at send time, so
112
- // printing a concrete UUID here would name one that never ships.
112
+ // printing a concrete UUID here would name one that never ships. The real
113
+ // one is shown by --verbose and carried by a TIMEOUT error.
113
114
  ...(method === 'POST' && options.idempotencyKey === undefined
114
115
  ? { idempotencyKey: '<generated at send time>' }
115
116
  : {}),
@@ -11,6 +11,7 @@ import { BaseCommand } from '../base.js';
11
11
  export default class Login extends BaseCommand {
12
12
  static description: string;
13
13
  static examples: string[];
14
+ protected readonly createsProfile = true;
14
15
  static flags: {
15
16
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
16
17
  quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
@@ -20,6 +20,8 @@ export default class Login extends BaseCommand {
20
20
  "<%= config.bin %> login --oidc --api-url https://agledger.internal --oidc-token-cmd 'gcloud auth print-identity-token --audiences=agledger'",
21
21
  '<%= config.bin %> login --oidc --api-url https://agledger.internal --oidc-token-file /var/run/secrets/tokens/agledger',
22
22
  ];
23
+ // --profile names the profile this login writes, so it need not exist yet.
24
+ createsProfile = true;
23
25
  static flags = {
24
26
  ...BaseCommand.baseFlags,
25
27
  profile: Flags.string({ description: 'Profile name', default: 'default' }),
@@ -36,7 +38,10 @@ export default class Login extends BaseCommand {
36
38
  env: OIDC_ENV.TOKEN_FILE,
37
39
  }),
38
40
  'oidc-agent-id': Flags.string({
39
- description: 'With --oidc: the agent the cert binds to, when the token does not map to one itself.',
41
+ description: 'With --oidc: an optional assertion of the agent id the token binds to. The token decides the agent, never this ' +
42
+ 'value: when it names a different agent, or the token binds none, the exchange fails 403 ' +
43
+ 'CERT_AGENT_BINDING_MISMATCH instead of issuing a cert. To bind an agent, an administrator sets oidcIss/oidcSub ' +
44
+ 'on it (PATCH /v1/agents/{id}) or maps an agent_id claim on the trusted issuer (claimMapping.agent_id).',
40
45
  env: OIDC_ENV.AGENT_ID,
41
46
  }),
42
47
  };
@@ -76,6 +81,7 @@ export default class Login extends BaseCommand {
76
81
  if (!apiUrl) {
77
82
  this.failWith(ErrorCode.CONFIG_ERROR, 'No API URL configured. AGLedger is self-hosted, so there is no default server to call.', ExitCode.USAGE_ERROR, 'Pass --api-url <url> or set AGLEDGER_API_URL.');
78
83
  }
84
+ this.requireUsableApiUrl(apiUrl, argvHasFlag('--api-url') ? '--api-url' : 'AGLEDGER_API_URL');
79
85
  // The command outranks the file, as it does at call time.
80
86
  const source = command
81
87
  ? { kind: 'command', command, origin: argvHasFlag('--oidc-token-cmd') ? '--oidc-token-cmd' : OIDC_ENV.TOKEN_CMD }
@@ -1,13 +1,14 @@
1
1
  import { BaseCommand } from '../base.js';
2
2
  export default class Logout extends BaseCommand {
3
3
  static description: string;
4
+ static examples: string[];
4
5
  static flags: {
5
6
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
6
7
  quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
7
8
  'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
9
  'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
10
  verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
10
- profile: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
11
+ profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
12
  all: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
13
  };
13
14
  run(): Promise<void>;
@@ -1,11 +1,16 @@
1
1
  import { Flags } from '@oclif/core';
2
- import { BaseCommand } from '../base.js';
2
+ import { BaseCommand, ErrorCode, ExitCode } from '../base.js';
3
3
  import { readConfig, writeConfig } from '../util/config.js';
4
4
  export default class Logout extends BaseCommand {
5
- static description = 'Remove a stored profile from ~/.agledger/config.json';
5
+ static description = 'Remove a stored profile from ~/.agledger/config.json: the active profile, the one named by --profile, or every profile with --all. Exits 2 when there is no such profile to remove. Removing the active profile leaves none active: pick another with `config use`.';
6
+ static examples = [
7
+ '<%= config.bin %> logout',
8
+ '<%= config.bin %> logout --profile prod',
9
+ '<%= config.bin %> logout --all',
10
+ ];
6
11
  static flags = {
7
12
  ...BaseCommand.baseFlags,
8
- profile: Flags.string({ description: 'Profile name to remove', default: 'default' }),
13
+ profile: Flags.string({ description: 'Profile name to remove (default: the active profile)' }),
9
14
  all: Flags.boolean({ description: 'Remove all profiles', default: false }),
10
15
  };
11
16
  async run() {
@@ -13,20 +18,39 @@ export default class Logout extends BaseCommand {
13
18
  const config = readConfig();
14
19
  if (flags.all) {
15
20
  const removed = Object.keys(config.profiles);
21
+ if (removed.length === 0) {
22
+ this.failWith(ErrorCode.MISSING_INPUT, 'No profiles are stored, so nothing was removed.', ExitCode.USAGE_ERROR, 'Run `agledger login` to store one.');
23
+ }
16
24
  writeConfig({ profiles: {} });
17
25
  this.output({ loggedOut: true, removedProfiles: removed });
18
26
  return;
19
27
  }
20
- if (!config.profiles[flags.profile]) {
21
- this.output({ loggedOut: false, message: `No profile '${flags.profile}' found.` });
22
- return;
28
+ // The profile a plain command authenticates with is the active one, so
29
+ // that is the one a plain logout removes. Removing nothing is an error,
30
+ // not a quiet success: the caller would otherwise stay logged in.
31
+ const name = flags.profile ?? config.activeProfile;
32
+ if (!name) {
33
+ this.failWith(ErrorCode.MISSING_INPUT, 'No active profile, so there is nothing to log out of.', ExitCode.USAGE_ERROR, 'Run `agledger config list` to see profiles, then `agledger logout --profile <name>`.');
23
34
  }
24
- delete config.profiles[flags.profile];
25
- if (config.activeProfile === flags.profile) {
26
- const remaining = Object.keys(config.profiles);
27
- config.activeProfile = remaining[0];
35
+ if (!config.profiles[name]) {
36
+ this.failWith(ErrorCode.MISSING_INPUT, `Profile '${name}' not found, so nothing was removed.`, ExitCode.USAGE_ERROR, 'Run `agledger config list` to see profiles.');
28
37
  }
38
+ delete config.profiles[name];
39
+ // Logging out the active profile leaves none active. Promoting whichever
40
+ // profile came first would quietly switch the next call to a different
41
+ // identity (an admin key, say), so the caller picks one with `config use`.
42
+ const wasActive = config.activeProfile === name;
43
+ if (wasActive)
44
+ delete config.activeProfile;
29
45
  writeConfig(config);
30
- this.output({ loggedOut: true, profile: flags.profile, activeProfile: config.activeProfile });
46
+ const remaining = Object.keys(config.profiles);
47
+ this.output({
48
+ loggedOut: true,
49
+ profile: name,
50
+ activeProfile: config.activeProfile ?? null,
51
+ ...(wasActive && remaining.length > 0
52
+ ? { note: `No profile is active now. Run \`agledger config use <name>\` to choose one of: ${remaining.join(', ')}.` }
53
+ : {}),
54
+ });
31
55
  }
32
56
  }
@@ -1,4 +1,13 @@
1
+ import { type VerifyExportResult } from '@agledger/verify-core';
1
2
  import { BaseCommand } from '../base.js';
3
+ /** One prose string from a result, its option names given as this command's flags. */
4
+ export declare function flagWording(text: string): string;
5
+ /**
6
+ * A result with its prose worded by {@link flagWording}: `brokenAt.detail`,
7
+ * each entry's detail, and the key-trust detail and each finding, note and
8
+ * accounted-for detail. Ids, digests and instants are data and pass through.
9
+ */
10
+ export declare function resultWithFlags(result: VerifyExportResult): VerifyExportResult;
2
11
  /**
3
12
  * Offline verification of a record audit export (format 2.0, COSE_Sign1).
4
13
  * Runs entirely offline: no network calls, no API key required. The
@@ -9,16 +18,21 @@ import { BaseCommand } from '../base.js';
9
18
  export default class Verify extends BaseCommand {
10
19
  static description: string;
11
20
  static examples: string[];
21
+ static usage: string;
12
22
  static args: {
13
- file: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
23
+ file: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
14
24
  };
15
25
  static flags: {
16
26
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
17
27
  quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
18
28
  keys: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
29
+ 'trust-anchor': import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
30
+ 'distrusted-key': import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
19
31
  'agent-keys': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
20
32
  'require-key-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
33
+ 'distrusted-keys': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
21
34
  'require-out-of-band-keys': import("@oclif/core/interfaces").BooleanFlag<boolean>;
35
+ 'require-supplied-keys': import("@oclif/core/interfaces").BooleanFlag<boolean>;
22
36
  };
23
37
  run(): Promise<void>;
24
38
  /**
@@ -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,27 +55,54 @@ 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',
16
61
  '<%= config.bin %> verify audit-export.json --agent-keys agent-jwks.json',
17
62
  '<%= config.bin %> verify audit-export.json --json',
18
63
  'cat audit-export.json | <%= config.bin %> verify -',
19
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]';
20
70
  static args = {
21
71
  file: Args.string({
22
72
  description: 'Path to the audit export JSON file (or "-" for stdin).',
23
- required: true,
24
73
  }),
25
74
  };
26
75
  static flags = {
27
76
  json: BaseCommand.baseFlags.json,
28
77
  quiet: BaseCommand.baseFlags.quiet,
29
78
  keys: Flags.string({
30
- 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 ' +
31
80
  '{keyId: SPKI-DER-base64} map, a [{keyId, publicKey, ...}] list, or the ' +
32
81
  'raw GET /v1/verification-keys response envelope ({data:[...], ...}, the ' +
33
- '.data array is unwrapped automatically). Merged over any keys embedded ' +
34
- '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.',
35
106
  }),
36
107
  'agent-keys': Flags.string({
37
108
  description: 'Path to a JSON file holding Ed25519 public keys of agent certs: a JWK, a list of JWKs, ' +
@@ -44,14 +115,69 @@ export default class Verify extends BaseCommand {
44
115
  description: 'Require every entry to reference this keyId. Rejects otherwise-valid exports ' +
45
116
  'signed by a retired or unexpected key.',
46
117
  }),
47
- 'require-out-of-band-keys': Flags.boolean({
48
- description: 'High-assurance: refuse keys embedded in the export. Verifying the engine against ' +
49
- '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.',
50
125
  default: false,
51
126
  }),
52
127
  };
53
128
  async run() {
54
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;
55
181
  const exportData = this.readJsonSource(args.file, 'audit export', 'Pass the path to an audit-export JSON file, or `-` to read it from stdin. ' +
56
182
  'Obtain one with `agledger api GET /v1/records/{id}/audit-export`.');
57
183
  if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
@@ -61,33 +187,37 @@ export default class Verify extends BaseCommand {
61
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 ' +
62
188
  '`agledger api GET /v1/verification-keys`.'))
63
189
  : undefined;
64
- const agentKeys = flags['agent-keys']
65
- ? 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.'))
66
- : undefined;
67
- // verify-core throws TypeError at the OOB-key boundary when the file's
68
- // shape is wrong (e.g. {keyId: 42}, [null], "..."). Catch it so the CLI
69
- // emits its structured-error envelope rather than oclif's raw exception
70
- // trace; agents parsing stderr need {code, message, suggestion}, not a
71
- // 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.
72
196
  let result;
73
197
  try {
74
198
  result = verifyAuditExport(exportData, {
75
199
  publicKeys,
76
200
  requireKeyId: flags['require-key-id'],
77
- requireOutOfBandKeys: flags['require-out-of-band-keys'],
201
+ requireSuppliedKeys: flags['require-supplied-keys'],
202
+ ...(trustAnchors.length > 0 ? { trustAnchors, distrustedKeys } : {}),
78
203
  agentKeys,
79
204
  });
80
205
  }
81
206
  catch (err) {
82
207
  if (err instanceof TypeError) {
83
- 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 ' +
84
- '{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); ' +
85
210
  'the --agent-keys file must hold Ed25519 JWKs ({"kty":"OKP","crv":"Ed25519","x":"..."}).');
86
211
  }
87
212
  throw err;
88
213
  }
214
+ // Findings, notes and suggestions name the flags, in JSON and text alike.
215
+ result = resultWithFlags(result);
89
216
  if (this.isJson) {
90
- 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 });
91
221
  }
92
222
  else {
93
223
  this.renderHuman(result, agentKeys !== undefined);
@@ -131,9 +261,49 @@ export default class Verify extends BaseCommand {
131
261
  if (this.isQuiet)
132
262
  return;
133
263
  const out = process.stdout;
134
- 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';
135
273
  out.write(`${icon} Record: ${result.recordId}\n`);
136
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
+ }
137
307
  // Agent signatures are checked only against keys the caller supplies, so
138
308
  // the lines below say exactly how many were, and the PASS line speaks for
139
309
  // the Server's signatures alone.
@@ -148,8 +318,16 @@ export default class Verify extends BaseCommand {
148
318
  else if (present > 0) {
149
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`);
150
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
+ }
151
325
  if (result.valid) {
152
- out.write(' Hash chain contiguous, every Server 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');
153
331
  return;
154
332
  }
155
333
  if (result.brokenAt) {
package/dist/oidc.js CHANGED
@@ -313,7 +313,7 @@ export class OidcCertCredential {
313
313
  }
314
314
  if (!res.ok) {
315
315
  const clean = scrub(parsed, token);
316
- const detail = typeof clean.detail === 'string' ? clean.detail : typeof clean.message === 'string' ? clean.message : '';
316
+ const detail = typeof clean.detail === 'string' ? clean.detail : '';
317
317
  // The Server exchanges a token id once. A token file returns the same
318
318
  // token until whatever writes it rotates it, so every CLI run after the
319
319
  // first lands here until then.
@@ -20,7 +20,7 @@
20
20
  "agledger api GET /v1/records -F status=ACTIVE -F limit=50",
21
21
  "agledger api POST /v1/records --data '{\"type\":\"notarize-generic-v1\",\"criteria\":{\"summary\":\"...\"}}'",
22
22
  "agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary=\"summarize Q3 filings\"",
23
- "agledger api POST /v1/records -F type=notarize-generic-v1 -f externalTaskId=4821 # -f keeps a digit-only id a string",
23
+ "agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary=\"file Q3 report\" -f externalTaskId=4821 # -f keeps a digit-only id a string",
24
24
  "agledger api POST /v1/records --input payload.json",
25
25
  "cat payload.json | agledger api POST /v1/records --input -",
26
26
  "agledger api GET /v1/records --paginate # streams all pages as NDJSON"
@@ -111,7 +111,7 @@
111
111
  "type": "boolean"
112
112
  },
113
113
  "idempotency-key": {
114
- "description": "Dedup key for POST, max 256 chars. One is generated per call, so pass this only when retrying a call that may already have reached the Server: reuse the first attempt's key and it replays the original result instead of creating a second record. Bound to method, route and body, so a retry with a changed body is rejected.",
114
+ "description": "Dedup key for POST, max 256 chars. One is generated per call and shown by --verbose, and a TIMEOUT or dropped-connection error carries it as `idempotencyKey`. Pass this only when retrying a call that may already have reached the Server: reuse the first attempt's key and it replays the original result instead of creating a second record, where a rerun without it can create a duplicate. Bound to method, route and body, so a retry with a changed body is rejected.",
115
115
  "name": "idempotency-key",
116
116
  "hasDynamicHelp": false,
117
117
  "multiple": false,
@@ -626,7 +626,7 @@
626
626
  "type": "option"
627
627
  },
628
628
  "oidc-agent-id": {
629
- "description": "With --oidc: the agent the cert binds to, when the token does not map to one itself.",
629
+ "description": "With --oidc: an optional assertion of the agent id the token binds to. The token decides the agent, never this value: when it names a different agent, or the token binds none, the exchange fails 403 CERT_AGENT_BINDING_MISMATCH instead of issuing a cert. To bind an agent, an administrator sets oidcIss/oidcSub on it (PATCH /v1/agents/{id}) or maps an agent_id claim on the trusted issuer (claimMapping.agent_id).",
630
630
  "env": "AGLEDGER_OIDC_AGENT_ID",
631
631
  "name": "oidc-agent-id",
632
632
  "hasDynamicHelp": false,
@@ -652,7 +652,12 @@
652
652
  "logout": {
653
653
  "aliases": [],
654
654
  "args": {},
655
- "description": "Remove a stored profile from ~/.agledger/config.json",
655
+ "description": "Remove a stored profile from ~/.agledger/config.json: the active profile, the one named by --profile, or every profile with --all. Exits 2 when there is no such profile to remove. Removing the active profile leaves none active: pick another with `config use`.",
656
+ "examples": [
657
+ "<%= config.bin %> logout",
658
+ "<%= config.bin %> logout --profile prod",
659
+ "<%= config.bin %> logout --all"
660
+ ],
656
661
  "flags": {
657
662
  "json": {
658
663
  "description": "Force JSON output (default when stdout is piped)",
@@ -683,9 +688,8 @@
683
688
  "type": "option"
684
689
  },
685
690
  "profile": {
686
- "description": "Profile name to remove",
691
+ "description": "Profile name to remove (default: the active profile)",
687
692
  "name": "profile",
688
- "default": "default",
689
693
  "hasDynamicHelp": false,
690
694
  "multiple": false,
691
695
  "type": "option"
@@ -723,12 +727,12 @@
723
727
  "args": {
724
728
  "file": {
725
729
  "description": "Path to the audit export JSON file (or \"-\" for stdin).",
726
- "name": "file",
727
- "required": true
730
+ "name": "file"
728
731
  }
729
732
  },
730
733
  "description": "Verify a record audit export offline (COSE_Sign1 envelope, RFC 9052; Ed25519 or ES256).",
731
734
  "examples": [
735
+ "<%= config.bin %> verify audit-export.json --trust-anchor sha256:<64 hex>",
732
736
  "<%= config.bin %> verify audit-export.json",
733
737
  "<%= config.bin %> verify audit-export.json --keys vault-keys.json",
734
738
  "<%= config.bin %> verify audit-export.json --agent-keys agent-jwks.json",
@@ -778,12 +782,26 @@
778
782
  "type": "boolean"
779
783
  },
780
784
  "keys": {
781
- "description": "Path to a JSON file holding out-of-band public keys. Accepts a {keyId: SPKI-DER-base64} map, a [{keyId, publicKey, ...}] list, or the raw GET /v1/verification-keys response envelope ({data:[...], ...}, the .data array is unwrapped automatically). Merged over any keys embedded in the export.",
785
+ "description": "Path to a JSON file holding public keys you supply. Accepts a {keyId: SPKI-DER-base64} map, a [{keyId, publicKey, ...}] list, or the raw GET /v1/verification-keys response envelope ({data:[...], ...}, the .data array is unwrapped automatically, and each key's signed statements are walked with --trust-anchor). Merged over any keys embedded in the export. Where a key came from is not whether it is trusted: that is --trust-anchor.",
782
786
  "name": "keys",
783
787
  "hasDynamicHelp": false,
784
788
  "multiple": false,
785
789
  "type": "option"
786
790
  },
791
+ "trust-anchor": {
792
+ "description": "sha256:<64 hex> SPKI digest of a vault key you took out of band (the installer prints the first vault key's; the Server's signing-key-digest.js derives one from any key you hold). The signed key statements the export carries are walked from it: an entry signed by a key the walk does not reach fails CHAIN_SIGNING_KEY_UNANCHORED, and a statement that does not hold fails KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID or CHAIN_KEY_WINDOW_DRIFT. Without one, a pass rests on keys nobody pinned. Repeatable.",
793
+ "name": "trust-anchor",
794
+ "hasDynamicHelp": false,
795
+ "multiple": true,
796
+ "type": "option"
797
+ },
798
+ "distrusted-key": {
799
+ "description": "sha256:<64 hex>, optionally @<RFC 3339 instant>: a key the operator distrusts, as in the Server's VAULT_DISTRUSTED_KEYS. What it signed from that instant (with none, from its retirement) counts for nothing in the walk. Requires --trust-anchor. A dated entry may name a key also given to --trust-anchor, which then vouches for what it signed before the instant. Where an export lists a key retired at the instant the Server distrusts it from (distrustedFrom), earlier than its signed retirement, a run without the same entry fails on that window, and the finding names the --distrusted-key to confirm with the Server's operator. Repeatable.",
800
+ "name": "distrusted-key",
801
+ "hasDynamicHelp": false,
802
+ "multiple": true,
803
+ "type": "option"
804
+ },
787
805
  "agent-keys": {
788
806
  "description": "Path to a JSON file holding Ed25519 public keys of agent certs: a JWK, a list of JWKs, or a {keys:[...]} JWK Set (an entry may wrap its key as {publicKeyJwk:{...}}). Each is the publicKeyJwk an agent sent at cert exchange (also the cnf.jwk claim in its certJws). An entry whose sealed agent signature names one of them by thumbprint has that signature re-verified offline, and fails CHAIN_AGENT_SIGNATURE_INVALID if it does not verify.",
789
807
  "name": "agent-keys",
@@ -798,11 +816,24 @@
798
816
  "multiple": false,
799
817
  "type": "option"
800
818
  },
819
+ "distrusted-keys": {
820
+ "hidden": true,
821
+ "name": "distrusted-keys",
822
+ "hasDynamicHelp": false,
823
+ "multiple": false,
824
+ "type": "option"
825
+ },
801
826
  "require-out-of-band-keys": {
802
- "description": "High-assurance: refuse keys embedded in the export. Verifying the engine against its own embedded key is not an independent audit, so supply keys via --keys instead.",
827
+ "hidden": true,
803
828
  "name": "require-out-of-band-keys",
804
829
  "allowNo": false,
805
830
  "type": "boolean"
831
+ },
832
+ "require-supplied-keys": {
833
+ "description": "Refuse keys embedded in the export: an entry whose only key is export-embedded fails CHAIN_KEY_POLICY_VIOLATION, so every signature is checked against a key from --keys.",
834
+ "name": "require-supplied-keys",
835
+ "allowNo": false,
836
+ "type": "boolean"
806
837
  }
807
838
  },
808
839
  "hasDynamicHelp": false,
@@ -812,6 +843,7 @@
812
843
  "pluginName": "@agledger/cli",
813
844
  "pluginType": "core",
814
845
  "strict": true,
846
+ "usage": "verify FILE [--trust-anchor <value>...] [--distrusted-key <value>...] [--keys <value>] [--agent-keys <value>] [--require-key-id <value>] [--require-supplied-keys] [--json] [--quiet]",
815
847
  "enableJsonFlag": false,
816
848
  "isESM": true,
817
849
  "relativePath": [
@@ -821,5 +853,5 @@
821
853
  ]
822
854
  }
823
855
  },
824
- "version": "1.5.0"
856
+ "version": "2.0.0"
825
857
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agledger/cli",
3
- "version": "1.5.0",
3
+ "version": "2.0.0",
4
4
  "description": "AGLedger CLI: developer and agent interface for AGLedger",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -31,7 +31,7 @@
31
31
  "prepublishOnly": "npm run build && npm run lint:pkg"
32
32
  },
33
33
  "dependencies": {
34
- "@agledger/verify-core": "^1.5.0",
34
+ "@agledger/verify-core": "^2.0.0",
35
35
  "@oclif/core": "^5.0.0"
36
36
  },
37
37
  "devDependencies": {