@agledger/cli 1.5.0 → 2.1.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 +102 -9
- package/SKILL.md +10 -8
- package/dist/api-client.js +1 -1
- package/dist/base.d.ts +40 -4
- package/dist/base.js +149 -27
- package/dist/commands/api.js +4 -3
- package/dist/commands/login.d.ts +1 -0
- package/dist/commands/login.js +7 -1
- package/dist/commands/logout.d.ts +2 -1
- package/dist/commands/logout.js +35 -11
- package/dist/commands/verify.d.ts +51 -1
- package/dist/commands/verify.js +335 -25
- package/dist/oidc.js +1 -1
- package/oclif.manifest.json +58 -11
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
The official CLI for the [AGLedger](https://agledger.ai) API: change control for AI agents. Agent memory, approvals, audit trail, and notifications: one API, one signed ledger, self-hosted.
|
|
4
4
|
|
|
5
|
+
Requires an AGLedger Server 2.0 or later. For a 1.x Server, use `npm i -g @agledger/cli@1.5.0`, the last release that supports it.
|
|
6
|
+
|
|
5
7
|
A **thin cover** over the API. The CLI passes your request straight through to the API and forwards the response: no hand-coded per-endpoint wrappers, no flag-to-body translation, no drift. Every AGLedger API route is reachable via `agledger api <METHOD> <path>`.
|
|
6
8
|
|
|
7
9
|
**Learn more**
|
|
@@ -94,17 +96,96 @@ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary=x
|
|
|
94
96
|
Reach for `-f` rather than quoting. Shell quotes that survive into the value
|
|
95
97
|
(`-F externalTaskId='"4821"'`) reach the Server as a string with the quote
|
|
96
98
|
characters inside it, and the Server accepts that: the Record is notarized,
|
|
97
|
-
signed and
|
|
99
|
+
signed and tamper-evident, with an identifier no other system will match.
|
|
100
|
+
|
|
101
|
+
## Verifying an export offline
|
|
102
|
+
|
|
103
|
+
`agledger verify` checks a Record's audit export with no network and no API
|
|
104
|
+
key: the hash chain, every COSE_Sign1 envelope signature (Ed25519 or ES256),
|
|
105
|
+
and the bindings between the signed bytes and the columns beside them.
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
# Save a Record's audit export
|
|
109
|
+
agledger api GET /v1/records/<record-id>/audit-export > audit-export.json
|
|
110
|
+
|
|
111
|
+
# Verify it against a vault key you pinned
|
|
112
|
+
agledger verify audit-export.json --trust-anchor sha256:<digest>
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The keys an export embeds, and the ones `GET /v1/verification-keys` serves,
|
|
116
|
+
come from the Server's database, so a key written into the database alone
|
|
117
|
+
would verify against them. `--trust-anchor` takes the SPKI digest of a vault
|
|
118
|
+
key you took out of band (the installer prints the first vault key's) and walks
|
|
119
|
+
the signed key statements the export carries from it:
|
|
120
|
+
|
|
121
|
+
- `PASS` means the chain verifies, every key is linked to your anchor, and at
|
|
122
|
+
least one signature verified under an anchored key.
|
|
123
|
+
- `VERIFIED, NOT ANCHORED` means nothing failed, but it is not a trusted
|
|
124
|
+
verdict. Either no `--trust-anchor` was given, so nothing links the keys to
|
|
125
|
+
one you trust (`keyTrust.status` is `no_anchor`), or the anchor was walked
|
|
126
|
+
but no signature verified under a key it anchors, as for an export of
|
|
127
|
+
unsigned history (`no_anchored_signature`). It exits 0, and `--json` output
|
|
128
|
+
carries `verdict: "unanchored"` for both. Treat it as unverified
|
|
129
|
+
provenance, not as a clean pass.
|
|
130
|
+
- `FAIL` exits 1. An entry signed by a key the walk does not reach is
|
|
131
|
+
`CHAIN_SIGNING_KEY_UNANCHORED`; a key statement that does not hold is
|
|
132
|
+
`KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`.
|
|
133
|
+
Those are listed under `keyTrust.findings`, and are `brokenAt` at position 0
|
|
134
|
+
only when the chain itself is intact; when the chain also breaks, `brokenAt`
|
|
135
|
+
is the chain failure.
|
|
136
|
+
|
|
137
|
+
`--distrusted-key sha256:<digest>[@<RFC 3339 instant>]` mirrors the operator's
|
|
138
|
+
`VAULT_DISTRUSTED_KEYS` and needs `--trust-anchor`: what such a key signed from
|
|
139
|
+
that instant counts for nothing, and a key statement it signed counts for
|
|
140
|
+
nothing at any instant, because the write times an export carries are not
|
|
141
|
+
signed. A dated `--distrusted-key` may name a key also given to
|
|
142
|
+
`--trust-anchor`, as the Server's key-compromise runbook does: the pin then
|
|
143
|
+
vouches for what the key signed before the instant. An export accounts for
|
|
144
|
+
nothing a distrusted key signed; such entries fail here, and only a full dump
|
|
145
|
+
verified with `@agledger/verify` lists them as accounted for. An API 2.0
|
|
146
|
+
export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with
|
|
147
|
+
`distrustedFrom`, the entry's instant, and where that instant is earlier than
|
|
148
|
+
the retirement the key's closures sign, lists the key retired at it. A run
|
|
149
|
+
not given the same entry still fails `CHAIN_KEY_WINDOW_DRIFT` on that window
|
|
150
|
+
(`KEY_CLOSURE_INVALID` where no closure retires the key), but the finding names
|
|
151
|
+
the entry, as `--distrusted-key sha256:<digest>@<distrustedFrom>`, and says so
|
|
152
|
+
when the entry you gave carries another instant; one at an earlier instant
|
|
153
|
+
draws no finding on the window and is a `Key note:`, though entries the key
|
|
154
|
+
signed after that instant still fail. The listing is the Server's unsigned word, so confirm the instant
|
|
155
|
+
with its operator before passing that entry. Findings and notes name the flags
|
|
156
|
+
in human and `--json` output alike. `--keys <file>` supplies
|
|
157
|
+
keys (a saved `GET /v1/verification-keys` response works as is, and its
|
|
158
|
+
statements are walked too), `--require-supplied-keys` refuses the export's
|
|
159
|
+
embedded keys, `--agent-keys <file>` re-verifies the agent signatures an
|
|
160
|
+
OIDC cert sealed on the chain, and `--federation-key <hubId>=<key>` re-verifies
|
|
161
|
+
the messages a federated peer signed and this Server sealed on its
|
|
162
|
+
`FEDERATION_*` entries (`payload.wire`), under the peer's federation key as its
|
|
163
|
+
operator gives it; a sealed message that does not hold fails
|
|
164
|
+
`CHAIN_FEDERATION_WIRE_INVALID`. After a peer changes its federation key,
|
|
165
|
+
`--federation-key-history <file>` (the JSON its
|
|
166
|
+
`GET /.well-known/agledger-federation-keys.json` serves) beside the
|
|
167
|
+
`--federation-key` for that hub trusts every key the history links to yours, so
|
|
168
|
+
the entries sealed before the change verify too. `--trust-anchor`, `--distrusted-key` and
|
|
169
|
+
`--federation-key` are given once per key. A malformed value, a distrusted key named twice,
|
|
170
|
+
`--distrusted-key` without `--trust-anchor`, a pinned key distrusted with no
|
|
171
|
+
instant (the Server refuses to start with that pair), and a
|
|
172
|
+
file that does not exist are each a usage error (exit 2), refused before the
|
|
173
|
+
export is read. A `--keys` file whose shape or key window (RFC 3339) is wrong
|
|
174
|
+
is `INVALID_FIELD`, exit 2. The flags,
|
|
175
|
+
these refusals and their messages, the headline words and the exit codes are
|
|
176
|
+
the same as `@agledger/verify`'s `agledger-verify` and the Python
|
|
177
|
+
`agledger-verify`'s, and `--json` output carries their `verdict` (`trusted`,
|
|
178
|
+
`unanchored` or `failed`).
|
|
98
179
|
|
|
99
180
|
## Agent-native DX
|
|
100
181
|
|
|
101
182
|
- `--json` on every command (auto when stdout is piped)
|
|
102
183
|
- `--quiet` suppresses output (exit code only)
|
|
103
184
|
- `--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
|
|
185
|
+
- `--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
186
|
- `--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
|
|
187
|
+
- 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
|
|
188
|
+
- 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
189
|
- 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
190
|
- `NO_COLOR` supported per [no-color.org](https://no-color.org)
|
|
110
191
|
|
|
@@ -124,10 +205,10 @@ agledger api GET /openapi.json # Full API route catalog
|
|
|
124
205
|
| `api` | Call any API endpoint |
|
|
125
206
|
| `discover` | Health + identity + scopes + quickstart |
|
|
126
207
|
| `login` | Verify an API key (or, with `--oidc`, an OIDC token source) and store it in `~/.agledger/config.json` (0600) |
|
|
127
|
-
| `logout` | Remove profile(
|
|
208
|
+
| `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
209
|
| `auth` | Check current login state and show the identity, including the OIDC cert (exit 0 when nothing is configured) |
|
|
129
210
|
| `config` | `list` / `get` / `use <profile>` / `path` |
|
|
130
|
-
| `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network). `--
|
|
211
|
+
| `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
212
|
| `docs` | Fetch the API's agent-oriented narrative (`llms.txt` / `--full`) |
|
|
132
213
|
| `list-commands` | Inventory (this list) |
|
|
133
214
|
| `help-json` | Per-command schema |
|
|
@@ -156,11 +237,22 @@ of an API key. The CLI runs a token source you name, exchanges the token at
|
|
|
156
237
|
that cert as the bearer. Your operator first registers the IdP as a trusted
|
|
157
238
|
issuer on the Server.
|
|
158
239
|
|
|
240
|
+
**The token decides which agent the cert binds to**, never the CLI. An
|
|
241
|
+
administrator binds an agent to the token's identity in one of two ways:
|
|
242
|
+
`PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's issuer and
|
|
243
|
+
subject), or a `claimMapping` of `agent_id` on the trusted issuer, which reads
|
|
244
|
+
the agent id from a claim in the token. An issuer that auto-provisions agents
|
|
245
|
+
creates one for an unbound subject instead. A token that binds no agent is
|
|
246
|
+
refused, and the Server's `recoveryHint` says which binding is missing. A
|
|
247
|
+
token bound to a federation shadow agent (one listed at `GET /v1/peer-agents`)
|
|
248
|
+
is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that agent authenticates on
|
|
249
|
+
its own Server.
|
|
250
|
+
|
|
159
251
|
| Variable | What it holds |
|
|
160
252
|
|---|---|
|
|
161
253
|
| `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
254
|
| `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.
|
|
255
|
+
| `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
256
|
|
|
165
257
|
```bash
|
|
166
258
|
unset AGLEDGER_API_KEY # an API key outranks a token source
|
|
@@ -204,8 +296,9 @@ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='e
|
|
|
204
296
|
|
|
205
297
|
**Credential precedence** (highest first), applied per command:
|
|
206
298
|
|
|
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
|
-
- **
|
|
299
|
+
- **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).
|
|
300
|
+
- **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.
|
|
301
|
+
- **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
302
|
|
|
210
303
|
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
304
|
|
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
|
|
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
|
|
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)
|
package/dist/api-client.js
CHANGED
|
@@ -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 =
|
|
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
|
|
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>;
|
|
@@ -97,6 +110,16 @@ export declare abstract class BaseCommand extends Command {
|
|
|
97
110
|
};
|
|
98
111
|
protected get isJson(): boolean;
|
|
99
112
|
protected get isQuiet(): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* oclif's own refusals (an unknown flag, a missing argument, a bad enum
|
|
115
|
+
* value) reach here before any command code runs. Under --quiet they exit
|
|
116
|
+
* as a usage error with nothing written, as every other error does; an
|
|
117
|
+
* explicit `this.exit(code)` passes through untouched, since it already
|
|
118
|
+
* carries the code the command chose.
|
|
119
|
+
*/
|
|
120
|
+
protected catch(err: Error & {
|
|
121
|
+
exitCode?: number;
|
|
122
|
+
}): Promise<unknown>;
|
|
100
123
|
/** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
|
|
101
124
|
protected verboseLog(flags: {
|
|
102
125
|
verbose?: boolean;
|
|
@@ -113,7 +136,8 @@ export declare abstract class BaseCommand extends Command {
|
|
|
113
136
|
*
|
|
114
137
|
* Explicit per-invocation sources outrank stored ones, which is the rule the
|
|
115
138
|
* API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
|
|
116
|
-
* stored agent id.
|
|
139
|
+
* stored agent id. That id is only an assertion sent on the exchange: the
|
|
140
|
+
* token decides the agent, and the Server refuses a mismatch.
|
|
117
141
|
*/
|
|
118
142
|
protected resolveCredential(flags: AuthFlags): {
|
|
119
143
|
credential: ResolvedCredential;
|
|
@@ -130,6 +154,12 @@ export declare abstract class BaseCommand extends Command {
|
|
|
130
154
|
protected createApiClient(flags: AuthFlags, options?: {
|
|
131
155
|
allowAnonymous?: boolean;
|
|
132
156
|
}): ApiClient;
|
|
157
|
+
/** Exit 3 when `--profile` names a profile that is not stored. */
|
|
158
|
+
protected requireNamedProfile(flags: {
|
|
159
|
+
profile?: string;
|
|
160
|
+
}, profile: Profile | undefined): void;
|
|
161
|
+
/** Refuse an API URL that is not an absolute http(s) URL, naming where it came from. */
|
|
162
|
+
protected requireUsableApiUrl(apiUrl: string, origin: string): void;
|
|
133
163
|
/** Build a cert credential for one invocation. Its key pair never leaves memory. */
|
|
134
164
|
protected oidcCredential(flags: {
|
|
135
165
|
verbose?: boolean;
|
|
@@ -180,7 +210,13 @@ export declare abstract class BaseCommand extends Command {
|
|
|
180
210
|
protected parseJsonInput(source: string, fieldName: string, suggestion?: string): unknown;
|
|
181
211
|
/** Read and parse a JSON file with structured errors. `-` reads from stdin. */
|
|
182
212
|
protected readJsonSource(path: string, fieldName: string, suggestion?: string): unknown;
|
|
183
|
-
protected failWith(code: string, message: string, exitCode: number, suggestion?: string): never;
|
|
213
|
+
protected failWith(code: string, message: string, exitCode: number, suggestion?: string, extra?: Record<string, unknown>): never;
|
|
214
|
+
/**
|
|
215
|
+
* The one place a structured error leaves the process. Under --quiet it
|
|
216
|
+
* leaves nothing: the flag promises exit code only, and a caller that
|
|
217
|
+
* asked for that reads the code, not a body it told the CLI not to write.
|
|
218
|
+
*/
|
|
219
|
+
private writeError;
|
|
184
220
|
/**
|
|
185
221
|
* Forward the full API error body to stderr verbatim. The API owns error
|
|
186
222
|
* guidance (code, message, suggestion, validationErrors, nextSteps); the CLI
|
package/dist/base.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* honors NO_COLOR via chalk's built-in detection, so no explicit check needed.
|
|
10
10
|
*/
|
|
11
11
|
import { readFileSync } from 'node:fs';
|
|
12
|
-
import { Command, Flags } from '@oclif/core';
|
|
12
|
+
import { Command, Errors, Flags } from '@oclif/core';
|
|
13
13
|
import { ApiClient } from './api-client.js';
|
|
14
14
|
import { DelegationToken, OIDC_ENV, ON_BEHALF_OF_ENV, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './oidc.js';
|
|
15
15
|
import { readConfig } from './util/config.js';
|
|
@@ -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
|
|
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 }),
|
|
@@ -139,6 +185,20 @@ export class BaseCommand extends Command {
|
|
|
139
185
|
get isQuiet() {
|
|
140
186
|
return process.argv.includes('--quiet');
|
|
141
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* oclif's own refusals (an unknown flag, a missing argument, a bad enum
|
|
190
|
+
* value) reach here before any command code runs. Under --quiet they exit
|
|
191
|
+
* as a usage error with nothing written, as every other error does; an
|
|
192
|
+
* explicit `this.exit(code)` passes through untouched, since it already
|
|
193
|
+
* carries the code the command chose.
|
|
194
|
+
*/
|
|
195
|
+
async catch(err) {
|
|
196
|
+
if (this.isQuiet && !(err instanceof Errors.ExitError)) {
|
|
197
|
+
const exit = err.oclif?.exit;
|
|
198
|
+
this.exit(typeof exit === 'number' ? exit : ExitCode.GENERAL_ERROR);
|
|
199
|
+
}
|
|
200
|
+
return super.catch(err);
|
|
201
|
+
}
|
|
142
202
|
/** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
|
|
143
203
|
verboseLog(flags, event) {
|
|
144
204
|
if (flags.verbose)
|
|
@@ -156,7 +216,8 @@ export class BaseCommand extends Command {
|
|
|
156
216
|
*
|
|
157
217
|
* Explicit per-invocation sources outrank stored ones, which is the rule the
|
|
158
218
|
* API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
|
|
159
|
-
* stored agent id.
|
|
219
|
+
* stored agent id. That id is only an assertion sent on the exchange: the
|
|
220
|
+
* token decides the agent, and the Server refuses a mismatch.
|
|
160
221
|
*/
|
|
161
222
|
resolveCredential(flags) {
|
|
162
223
|
const config = readConfig();
|
|
@@ -204,21 +265,15 @@ export class BaseCommand extends Command {
|
|
|
204
265
|
* AGLedger is self-hosted.
|
|
205
266
|
*/
|
|
206
267
|
createApiClient(flags, options) {
|
|
207
|
-
const { credential, profile } = this.resolveCredential(flags);
|
|
268
|
+
const { credential, profileName, profile } = this.resolveCredential(flags);
|
|
208
269
|
const flagUrl = flags['api-url'] || undefined;
|
|
209
|
-
// A profile is
|
|
210
|
-
//
|
|
211
|
-
//
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
-
}
|
|
270
|
+
// A --profile that names nothing is a mistake whatever else is set: an
|
|
271
|
+
// env key or --api-key would otherwise run the call as a credential the
|
|
272
|
+
// caller did not mean, with no sign that the profile was ignored.
|
|
273
|
+
this.requireNamedProfile(flags, profile);
|
|
274
|
+
// The URL is checked before the credential: without a usable URL there is
|
|
275
|
+
// no Server to authenticate to, so a missing or malformed one is the first
|
|
276
|
+
// thing to fix, and it is a configuration error (exit 2), not an auth one.
|
|
222
277
|
// No placeholder: a default of agledger.example.com resolved nowhere and
|
|
223
278
|
// turned a missing config into a DNS failure the user could not read.
|
|
224
279
|
// Every deployment is self-hosted, so there is no sane default.
|
|
@@ -226,7 +281,23 @@ export class BaseCommand extends Command {
|
|
|
226
281
|
if (!apiUrl) {
|
|
227
282
|
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
283
|
}
|
|
284
|
+
this.requireUsableApiUrl(apiUrl, apiUrlOrigin(flagUrl !== undefined, profileName));
|
|
285
|
+
// Discovery surfaces answer without auth, so a credential-less invocation
|
|
286
|
+
// proceeds anonymously rather than being refused before any request is
|
|
287
|
+
// made. The Server, not the CLI, decides what needs a key.
|
|
288
|
+
if (credential.kind === 'none' && !options?.allowAnonymous) {
|
|
289
|
+
this.failWith(ErrorCode.AUTH_REQUIRED, 'No credential configured.', ExitCode.AUTH_ERROR, CREDENTIAL_SOURCES);
|
|
290
|
+
}
|
|
229
291
|
this.lastApiUrl = apiUrl;
|
|
292
|
+
const timeoutRaw = process.env.AGLEDGER_TIMEOUT;
|
|
293
|
+
let timeoutMs;
|
|
294
|
+
if (timeoutRaw !== undefined) {
|
|
295
|
+
const problem = timeoutProblem(timeoutRaw);
|
|
296
|
+
if (problem) {
|
|
297
|
+
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.');
|
|
298
|
+
}
|
|
299
|
+
timeoutMs = Math.round(Number(timeoutRaw) * 1000);
|
|
300
|
+
}
|
|
230
301
|
const onBehalfOfSource = envOnBehalfOfSource();
|
|
231
302
|
this.verboseLog(flags, {
|
|
232
303
|
event: 'auth',
|
|
@@ -236,9 +307,22 @@ export class BaseCommand extends Command {
|
|
|
236
307
|
});
|
|
237
308
|
const onBehalfOf = onBehalfOfSource ? new DelegationToken(onBehalfOfSource) : null;
|
|
238
309
|
if (credential.kind === 'oidc') {
|
|
239
|
-
return new ApiClient(apiUrl, this.oidcCredential(flags, credential), this.config.version,
|
|
310
|
+
return new ApiClient(apiUrl, this.oidcCredential(flags, credential), this.config.version, timeoutMs, onBehalfOf);
|
|
311
|
+
}
|
|
312
|
+
return new ApiClient(apiUrl, credential.kind === 'api-key' ? credential.key : null, this.config.version, timeoutMs, onBehalfOf);
|
|
313
|
+
}
|
|
314
|
+
/** Exit 3 when `--profile` names a profile that is not stored. */
|
|
315
|
+
requireNamedProfile(flags, profile) {
|
|
316
|
+
if (flags.profile && !profile && !this.createsProfile) {
|
|
317
|
+
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.');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/** Refuse an API URL that is not an absolute http(s) URL, naming where it came from. */
|
|
321
|
+
requireUsableApiUrl(apiUrl, origin) {
|
|
322
|
+
const problem = apiUrlProblem(apiUrl);
|
|
323
|
+
if (problem) {
|
|
324
|
+
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
325
|
}
|
|
241
|
-
return new ApiClient(apiUrl, credential.kind === 'api-key' ? credential.key : null, this.config.version, undefined, onBehalfOf);
|
|
242
326
|
}
|
|
243
327
|
/** Build a cert credential for one invocation. Its key pair never leaves memory. */
|
|
244
328
|
oidcCredential(flags, credential) {
|
|
@@ -273,6 +357,7 @@ export class BaseCommand extends Command {
|
|
|
273
357
|
*/
|
|
274
358
|
resolvedAuth(flags) {
|
|
275
359
|
const { credential, profileName, profile } = this.resolveCredential(flags);
|
|
360
|
+
this.requireNamedProfile(flags, profile);
|
|
276
361
|
const flagUrl = flags['api-url'] || undefined;
|
|
277
362
|
// Null, not a placeholder. `agledger.example.com` was removed from
|
|
278
363
|
// `createApiClient`, which now refuses to build a client without a URL, but
|
|
@@ -281,6 +366,7 @@ export class BaseCommand extends Command {
|
|
|
281
366
|
// use: the unconfigured case printed agledger.example.com and exited 0
|
|
282
367
|
// while the same invocation without --dry-run exited 2 with CONFIG_ERROR.
|
|
283
368
|
const apiUrl = flagUrl ?? profile?.apiUrl ?? null;
|
|
369
|
+
const problem = apiUrl === null ? undefined : apiUrlProblem(apiUrl);
|
|
284
370
|
const mask = (k) => (k.length <= 4 ? '****' : `****${k.slice(-4)}`);
|
|
285
371
|
const source = credential.kind === 'none' ? 'none' : credential.from;
|
|
286
372
|
return {
|
|
@@ -296,6 +382,11 @@ export class BaseCommand extends Command {
|
|
|
296
382
|
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
383
|
}
|
|
298
384
|
: {}),
|
|
385
|
+
...(problem
|
|
386
|
+
? {
|
|
387
|
+
apiUrlSource: `unusable: the API URL from ${apiUrlOrigin(flagUrl !== undefined, profileName)} ${problem}, so this call would fail with CONFIG_ERROR (exit 2).`,
|
|
388
|
+
}
|
|
389
|
+
: {}),
|
|
299
390
|
...(source === 'profile' && profileName ? { profile: profileName } : {}),
|
|
300
391
|
};
|
|
301
392
|
}
|
|
@@ -316,7 +407,17 @@ export class BaseCommand extends Command {
|
|
|
316
407
|
// Same refusal a fresh client would give for a path that needs a credential.
|
|
317
408
|
this.createApiClient(flags, { allowAnonymous });
|
|
318
409
|
}
|
|
319
|
-
|
|
410
|
+
// The key is minted here rather than inside the client so the CLI knows it:
|
|
411
|
+
// a timeout must be able to say which key the lost request carried.
|
|
412
|
+
let sent = options;
|
|
413
|
+
this.sentIdempotencyKey = undefined;
|
|
414
|
+
if (method.toUpperCase() === 'POST') {
|
|
415
|
+
const idempotencyKey = options?.idempotencyKey ?? crypto.randomUUID();
|
|
416
|
+
sent = { ...options, idempotencyKey };
|
|
417
|
+
this.sentIdempotencyKey = idempotencyKey;
|
|
418
|
+
this.verboseLog(flags, { event: 'request', method: 'POST', path, idempotencyKey });
|
|
419
|
+
}
|
|
420
|
+
return this.client.request(method, path, sent);
|
|
320
421
|
}
|
|
321
422
|
output(data) {
|
|
322
423
|
if (this.isQuiet)
|
|
@@ -384,14 +485,26 @@ export class BaseCommand extends Command {
|
|
|
384
485
|
}
|
|
385
486
|
return this.parseJsonInput(content, path === '-' ? 'stdin' : `${fieldName} ${path}`, suggestion);
|
|
386
487
|
}
|
|
387
|
-
failWith(code, message, exitCode, suggestion) {
|
|
488
|
+
failWith(code, message, exitCode, suggestion, extra) {
|
|
388
489
|
const error = { error: true, code, message };
|
|
389
490
|
if (suggestion)
|
|
390
491
|
error.suggestion = suggestion;
|
|
391
|
-
|
|
492
|
+
if (extra)
|
|
493
|
+
Object.assign(error, extra);
|
|
494
|
+
this.writeError(error);
|
|
392
495
|
this.exit(exitCode);
|
|
393
496
|
throw new Error('unreachable');
|
|
394
497
|
}
|
|
498
|
+
/**
|
|
499
|
+
* The one place a structured error leaves the process. Under --quiet it
|
|
500
|
+
* leaves nothing: the flag promises exit code only, and a caller that
|
|
501
|
+
* asked for that reads the code, not a body it told the CLI not to write.
|
|
502
|
+
*/
|
|
503
|
+
writeError(error) {
|
|
504
|
+
if (this.isQuiet)
|
|
505
|
+
return;
|
|
506
|
+
process.stderr.write(JSON.stringify(error) + '\n');
|
|
507
|
+
}
|
|
395
508
|
/**
|
|
396
509
|
* Forward the full API error body to stderr verbatim. The API owns error
|
|
397
510
|
* guidance (code, message, suggestion, validationErrors, nextSteps); the CLI
|
|
@@ -401,7 +514,7 @@ export class BaseCommand extends Command {
|
|
|
401
514
|
const body = (response.body ?? {});
|
|
402
515
|
const exitCode = this.statusToExitCode(response.status);
|
|
403
516
|
const error = { error: true, ...body };
|
|
404
|
-
|
|
517
|
+
this.writeError(error);
|
|
405
518
|
this.exit(exitCode);
|
|
406
519
|
throw new Error('unreachable');
|
|
407
520
|
}
|
|
@@ -424,12 +537,15 @@ export class BaseCommand extends Command {
|
|
|
424
537
|
source: err.origin,
|
|
425
538
|
apiError: err.body,
|
|
426
539
|
};
|
|
427
|
-
|
|
540
|
+
this.writeError(error);
|
|
428
541
|
this.exit(this.statusToExitCode(err.status));
|
|
429
542
|
throw new Error('unreachable');
|
|
430
543
|
}
|
|
431
544
|
if (err instanceof DOMException && err.name === 'AbortError') {
|
|
432
|
-
|
|
545
|
+
const key = this.sentIdempotencyKey;
|
|
546
|
+
this.failWith(ErrorCode.TIMEOUT, 'Request timed out.', ExitCode.TIMEOUT, key
|
|
547
|
+
? `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).`
|
|
548
|
+
: '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
549
|
}
|
|
434
550
|
if (err instanceof TypeError && String(err.message).includes('fetch')) {
|
|
435
551
|
// "fetch failed" is undici's generic message: DNS failure, connection
|
|
@@ -440,11 +556,17 @@ export class BaseCommand extends Command {
|
|
|
440
556
|
const causeMessage = typeof cause?.message === 'string' ? cause.message : undefined;
|
|
441
557
|
const target = this.lastApiUrl ? ` connecting to ${this.lastApiUrl}` : '';
|
|
442
558
|
const detail = causeCode ?? causeMessage;
|
|
559
|
+
// Refused and unresolved connections never carried the request, so a
|
|
560
|
+
// retry cannot duplicate it. Anything else (a reset, a closed socket)
|
|
561
|
+
// may have dropped the connection after the Server had the body.
|
|
562
|
+
const key = causeCode === 'ENOTFOUND' || causeCode === 'ECONNREFUSED' ? undefined : this.sentIdempotencyKey;
|
|
443
563
|
this.failWith(ErrorCode.NETWORK_ERROR, `${String(err.message)}${target}${detail ? ` (${detail})` : ''}`, ExitCode.NETWORK_ERROR, causeCode === 'ENOTFOUND'
|
|
444
564
|
? 'The host does not resolve. Check the API URL for a typo, and that DNS can see it from here.'
|
|
445
565
|
: causeCode === 'ECONNREFUSED'
|
|
446
566
|
? 'The host resolved but refused the connection. Check the Server is running and the port is right.'
|
|
447
|
-
:
|
|
567
|
+
: key
|
|
568
|
+
? `The connection failed after the request may have been sent. ${retryWithKey(key)}`
|
|
569
|
+
: 'Check the API URL and that the Server is reachable from here.', key ? { idempotencyKey: key } : undefined);
|
|
448
570
|
}
|
|
449
571
|
this.failWith(ErrorCode.UNKNOWN_ERROR, err instanceof Error ? err.message : String(err), ExitCode.GENERAL_ERROR, 'Run `agledger api --help` to see usage.');
|
|
450
572
|
}
|