@agledger/cli 1.4.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +10 -14
- package/README.md +162 -16
- package/SKILL.md +14 -9
- package/dist/api-client.d.ts +24 -5
- package/dist/api-client.js +85 -16
- package/dist/base.d.ts +106 -31
- package/dist/base.js +299 -41
- package/dist/commands/api.d.ts +1 -0
- package/dist/commands/api.js +4 -3
- package/dist/commands/auth.d.ts +6 -2
- package/dist/commands/auth.js +20 -10
- package/dist/commands/config.d.ts +1 -0
- package/dist/commands/config.js +17 -1
- package/dist/commands/discover.d.ts +1 -0
- package/dist/commands/discover.js +5 -1
- package/dist/commands/docs.d.ts +1 -0
- package/dist/commands/docs.js +7 -1
- package/dist/commands/help-json.d.ts +1 -0
- package/dist/commands/list-commands.d.ts +1 -0
- package/dist/commands/login.d.ts +16 -3
- package/dist/commands/login.js +121 -10
- package/dist/commands/logout.d.ts +3 -1
- package/dist/commands/logout.js +35 -11
- package/dist/commands/verify.d.ts +22 -1
- package/dist/commands/verify.js +241 -21
- package/dist/oidc.d.ts +143 -0
- package/dist/oidc.js +384 -0
- package/dist/util/config.d.ts +13 -1
- package/oclif.manifest.json +147 -12
- package/package.json +2 -2
package/dist/base.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { readFileSync } from 'node:fs';
|
|
12
12
|
import { Command, Flags } from '@oclif/core';
|
|
13
13
|
import { ApiClient } from './api-client.js';
|
|
14
|
+
import { DelegationToken, OIDC_ENV, ON_BEHALF_OF_ENV, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './oidc.js';
|
|
14
15
|
import { readConfig } from './util/config.js';
|
|
15
16
|
/** Semantic exit codes for agent consumption. Stable across releases. */
|
|
16
17
|
export const ExitCode = {
|
|
@@ -33,8 +34,12 @@ export const ExitCode = {
|
|
|
33
34
|
*/
|
|
34
35
|
export const ErrorCode = {
|
|
35
36
|
AUTH_REQUIRED: 'AUTH_REQUIRED',
|
|
36
|
-
/**
|
|
37
|
-
|
|
37
|
+
/** The OIDC token command or file could not produce a token. */
|
|
38
|
+
OIDC_TOKEN_SOURCE_FAILED: 'OIDC_TOKEN_SOURCE_FAILED',
|
|
39
|
+
/** The Server refused `POST /v1/auth/oidc/cert`; its error body rides along as `apiError`. */
|
|
40
|
+
OIDC_EXCHANGE_FAILED: 'OIDC_EXCHANGE_FAILED',
|
|
41
|
+
/** Required configuration (currently the API URL) is absent or unusable.
|
|
42
|
+
* Exits as a usage error rather than claiming a new exit code. */
|
|
38
43
|
CONFIG_ERROR: 'CONFIG_ERROR',
|
|
39
44
|
COMMAND_NOT_FOUND: 'COMMAND_NOT_FOUND',
|
|
40
45
|
MISSING_INPUT: 'MISSING_INPUT',
|
|
@@ -65,6 +70,83 @@ const PUBLIC_GET_PATHS = new Set([
|
|
|
65
70
|
'/docs',
|
|
66
71
|
'/v1/conformance',
|
|
67
72
|
]);
|
|
73
|
+
/** The credential sources, in the order they are tried, for a no-credential error. */
|
|
74
|
+
const CREDENTIAL_SOURCES = 'Set AGLEDGER_API_KEY (or pass --api-key), set AGLEDGER_OIDC_TOKEN_CMD to a command that prints an OIDC token, set AGLEDGER_OIDC_TOKEN_FILE to a file holding one, or run `agledger login`.';
|
|
75
|
+
/** The OIDC token source stored on a profile, if it has one. */
|
|
76
|
+
export function profileOidcSource(name, profile) {
|
|
77
|
+
const oidc = profile?.oidc;
|
|
78
|
+
if (oidc?.tokenCommand) {
|
|
79
|
+
return { kind: 'command', command: oidc.tokenCommand, origin: `profile '${name}' oidc.tokenCommand` };
|
|
80
|
+
}
|
|
81
|
+
if (oidc?.tokenFile) {
|
|
82
|
+
return { kind: 'file', path: oidc.tokenFile, origin: `profile '${name}' oidc.tokenFile` };
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
/** The OIDC token source named by the environment: the command outranks the file. */
|
|
87
|
+
export function envOidcSource() {
|
|
88
|
+
const command = process.env[OIDC_ENV.TOKEN_CMD];
|
|
89
|
+
if (command)
|
|
90
|
+
return { kind: 'command', command, origin: OIDC_ENV.TOKEN_CMD };
|
|
91
|
+
const path = process.env[OIDC_ENV.TOKEN_FILE];
|
|
92
|
+
if (path)
|
|
93
|
+
return { kind: 'file', path, origin: OIDC_ENV.TOKEN_FILE };
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
/** The delegation token source from the environment. The command wins over the file. */
|
|
97
|
+
export function envOnBehalfOfSource() {
|
|
98
|
+
const command = process.env[ON_BEHALF_OF_ENV.CMD];
|
|
99
|
+
if (command)
|
|
100
|
+
return { kind: 'command', command, origin: ON_BEHALF_OF_ENV.CMD };
|
|
101
|
+
const path = process.env[ON_BEHALF_OF_ENV.FILE];
|
|
102
|
+
if (path)
|
|
103
|
+
return { kind: 'file', path, origin: ON_BEHALF_OF_ENV.FILE };
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
/** Whether a flag was passed on the command line (`--flag value` or `--flag=value`),
|
|
107
|
+
* as opposed to reaching oclif through its `env` binding. */
|
|
108
|
+
export function argvHasFlag(flag) {
|
|
109
|
+
return process.argv.some((a) => a === flag || a.startsWith(`${flag}=`));
|
|
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
|
+
}
|
|
68
150
|
function isPublicPath(method, path) {
|
|
69
151
|
if (method.toUpperCase() !== 'GET')
|
|
70
152
|
return false;
|
|
@@ -75,6 +157,15 @@ export class BaseCommand extends Command {
|
|
|
75
157
|
/** The URL the most recent client was built for, so a network failure can
|
|
76
158
|
* name the host it actually tried. */
|
|
77
159
|
lastApiUrl;
|
|
160
|
+
/** The client `callApi` built for this invocation, reused by every later call. */
|
|
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;
|
|
78
169
|
static baseFlags = {
|
|
79
170
|
json: Flags.boolean({ description: 'Force JSON output (default when stdout is piped)', default: false }),
|
|
80
171
|
quiet: Flags.boolean({ description: 'Suppress output (exit code only)', default: false }),
|
|
@@ -83,6 +174,10 @@ export class BaseCommand extends Command {
|
|
|
83
174
|
profile: Flags.string({
|
|
84
175
|
description: 'Stored profile to use for credentials (falls back to the active profile)',
|
|
85
176
|
}),
|
|
177
|
+
verbose: Flags.boolean({
|
|
178
|
+
description: 'Report which credential was used, and each OIDC cert exchange, as JSON lines on stderr. Never prints a key, token or cert.',
|
|
179
|
+
default: false,
|
|
180
|
+
}),
|
|
86
181
|
};
|
|
87
182
|
get isJson() {
|
|
88
183
|
return process.argv.includes('--json') || !process.stdout.isTTY;
|
|
@@ -90,40 +185,81 @@ export class BaseCommand extends Command {
|
|
|
90
185
|
get isQuiet() {
|
|
91
186
|
return process.argv.includes('--quiet');
|
|
92
187
|
}
|
|
188
|
+
/** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
|
|
189
|
+
verboseLog(flags, event) {
|
|
190
|
+
if (flags.verbose)
|
|
191
|
+
process.stderr.write(JSON.stringify({ verbose: true, ...event }) + '\n');
|
|
192
|
+
}
|
|
93
193
|
/**
|
|
94
|
-
* Resolve
|
|
194
|
+
* Resolve which credential a command uses, without calling anything.
|
|
95
195
|
*
|
|
96
|
-
* Precedence:
|
|
97
|
-
* API key
|
|
98
|
-
*
|
|
99
|
-
*
|
|
196
|
+
* Precedence, highest first:
|
|
197
|
+
* 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (oclif merges the
|
|
198
|
+
* two into `flags['api-key']`).
|
|
199
|
+
* 2. `AGLEDGER_OIDC_TOKEN_CMD`, then `AGLEDGER_OIDC_TOKEN_FILE`.
|
|
200
|
+
* 3. The selected profile (`--profile <name>`, else the active one): its
|
|
201
|
+
* API key, or the OIDC token source `agledger login --oidc` stored.
|
|
100
202
|
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
203
|
+
* Explicit per-invocation sources outrank stored ones, which is the rule the
|
|
204
|
+
* API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
|
|
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.
|
|
105
207
|
*/
|
|
106
|
-
|
|
208
|
+
resolveCredential(flags) {
|
|
107
209
|
const config = readConfig();
|
|
108
210
|
const profileName = flags.profile ?? config.activeProfile;
|
|
109
211
|
const profile = profileName ? config.profiles[profileName] : undefined;
|
|
212
|
+
const envAgentId = process.env[OIDC_ENV.AGENT_ID] || undefined;
|
|
110
213
|
// Treat an empty-string flag/env (e.g. AGLEDGER_API_KEY="") as absent so the
|
|
111
|
-
//
|
|
214
|
+
// later sources still apply.
|
|
112
215
|
const flagKey = flags['api-key'] || undefined;
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
// back on, that's an error worth surfacing (rather than a generic no-key one).
|
|
117
|
-
if (flags.profile && !profile && !flagKey) {
|
|
118
|
-
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.');
|
|
216
|
+
if (flagKey) {
|
|
217
|
+
const origin = argvHasFlag('--api-key') ? '--api-key' : 'AGLEDGER_API_KEY';
|
|
218
|
+
return { credential: { kind: 'api-key', key: flagKey, from: 'flag-or-env', origin }, profileName, profile };
|
|
119
219
|
}
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
220
|
+
const fromEnv = envOidcSource();
|
|
221
|
+
if (fromEnv) {
|
|
222
|
+
return {
|
|
223
|
+
credential: { kind: 'oidc', source: fromEnv, ...(envAgentId ? { agentId: envAgentId } : {}), from: 'env' },
|
|
224
|
+
profileName,
|
|
225
|
+
profile,
|
|
226
|
+
};
|
|
126
227
|
}
|
|
228
|
+
if (profileName && profile?.apiKey) {
|
|
229
|
+
return {
|
|
230
|
+
credential: { kind: 'api-key', key: profile.apiKey, from: 'profile', origin: `profile '${profileName}'` },
|
|
231
|
+
profileName,
|
|
232
|
+
profile,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
const fromProfile = profileName ? profileOidcSource(profileName, profile) : undefined;
|
|
236
|
+
if (fromProfile) {
|
|
237
|
+
const agentId = envAgentId ?? profile?.oidc?.agentId;
|
|
238
|
+
return {
|
|
239
|
+
credential: { kind: 'oidc', source: fromProfile, ...(agentId ? { agentId } : {}), from: 'profile' },
|
|
240
|
+
profileName,
|
|
241
|
+
profile,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
return { credential: { kind: 'none' }, profileName, profile };
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Resolve credentials and build the API client.
|
|
248
|
+
*
|
|
249
|
+
* Credential precedence is `resolveCredential`'s. API URL: `--api-url` flag >
|
|
250
|
+
* `AGLEDGER_API_URL` env > stored profile url. There is no default;
|
|
251
|
+
* AGLedger is self-hosted.
|
|
252
|
+
*/
|
|
253
|
+
createApiClient(flags, options) {
|
|
254
|
+
const { credential, profileName, profile } = this.resolveCredential(flags);
|
|
255
|
+
const flagUrl = flags['api-url'] || undefined;
|
|
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.
|
|
127
263
|
// No placeholder: a default of agledger.example.com resolved nowhere and
|
|
128
264
|
// turned a missing config into a DNS failure the user could not read.
|
|
129
265
|
// Every deployment is self-hosted, so there is no sane default.
|
|
@@ -131,23 +267,84 @@ export class BaseCommand extends Command {
|
|
|
131
267
|
if (!apiUrl) {
|
|
132
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>`.');
|
|
133
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
|
+
}
|
|
134
277
|
this.lastApiUrl = apiUrl;
|
|
135
|
-
|
|
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
|
+
}
|
|
287
|
+
const onBehalfOfSource = envOnBehalfOfSource();
|
|
288
|
+
this.verboseLog(flags, {
|
|
289
|
+
event: 'auth',
|
|
290
|
+
...this.describeCredential(credential),
|
|
291
|
+
apiUrl,
|
|
292
|
+
...(onBehalfOfSource ? { onBehalfOfSource: onBehalfOfSource.origin } : {}),
|
|
293
|
+
});
|
|
294
|
+
const onBehalfOf = onBehalfOfSource ? new DelegationToken(onBehalfOfSource) : null;
|
|
295
|
+
if (credential.kind === 'oidc') {
|
|
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.');
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/** Build a cert credential for one invocation. Its key pair never leaves memory. */
|
|
314
|
+
oidcCredential(flags, credential) {
|
|
315
|
+
return new OidcCertCredential({
|
|
316
|
+
source: credential.source,
|
|
317
|
+
...(credential.agentId ? { agentId: credential.agentId } : {}),
|
|
318
|
+
userAgent: `agledger-cli/${this.config.version}`,
|
|
319
|
+
log: (event) => this.verboseLog(flags, event),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
/** A secret-free description of a credential, for --verbose, --dry-run and `auth`. */
|
|
323
|
+
describeCredential(credential) {
|
|
324
|
+
switch (credential.kind) {
|
|
325
|
+
case 'api-key':
|
|
326
|
+
return { credential: 'api-key', source: credential.origin };
|
|
327
|
+
case 'oidc':
|
|
328
|
+
return {
|
|
329
|
+
credential: 'oidc-cert',
|
|
330
|
+
source: credential.source.origin,
|
|
331
|
+
...(credential.source.kind === 'file' ? { tokenFile: credential.source.path } : {}),
|
|
332
|
+
...(credential.agentId ? { agentId: credential.agentId } : {}),
|
|
333
|
+
};
|
|
334
|
+
case 'none':
|
|
335
|
+
return { credential: 'none' };
|
|
336
|
+
}
|
|
136
337
|
}
|
|
137
338
|
/**
|
|
138
339
|
* Resolve the credentials that an actual call would use, for --dry-run display.
|
|
139
|
-
* Same precedence as `createApiClient
|
|
140
|
-
*
|
|
141
|
-
*
|
|
340
|
+
* Same precedence as `createApiClient`, but the key is masked so it is safe
|
|
341
|
+
* to print, and an OIDC token source is named, never run. Does not throw on
|
|
342
|
+
* a missing credential (dry-run is non-fatal).
|
|
142
343
|
*/
|
|
143
344
|
resolvedAuth(flags) {
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
const profile = profileName ? config.profiles[profileName] : undefined;
|
|
147
|
-
const flagKey = flags['api-key'] || undefined;
|
|
345
|
+
const { credential, profileName, profile } = this.resolveCredential(flags);
|
|
346
|
+
this.requireNamedProfile(flags, profile);
|
|
148
347
|
const flagUrl = flags['api-url'] || undefined;
|
|
149
|
-
const apiKey = flagKey ?? profile?.apiKey ?? null;
|
|
150
|
-
const source = flagKey ? 'flag-or-env' : profile?.apiKey ? 'profile' : 'none';
|
|
151
348
|
// Null, not a placeholder. `agledger.example.com` was removed from
|
|
152
349
|
// `createApiClient`, which now refuses to build a client without a URL, but
|
|
153
350
|
// this sibling kept it. The whole job of --dry-run is to report what the
|
|
@@ -155,11 +352,15 @@ export class BaseCommand extends Command {
|
|
|
155
352
|
// use: the unconfigured case printed agledger.example.com and exited 0
|
|
156
353
|
// while the same invocation without --dry-run exited 2 with CONFIG_ERROR.
|
|
157
354
|
const apiUrl = flagUrl ?? profile?.apiUrl ?? null;
|
|
355
|
+
const problem = apiUrl === null ? undefined : apiUrlProblem(apiUrl);
|
|
158
356
|
const mask = (k) => (k.length <= 4 ? '****' : `****${k.slice(-4)}`);
|
|
357
|
+
const source = credential.kind === 'none' ? 'none' : credential.from;
|
|
159
358
|
return {
|
|
160
359
|
apiUrl,
|
|
161
|
-
apiKey:
|
|
360
|
+
apiKey: credential.kind === 'api-key' ? mask(credential.key) : null,
|
|
162
361
|
source,
|
|
362
|
+
credential: credential.kind === 'oidc' ? 'oidc-cert' : credential.kind,
|
|
363
|
+
...(credential.kind === 'oidc' ? { oidcTokenSource: credential.source.origin } : {}),
|
|
163
364
|
// A dry run whose real counterpart would refuse to send says so, rather
|
|
164
365
|
// than leaving a bare `"apiUrl": null` for the reader to interpret.
|
|
165
366
|
...(apiUrl === null
|
|
@@ -167,6 +368,11 @@ export class BaseCommand extends Command {
|
|
|
167
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>`.',
|
|
168
369
|
}
|
|
169
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
|
+
: {}),
|
|
170
376
|
...(source === 'profile' && profileName ? { profile: profileName } : {}),
|
|
171
377
|
};
|
|
172
378
|
}
|
|
@@ -175,8 +381,29 @@ export class BaseCommand extends Command {
|
|
|
175
381
|
* (e.g. `/v1/records`, `/health`, `/federation/v1/peer`). No auto-prefixing.
|
|
176
382
|
*/
|
|
177
383
|
async callApi(flags, method, path, options) {
|
|
178
|
-
const
|
|
179
|
-
|
|
384
|
+
const allowAnonymous = isPublicPath(method, path);
|
|
385
|
+
// One client per invocation. With an OIDC credential a new client means a
|
|
386
|
+
// new key pair and a new exchange, so rebuilding it per call (one per page
|
|
387
|
+
// under --paginate) spent a token per page: a token file 409s on the second
|
|
388
|
+
// exchange, and a command runs into the exchange route's rate limit.
|
|
389
|
+
if (!this.client) {
|
|
390
|
+
this.client = this.createApiClient(flags, { allowAnonymous });
|
|
391
|
+
}
|
|
392
|
+
else if (this.client.isAnonymous && !allowAnonymous) {
|
|
393
|
+
// Same refusal a fresh client would give for a path that needs a credential.
|
|
394
|
+
this.createApiClient(flags, { allowAnonymous });
|
|
395
|
+
}
|
|
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);
|
|
180
407
|
}
|
|
181
408
|
output(data) {
|
|
182
409
|
if (this.isQuiet)
|
|
@@ -244,10 +471,12 @@ export class BaseCommand extends Command {
|
|
|
244
471
|
}
|
|
245
472
|
return this.parseJsonInput(content, path === '-' ? 'stdin' : `${fieldName} ${path}`, suggestion);
|
|
246
473
|
}
|
|
247
|
-
failWith(code, message, exitCode, suggestion) {
|
|
474
|
+
failWith(code, message, exitCode, suggestion, extra) {
|
|
248
475
|
const error = { error: true, code, message };
|
|
249
476
|
if (suggestion)
|
|
250
477
|
error.suggestion = suggestion;
|
|
478
|
+
if (extra)
|
|
479
|
+
Object.assign(error, extra);
|
|
251
480
|
process.stderr.write(JSON.stringify(error) + '\n');
|
|
252
481
|
this.exit(exitCode);
|
|
253
482
|
throw new Error('unreachable');
|
|
@@ -268,8 +497,31 @@ export class BaseCommand extends Command {
|
|
|
268
497
|
handleError(err) {
|
|
269
498
|
if (err instanceof Error && err.message.startsWith('EEXIT:'))
|
|
270
499
|
throw err;
|
|
500
|
+
if (err instanceof OidcTokenSourceError) {
|
|
501
|
+
this.failWith(ErrorCode.OIDC_TOKEN_SOURCE_FAILED, err.message, ExitCode.AUTH_ERROR, err.kind === 'command'
|
|
502
|
+
? `Run the command in ${err.origin} by hand and check it prints one JWT on stdout and exits 0.`
|
|
503
|
+
: `Check the file named by ${err.origin} exists, is readable, and holds one JWT.`);
|
|
504
|
+
}
|
|
505
|
+
if (err instanceof OidcExchangeError) {
|
|
506
|
+
// The Server's error body is forwarded as it came (its recoveryHint is
|
|
507
|
+
// the useful part), with the OIDC token scrubbed out of it.
|
|
508
|
+
const error = {
|
|
509
|
+
error: true,
|
|
510
|
+
code: ErrorCode.OIDC_EXCHANGE_FAILED,
|
|
511
|
+
message: err.message,
|
|
512
|
+
status: err.status,
|
|
513
|
+
source: err.origin,
|
|
514
|
+
apiError: err.body,
|
|
515
|
+
};
|
|
516
|
+
process.stderr.write(JSON.stringify(error) + '\n');
|
|
517
|
+
this.exit(this.statusToExitCode(err.status));
|
|
518
|
+
throw new Error('unreachable');
|
|
519
|
+
}
|
|
271
520
|
if (err instanceof DOMException && err.name === 'AbortError') {
|
|
272
|
-
|
|
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);
|
|
273
525
|
}
|
|
274
526
|
if (err instanceof TypeError && String(err.message).includes('fetch')) {
|
|
275
527
|
// "fetch failed" is undici's generic message: DNS failure, connection
|
|
@@ -280,11 +532,17 @@ export class BaseCommand extends Command {
|
|
|
280
532
|
const causeMessage = typeof cause?.message === 'string' ? cause.message : undefined;
|
|
281
533
|
const target = this.lastApiUrl ? ` connecting to ${this.lastApiUrl}` : '';
|
|
282
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;
|
|
283
539
|
this.failWith(ErrorCode.NETWORK_ERROR, `${String(err.message)}${target}${detail ? ` (${detail})` : ''}`, ExitCode.NETWORK_ERROR, causeCode === 'ENOTFOUND'
|
|
284
540
|
? 'The host does not resolve. Check the API URL for a typo, and that DNS can see it from here.'
|
|
285
541
|
: causeCode === 'ECONNREFUSED'
|
|
286
542
|
? 'The host resolved but refused the connection. Check the Server is running and the port is right.'
|
|
287
|
-
:
|
|
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);
|
|
288
546
|
}
|
|
289
547
|
this.failWith(ErrorCode.UNKNOWN_ERROR, err instanceof Error ? err.message : String(err), ExitCode.GENERAL_ERROR, 'Run `agledger api --help` to see usage.');
|
|
290
548
|
}
|
package/dist/commands/api.d.ts
CHANGED
|
@@ -22,6 +22,7 @@ export default class Api extends BaseCommand {
|
|
|
22
22
|
'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
23
23
|
'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
24
24
|
profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
25
|
+
verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
|
|
25
26
|
data: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
26
27
|
input: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
27
28
|
field: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
package/dist/commands/api.js
CHANGED
|
@@ -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,
|
|
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
|
: {}),
|
package/dist/commands/auth.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { BaseCommand } from '../base.js';
|
|
2
2
|
/**
|
|
3
3
|
* Quick "am I logged in?" check. Local-first: returns `authenticated: false`
|
|
4
|
-
* with exit 0 when no
|
|
5
|
-
*
|
|
4
|
+
* with exit 0 when no credential is configured (useful for scripts gating on
|
|
5
|
+
* login state). Otherwise verifies the credential via GET /v1/auth/me. With an
|
|
6
|
+
* OIDC token source, that call runs one cert exchange, and the cert the Server
|
|
7
|
+
* issued (id, agent, issuer, subject, scopes, lifetime) is shown beside the
|
|
8
|
+
* identity.
|
|
6
9
|
*/
|
|
7
10
|
export default class Auth extends BaseCommand {
|
|
8
11
|
static description: string;
|
|
@@ -12,6 +15,7 @@ export default class Auth extends BaseCommand {
|
|
|
12
15
|
'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
13
16
|
'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
14
17
|
profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
18
|
+
verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
|
|
15
19
|
};
|
|
16
20
|
run(): Promise<void>;
|
|
17
21
|
}
|
package/dist/commands/auth.js
CHANGED
|
@@ -1,32 +1,42 @@
|
|
|
1
1
|
import { BaseCommand } from '../base.js';
|
|
2
2
|
/**
|
|
3
3
|
* Quick "am I logged in?" check. Local-first: returns `authenticated: false`
|
|
4
|
-
* with exit 0 when no
|
|
5
|
-
*
|
|
4
|
+
* with exit 0 when no credential is configured (useful for scripts gating on
|
|
5
|
+
* login state). Otherwise verifies the credential via GET /v1/auth/me. With an
|
|
6
|
+
* OIDC token source, that call runs one cert exchange, and the cert the Server
|
|
7
|
+
* issued (id, agent, issuer, subject, scopes, lifetime) is shown beside the
|
|
8
|
+
* identity.
|
|
6
9
|
*/
|
|
7
10
|
export default class Auth extends BaseCommand {
|
|
8
|
-
static description = 'Check current authentication status. Returns `authenticated: false` when no
|
|
11
|
+
static description = 'Check current authentication status, including the OIDC cert identity when a token source is configured. Returns `authenticated: false` when no credential is configured (exit 0).';
|
|
9
12
|
static flags = { ...BaseCommand.baseFlags };
|
|
10
13
|
async run() {
|
|
11
14
|
const { flags } = await this.parse(Auth);
|
|
12
|
-
// Resolve the
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
// a successful `login` wrote the key to a profile.
|
|
15
|
+
// Resolve the credential the same way an actual call does. An earlier
|
|
16
|
+
// check looked only at the flag/env, so `agledger auth` reported
|
|
17
|
+
// not-authenticated right after a successful `login` wrote a profile.
|
|
16
18
|
const auth = this.resolvedAuth(flags);
|
|
17
|
-
if (auth.
|
|
18
|
-
this.output({
|
|
19
|
+
if (auth.credential === 'none') {
|
|
20
|
+
this.output({
|
|
21
|
+
authenticated: false,
|
|
22
|
+
message: 'No credential configured. Set AGLEDGER_API_KEY, AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE, or run `agledger login`.',
|
|
23
|
+
});
|
|
19
24
|
return;
|
|
20
25
|
}
|
|
21
26
|
try {
|
|
22
|
-
const
|
|
27
|
+
const client = this.createApiClient(flags);
|
|
28
|
+
const response = await client.request('GET', '/v1/auth/me');
|
|
23
29
|
if (!response.ok) {
|
|
24
30
|
this.handleApiError(response);
|
|
25
31
|
}
|
|
32
|
+
const cert = client.credential?.cert;
|
|
26
33
|
this.output({
|
|
27
34
|
authenticated: true,
|
|
28
35
|
source: auth.source,
|
|
36
|
+
credential: auth.credential,
|
|
37
|
+
...(auth.oidcTokenSource ? { oidcTokenSource: auth.oidcTokenSource } : {}),
|
|
29
38
|
...(auth.profile ? { profile: auth.profile } : {}),
|
|
39
|
+
...(cert ? { cert } : {}),
|
|
30
40
|
account: response.body,
|
|
31
41
|
});
|
|
32
42
|
}
|
|
@@ -17,6 +17,7 @@ export default class Config extends BaseCommand {
|
|
|
17
17
|
quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
|
|
18
18
|
'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
19
19
|
'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
20
|
+
verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
|
|
20
21
|
profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
21
22
|
};
|
|
22
23
|
run(): Promise<void>;
|
package/dist/commands/config.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { Args, Flags } from '@oclif/core';
|
|
2
2
|
import { BaseCommand, ErrorCode, ExitCode } from '../base.js';
|
|
3
3
|
import { configPath, readConfig, writeConfig } from '../util/config.js';
|
|
4
|
+
/** What kind of credential a profile holds. Never echoes the key itself. */
|
|
5
|
+
function credentialOf(p) {
|
|
6
|
+
if (p.apiKey)
|
|
7
|
+
return 'api-key';
|
|
8
|
+
if (p.oidc?.tokenCommand || p.oidc?.tokenFile)
|
|
9
|
+
return 'oidc-cert';
|
|
10
|
+
return 'none';
|
|
11
|
+
}
|
|
4
12
|
/**
|
|
5
13
|
* Inspect and switch between stored profiles in ~/.agledger/config.json.
|
|
6
14
|
*
|
|
@@ -39,6 +47,7 @@ export default class Config extends BaseCommand {
|
|
|
39
47
|
const profiles = Object.entries(config.profiles).map(([name, p]) => ({
|
|
40
48
|
name,
|
|
41
49
|
apiUrl: p.apiUrl,
|
|
50
|
+
credential: credentialOf(p),
|
|
42
51
|
active: name === config.activeProfile,
|
|
43
52
|
}));
|
|
44
53
|
this.output({ activeProfile: config.activeProfile, profiles });
|
|
@@ -53,7 +62,14 @@ export default class Config extends BaseCommand {
|
|
|
53
62
|
if (!profile) {
|
|
54
63
|
this.failWith(ErrorCode.MISSING_INPUT, `Profile '${name}' not found.`, ExitCode.USAGE_ERROR, `Run \`agledger config list\` to see profiles.`);
|
|
55
64
|
}
|
|
56
|
-
this.output({
|
|
65
|
+
this.output({
|
|
66
|
+
name,
|
|
67
|
+
apiUrl: profile.apiUrl,
|
|
68
|
+
credential: credentialOf(profile),
|
|
69
|
+
// The stored token source (a command or a path), never a token.
|
|
70
|
+
...(profile.oidc ? { oidc: profile.oidc } : {}),
|
|
71
|
+
active: name === config.activeProfile,
|
|
72
|
+
});
|
|
57
73
|
return;
|
|
58
74
|
}
|
|
59
75
|
case 'use': {
|
|
@@ -15,6 +15,7 @@ export default class Discover extends BaseCommand {
|
|
|
15
15
|
'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
16
16
|
'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
17
17
|
profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
|
|
18
|
+
verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
|
|
18
19
|
};
|
|
19
20
|
run(): Promise<void>;
|
|
20
21
|
}
|