@agledger/mcp-server 2.10.0 → 2.11.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/CHANGELOG.md +39 -0
- package/LICENSE +13 -16
- package/README.md +105 -8
- package/dist/api-client.d.ts +24 -7
- package/dist/api-client.js +75 -13
- package/dist/credentials.d.ts +140 -0
- package/dist/credentials.js +384 -0
- package/dist/delegation.d.ts +49 -0
- package/dist/delegation.js +89 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +90 -5
- package/dist/server.d.ts +17 -1
- package/dist/server.js +206 -70
- package/package.json +3 -3
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the server authenticates to the AGLedger API.
|
|
3
|
+
*
|
|
4
|
+
* Two shapes. An API key is a static bearer. An OIDC cert credential exchanges
|
|
5
|
+
* a customer IdP token for a short-lived, Server-signed cert
|
|
6
|
+
* (`POST /v1/auth/oidc/cert`), re-exchanges before the cert runs out, and signs
|
|
7
|
+
* request bodies with the key bound to it.
|
|
8
|
+
*
|
|
9
|
+
* Nothing here writes to disk. The Ed25519 key pair lives in memory for the
|
|
10
|
+
* life of one credential (one server process) and the cert is cached in memory
|
|
11
|
+
* only. The token source is called for EVERY exchange: the Server refuses a
|
|
12
|
+
* token id it has already exchanged (409), and a projected Kubernetes token is
|
|
13
|
+
* rotated on disk underneath a running process, so a token is never reused.
|
|
14
|
+
*
|
|
15
|
+
* No token, cert or key ever reaches an error message, a log line or tool
|
|
16
|
+
* output. Server error bodies and token-command stderr are scrubbed before
|
|
17
|
+
* they are surfaced, because either can echo a token back.
|
|
18
|
+
*/
|
|
19
|
+
import { spawn } from 'node:child_process';
|
|
20
|
+
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
|
|
21
|
+
import { readFile } from 'node:fs/promises';
|
|
22
|
+
/** The env vars the server reads a token source from. The CLI reads the same names. */
|
|
23
|
+
export const OIDC_ENV = {
|
|
24
|
+
TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD',
|
|
25
|
+
TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE',
|
|
26
|
+
AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID',
|
|
27
|
+
};
|
|
28
|
+
const EXCHANGE_PATH = '/v1/auth/oidc/cert';
|
|
29
|
+
const POP_CONTEXT = 'agledger.oidc.cert.v1\n';
|
|
30
|
+
const AGENT_SIG_CONTEXT = 'agledger.agent.sig.v1\n';
|
|
31
|
+
const COMMAND_TIMEOUT_MS = 60_000;
|
|
32
|
+
const STDERR_LIMIT = 1_000;
|
|
33
|
+
const MAX_STDOUT_BYTES = 64 * 1024;
|
|
34
|
+
/** A compact JWS: three base64url segments, the first a JSON header (`eyJ`). */
|
|
35
|
+
const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
|
|
36
|
+
const REDACTED = '<redacted-token>';
|
|
37
|
+
/** Replace anything shaped like a JWT with a placeholder. */
|
|
38
|
+
export function redactTokens(text) {
|
|
39
|
+
return text.replace(JWT_PATTERN, REDACTED);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Deep-copy a JSON value with every string passed through `redactTokens`, and
|
|
43
|
+
* any occurrence of `secret` cut out. The Server's validation errors echo the
|
|
44
|
+
* offending input back, which on the exchange route is the OIDC token.
|
|
45
|
+
*/
|
|
46
|
+
export function scrub(value, secret) {
|
|
47
|
+
return mapStrings(value, (v) => redactTokens(secret ? v.split(secret).join(REDACTED) : v));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Deep-copy a JSON value with every occurrence of `secret` cut out, and
|
|
51
|
+
* nothing else touched. For API responses, which may legitimately carry other
|
|
52
|
+
* JWT-shaped values (an agent can call the exchange route itself).
|
|
53
|
+
*/
|
|
54
|
+
export function cutSecret(value, secret) {
|
|
55
|
+
return mapStrings(value, (v) => (v.includes(secret) ? v.split(secret).join(REDACTED) : v));
|
|
56
|
+
}
|
|
57
|
+
function mapStrings(value, f) {
|
|
58
|
+
if (typeof value === 'string')
|
|
59
|
+
return f(value);
|
|
60
|
+
if (Array.isArray(value))
|
|
61
|
+
return value.map((v) => mapStrings(v, f));
|
|
62
|
+
if (value !== null && typeof value === 'object') {
|
|
63
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, mapStrings(v, f)]));
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
/** The token source could not produce a usable token. */
|
|
68
|
+
export class OidcTokenSourceError extends Error {
|
|
69
|
+
unrotated;
|
|
70
|
+
code = 'OIDC_TOKEN_SOURCE_FAILED';
|
|
71
|
+
/** @param unrotated the source returned the token it returned last time, which is expected for a file between rotations */
|
|
72
|
+
constructor(message, unrotated = false) {
|
|
73
|
+
super(message);
|
|
74
|
+
this.unrotated = unrotated;
|
|
75
|
+
this.name = 'OidcTokenSourceError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** The Server refused the exchange. `body` is its error response, scrubbed. */
|
|
79
|
+
export class OidcExchangeError extends Error {
|
|
80
|
+
status;
|
|
81
|
+
body;
|
|
82
|
+
code = 'OIDC_EXCHANGE_FAILED';
|
|
83
|
+
constructor(message, status, body) {
|
|
84
|
+
super(message);
|
|
85
|
+
this.status = status;
|
|
86
|
+
this.body = body;
|
|
87
|
+
this.name = 'OidcExchangeError';
|
|
88
|
+
}
|
|
89
|
+
/** The Server's own recovery guidance, when its error body carries one. */
|
|
90
|
+
get recoveryHint() {
|
|
91
|
+
const b = this.body;
|
|
92
|
+
if (b && typeof b.recoveryHint === 'string')
|
|
93
|
+
return b.recoveryHint;
|
|
94
|
+
if (b && typeof b.suggestion === 'string')
|
|
95
|
+
return b.suggestion;
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Reads a token file on every call. Kubernetes rotates projected tokens on disk. */
|
|
100
|
+
export function oidcTokenFromFile(path, origin = OIDC_ENV.TOKEN_FILE) {
|
|
101
|
+
return async () => {
|
|
102
|
+
try {
|
|
103
|
+
return await readFile(path, 'utf8');
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
const code = err.code;
|
|
107
|
+
throw new OidcTokenSourceError(`${origin}: cannot read the token file ${path}${typeof code === 'string' ? ` (${code})` : ''}.`);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Kill the command's whole process group. The shell is only the group
|
|
113
|
+
* leader: in `a | b`, or a helper that forks, killing the shell alone leaves
|
|
114
|
+
* the children running, and in a long-running server a hung refresh would
|
|
115
|
+
* leave another set behind every time.
|
|
116
|
+
*/
|
|
117
|
+
function killTree(pid) {
|
|
118
|
+
if (pid === undefined)
|
|
119
|
+
return;
|
|
120
|
+
try {
|
|
121
|
+
if (process.platform === 'win32') {
|
|
122
|
+
spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
process.kill(-pid, 'SIGKILL');
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// Already gone.
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Runs a shell command on every call; its stdout is the token. The command
|
|
134
|
+
* runs in its own process group, which is killed on timeout, on oversized
|
|
135
|
+
* output, and after it exits, so nothing it started outlives the call. The
|
|
136
|
+
* command text is never echoed back, since it can carry a secret of its own.
|
|
137
|
+
*/
|
|
138
|
+
export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, options = {}) {
|
|
139
|
+
const timeoutMs = options.timeoutMs ?? COMMAND_TIMEOUT_MS;
|
|
140
|
+
const maxStdout = options.maxStdoutBytes ?? MAX_STDOUT_BYTES;
|
|
141
|
+
return () => new Promise((resolve, reject) => {
|
|
142
|
+
let child;
|
|
143
|
+
try {
|
|
144
|
+
child = spawn(command, {
|
|
145
|
+
shell: true,
|
|
146
|
+
// Its own process group on POSIX, so the group can be killed whole.
|
|
147
|
+
detached: process.platform !== 'win32',
|
|
148
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
149
|
+
windowsHide: true,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
reject(new OidcTokenSourceError(`${origin}: could not run the token command: ${err instanceof Error ? err.message : String(err)}`));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const out = [];
|
|
157
|
+
let outBytes = 0;
|
|
158
|
+
let stderr = '';
|
|
159
|
+
let settled = false;
|
|
160
|
+
const fail = (message) => {
|
|
161
|
+
if (settled)
|
|
162
|
+
return;
|
|
163
|
+
settled = true;
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
killTree(child.pid);
|
|
166
|
+
reject(new OidcTokenSourceError(`${origin}: ${message}`));
|
|
167
|
+
};
|
|
168
|
+
const timer = setTimeout(() => fail(`the token command did not finish within ${timeoutMs / 1000}s and was killed.`), timeoutMs);
|
|
169
|
+
child.stdout.on('data', (d) => {
|
|
170
|
+
outBytes += d.length;
|
|
171
|
+
if (outBytes > maxStdout) {
|
|
172
|
+
fail(`the token command printed more than ${maxStdout} bytes, which is not a token; it was killed.`);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
out.push(d);
|
|
176
|
+
});
|
|
177
|
+
child.stderr.setEncoding('utf8').on('data', (d) => {
|
|
178
|
+
if (stderr.length < STDERR_LIMIT * 2)
|
|
179
|
+
stderr += d;
|
|
180
|
+
});
|
|
181
|
+
child.on('error', (err) => fail(`could not run the token command: ${err.message}`));
|
|
182
|
+
child.on('close', (code, signal) => {
|
|
183
|
+
if (settled)
|
|
184
|
+
return;
|
|
185
|
+
settled = true;
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
// Anything it left running in the background goes with it.
|
|
188
|
+
killTree(child.pid);
|
|
189
|
+
if (code === 0) {
|
|
190
|
+
resolve(Buffer.concat(out).toString('utf8'));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const detail = redactTokens(stderr.trim()).slice(0, STDERR_LIMIT);
|
|
194
|
+
const how = signal ? `was killed by ${signal}` : `exited ${code}`;
|
|
195
|
+
reject(new OidcTokenSourceError(`${origin}: the token command ${how}${detail ? `. stderr: ${detail}` : ' with no stderr output.'}`));
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Validate a compact JWT's shape and return its unverified payload. The Server
|
|
201
|
+
* verifies the signature. Errors never quote the token.
|
|
202
|
+
*/
|
|
203
|
+
export function jwtPayloadOf(token, origin) {
|
|
204
|
+
const parts = token.split('.');
|
|
205
|
+
if (parts.length !== 3 || parts.some((p, i) => i < 2 && p.length === 0)) {
|
|
206
|
+
throw new OidcTokenSourceError(`${origin}: the token source did not produce a compact JWT (expected three dot-separated segments).`);
|
|
207
|
+
}
|
|
208
|
+
let payload;
|
|
209
|
+
try {
|
|
210
|
+
payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
throw new OidcTokenSourceError(`${origin}: the token's payload segment is not base64url JSON.`);
|
|
214
|
+
}
|
|
215
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
216
|
+
throw new OidcTokenSourceError(`${origin}: the token's payload is not a JSON object.`);
|
|
217
|
+
}
|
|
218
|
+
return payload;
|
|
219
|
+
}
|
|
220
|
+
/** Read a token's unverified `sub` and `jti`. */
|
|
221
|
+
function claimsOf(token, origin) {
|
|
222
|
+
const { sub, jti } = jwtPayloadOf(token, origin);
|
|
223
|
+
if (typeof sub !== 'string' || sub.length === 0) {
|
|
224
|
+
throw new OidcTokenSourceError(`${origin}: the token carries no \`sub\` claim, so it cannot be exchanged.`);
|
|
225
|
+
}
|
|
226
|
+
return { sub, jti: typeof jti === 'string' && jti.length > 0 ? jti : undefined };
|
|
227
|
+
}
|
|
228
|
+
export class ApiKeyCredential {
|
|
229
|
+
apiKey;
|
|
230
|
+
renewable = false;
|
|
231
|
+
constructor(apiKey) {
|
|
232
|
+
this.apiKey = apiKey;
|
|
233
|
+
}
|
|
234
|
+
bearer() {
|
|
235
|
+
return Promise.resolve(this.apiKey);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
export class OidcCertCredential {
|
|
239
|
+
renewable = true;
|
|
240
|
+
getOidcToken;
|
|
241
|
+
agentId;
|
|
242
|
+
refreshFraction;
|
|
243
|
+
origin;
|
|
244
|
+
onWarning;
|
|
245
|
+
now;
|
|
246
|
+
privateKey;
|
|
247
|
+
publicX;
|
|
248
|
+
cert;
|
|
249
|
+
inflight;
|
|
250
|
+
lastWarned;
|
|
251
|
+
/** The last token the Server accepted. A token carrying a `jti` is exchangeable once. */
|
|
252
|
+
lastExchangedToken;
|
|
253
|
+
constructor(options) {
|
|
254
|
+
const fraction = options.refreshFraction ?? 0.5;
|
|
255
|
+
if (!(fraction > 0 && fraction <= 1)) {
|
|
256
|
+
throw new RangeError('refreshFraction must be greater than 0 and at most 1.');
|
|
257
|
+
}
|
|
258
|
+
this.getOidcToken = options.getOidcToken;
|
|
259
|
+
this.agentId = options.agentId;
|
|
260
|
+
this.refreshFraction = fraction;
|
|
261
|
+
this.origin = options.origin ?? 'OIDC token source';
|
|
262
|
+
this.onWarning = options.onWarning;
|
|
263
|
+
this.now = options.now ?? Date.now;
|
|
264
|
+
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
|
265
|
+
this.privateKey = privateKey;
|
|
266
|
+
const jwk = publicKey.export({ format: 'jwk' });
|
|
267
|
+
if (typeof jwk.x !== 'string')
|
|
268
|
+
throw new Error('Ed25519 public key export carried no x coordinate.');
|
|
269
|
+
this.publicX = jwk.x;
|
|
270
|
+
}
|
|
271
|
+
async bearer(ctx) {
|
|
272
|
+
const current = this.cert;
|
|
273
|
+
const t = this.now();
|
|
274
|
+
if (ctx.rejected !== undefined) {
|
|
275
|
+
// A retry after a 401. If another request already replaced the bearer
|
|
276
|
+
// that was refused, use the replacement rather than exchanging again.
|
|
277
|
+
if (current && current.jws !== ctx.rejected && t < current.expiresAt)
|
|
278
|
+
return current.jws;
|
|
279
|
+
return (await this.exchange(ctx)).jws;
|
|
280
|
+
}
|
|
281
|
+
if (current && t < current.refreshAt)
|
|
282
|
+
return current.jws;
|
|
283
|
+
try {
|
|
284
|
+
return (await this.exchange(ctx)).jws;
|
|
285
|
+
}
|
|
286
|
+
catch (err) {
|
|
287
|
+
// Past the refresh point but not past expiry: the cert still works, so a
|
|
288
|
+
// failed refresh must not fail the request. Say so once per failure and
|
|
289
|
+
// try again on the next call. After expiry the error surfaces.
|
|
290
|
+
if (current && t < current.expiresAt) {
|
|
291
|
+
// Warn once per distinct failure, not once per call: a token file that
|
|
292
|
+
// has not rotated yet fails the same way on every call until it does.
|
|
293
|
+
// An unrotated token file is the normal state between rotations, not a
|
|
294
|
+
// failure worth a line on stderr.
|
|
295
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
296
|
+
const expected = err instanceof OidcTokenSourceError && err.unrotated;
|
|
297
|
+
if (!expected && this.lastWarned !== message) {
|
|
298
|
+
this.lastWarned = message;
|
|
299
|
+
this.onWarning?.(`AGLedger OIDC cert refresh failed; the current cert stays in use until it expires. ${message}`);
|
|
300
|
+
}
|
|
301
|
+
return current.jws;
|
|
302
|
+
}
|
|
303
|
+
throw err;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
signBody(body) {
|
|
307
|
+
const hex = createHash('sha256').update(body, 'utf8').digest('hex');
|
|
308
|
+
const signature = sign(null, Buffer.from(`${AGENT_SIG_CONTEXT}${hex}`, 'utf8'), this.privateKey);
|
|
309
|
+
return {
|
|
310
|
+
'X-Agent-Signature-Content-Hash': `sha256:${hex}`,
|
|
311
|
+
'X-Agent-Signature': signature.toString('base64'),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
/** Single-flight: concurrent callers share one exchange. */
|
|
315
|
+
exchange(ctx) {
|
|
316
|
+
if (!this.inflight) {
|
|
317
|
+
this.inflight = this.runExchange(ctx).finally(() => {
|
|
318
|
+
this.inflight = undefined;
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
return this.inflight;
|
|
322
|
+
}
|
|
323
|
+
async runExchange(ctx) {
|
|
324
|
+
let token;
|
|
325
|
+
try {
|
|
326
|
+
token = String(await this.getOidcToken()).trim();
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
if (err instanceof OidcTokenSourceError)
|
|
330
|
+
throw err;
|
|
331
|
+
throw new OidcTokenSourceError(`${this.origin}: ${redactTokens(err instanceof Error ? err.message : String(err))}`);
|
|
332
|
+
}
|
|
333
|
+
if (!token)
|
|
334
|
+
throw new OidcTokenSourceError(`${this.origin}: the token source returned nothing.`);
|
|
335
|
+
const { sub, jti } = claimsOf(token, this.origin);
|
|
336
|
+
// The Server exchanges a token id once and answers 409 after that. A token
|
|
337
|
+
// file hands back the same token until it rotates, so a refresh against an
|
|
338
|
+
// unrotated file is certain to fail: say why here instead of asking.
|
|
339
|
+
if (jti !== undefined && token === this.lastExchangedToken) {
|
|
340
|
+
throw new OidcTokenSourceError(`${this.origin}: the token source returned the same token as the last exchange, and the Server exchanges ` +
|
|
341
|
+
'a token id (jti) only once, so the cert expired before a new token appeared. For a Kubernetes ' +
|
|
342
|
+
'projected token, the kubelet rewrites the file at 80% of expirationSeconds; that interval must be ' +
|
|
343
|
+
"shorter than the trusted issuer's maxCredentialTtlSeconds (e.g. expirationSeconds: 600 with a " +
|
|
344
|
+
'600-second cert lifetime).', true);
|
|
345
|
+
}
|
|
346
|
+
const proofOfPossession = sign(null, Buffer.from(`${POP_CONTEXT}${sub}`, 'utf8'), this.privateKey).toString('base64');
|
|
347
|
+
const body = {
|
|
348
|
+
oidcToken: token,
|
|
349
|
+
publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: this.publicX },
|
|
350
|
+
proofOfPossession,
|
|
351
|
+
};
|
|
352
|
+
if (this.agentId)
|
|
353
|
+
body.agentId = this.agentId;
|
|
354
|
+
let res;
|
|
355
|
+
try {
|
|
356
|
+
res = await ctx.postAnonymous(EXCHANGE_PATH, body);
|
|
357
|
+
}
|
|
358
|
+
catch (err) {
|
|
359
|
+
throw new OidcExchangeError(`OIDC cert exchange failed: ${redactTokens(err instanceof Error ? err.message : String(err))}`, 0, null);
|
|
360
|
+
}
|
|
361
|
+
if (res.status !== 201) {
|
|
362
|
+
const scrubbed = scrub(res.body, token);
|
|
363
|
+
const serverMessage = scrubbed?.message;
|
|
364
|
+
throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned ${res.status}${typeof serverMessage === 'string' ? `: ${serverMessage}` : ''}`, res.status, scrubbed);
|
|
365
|
+
}
|
|
366
|
+
const out = res.body;
|
|
367
|
+
const issuedAt = Date.parse(String(out?.cert?.issuedAt));
|
|
368
|
+
const expiresAt = Date.parse(String(out?.cert?.expiresAt));
|
|
369
|
+
const lifetime = expiresAt - issuedAt;
|
|
370
|
+
if (typeof out?.certJws !== 'string' || !Number.isFinite(lifetime) || lifetime <= 0) {
|
|
371
|
+
throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned 201 without a certJws and a valid cert.issuedAt/expiresAt.`, res.status, null);
|
|
372
|
+
}
|
|
373
|
+
this.lastExchangedToken = token;
|
|
374
|
+
this.lastWarned = undefined;
|
|
375
|
+
const receivedAt = this.now();
|
|
376
|
+
const cert = {
|
|
377
|
+
jws: out.certJws,
|
|
378
|
+
refreshAt: receivedAt + this.refreshFraction * lifetime,
|
|
379
|
+
expiresAt: receivedAt + lifetime,
|
|
380
|
+
};
|
|
381
|
+
this.cert = cert;
|
|
382
|
+
return cert;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RFC 8693 delegation token sent as `AGLedger-On-Behalf-Of`, when this
|
|
3
|
+
* server acts for a person or another party rather than for itself.
|
|
4
|
+
*
|
|
5
|
+
* It comes from the process, never from a tool argument: a token a model could
|
|
6
|
+
* read or write is a token a prompt could steal or forge. The operator names a
|
|
7
|
+
* command or a file, and the server attaches the token to POST requests, which
|
|
8
|
+
* is where every route that declares the header lives. The Server ignores the
|
|
9
|
+
* header on routes that do not declare it.
|
|
10
|
+
*
|
|
11
|
+
* Unlike the OIDC token behind the cert, a delegation token is not single use,
|
|
12
|
+
* so it is cached until its `exp` and re-read after that, or when the Server
|
|
13
|
+
* refuses it with a 401 that names the delegation.
|
|
14
|
+
*/
|
|
15
|
+
import { type OidcTokenGetter } from './credentials.js';
|
|
16
|
+
export declare const ON_BEHALF_OF_ENV: {
|
|
17
|
+
readonly CMD: 'AGLEDGER_ON_BEHALF_OF_CMD';
|
|
18
|
+
readonly FILE: 'AGLEDGER_ON_BEHALF_OF_FILE';
|
|
19
|
+
};
|
|
20
|
+
export declare const ON_BEHALF_OF_HEADER = "AGLedger-On-Behalf-Of";
|
|
21
|
+
/** The delegation source could not produce a usable token. */
|
|
22
|
+
export declare class DelegationSourceError extends Error {
|
|
23
|
+
readonly code = "ON_BEHALF_OF_SOURCE_FAILED";
|
|
24
|
+
constructor(message: string);
|
|
25
|
+
}
|
|
26
|
+
export interface DelegationSourceOptions {
|
|
27
|
+
/** Returns the delegation token. Called when nothing valid is cached. */
|
|
28
|
+
getToken: OidcTokenGetter;
|
|
29
|
+
/** Names the source in errors and in `agledger_discover`, e.g. `AGLEDGER_ON_BEHALF_OF_FILE`. */
|
|
30
|
+
origin: string;
|
|
31
|
+
/** Injectable clock, for tests. */
|
|
32
|
+
now?: () => number;
|
|
33
|
+
}
|
|
34
|
+
/** True when a 401 body is about the delegation token rather than the caller's own credential. */
|
|
35
|
+
export declare function namesDelegation(body: unknown): boolean;
|
|
36
|
+
export declare class DelegationSource {
|
|
37
|
+
readonly origin: string;
|
|
38
|
+
private readonly getToken;
|
|
39
|
+
private readonly now;
|
|
40
|
+
private cached;
|
|
41
|
+
private inflight;
|
|
42
|
+
constructor(options: DelegationSourceOptions);
|
|
43
|
+
/**
|
|
44
|
+
* The token to send. `rejected` is the token the Server just refused: a
|
|
45
|
+
* cached token equal to it is dropped and the source read again.
|
|
46
|
+
*/
|
|
47
|
+
token(rejected?: string): Promise<string>;
|
|
48
|
+
private read;
|
|
49
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RFC 8693 delegation token sent as `AGLedger-On-Behalf-Of`, when this
|
|
3
|
+
* server acts for a person or another party rather than for itself.
|
|
4
|
+
*
|
|
5
|
+
* It comes from the process, never from a tool argument: a token a model could
|
|
6
|
+
* read or write is a token a prompt could steal or forge. The operator names a
|
|
7
|
+
* command or a file, and the server attaches the token to POST requests, which
|
|
8
|
+
* is where every route that declares the header lives. The Server ignores the
|
|
9
|
+
* header on routes that do not declare it.
|
|
10
|
+
*
|
|
11
|
+
* Unlike the OIDC token behind the cert, a delegation token is not single use,
|
|
12
|
+
* so it is cached until its `exp` and re-read after that, or when the Server
|
|
13
|
+
* refuses it with a 401 that names the delegation.
|
|
14
|
+
*/
|
|
15
|
+
import { jwtPayloadOf, OidcTokenSourceError, redactTokens } from './credentials.js';
|
|
16
|
+
export const ON_BEHALF_OF_ENV = {
|
|
17
|
+
CMD: 'AGLEDGER_ON_BEHALF_OF_CMD',
|
|
18
|
+
FILE: 'AGLEDGER_ON_BEHALF_OF_FILE',
|
|
19
|
+
};
|
|
20
|
+
export const ON_BEHALF_OF_HEADER = 'AGLedger-On-Behalf-Of';
|
|
21
|
+
/** Re-read this long before `exp`, so a token is not sent in its last seconds. */
|
|
22
|
+
const EXPIRY_MARGIN_MS = 30_000;
|
|
23
|
+
/** The delegation source could not produce a usable token. */
|
|
24
|
+
export class DelegationSourceError extends Error {
|
|
25
|
+
code = 'ON_BEHALF_OF_SOURCE_FAILED';
|
|
26
|
+
constructor(message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = 'DelegationSourceError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** True when a 401 body is about the delegation token rather than the caller's own credential. */
|
|
32
|
+
export function namesDelegation(body) {
|
|
33
|
+
let text;
|
|
34
|
+
try {
|
|
35
|
+
text = JSON.stringify(body) ?? '';
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return /on-behalf-of|delegation/i.test(text);
|
|
41
|
+
}
|
|
42
|
+
export class DelegationSource {
|
|
43
|
+
origin;
|
|
44
|
+
getToken;
|
|
45
|
+
now;
|
|
46
|
+
cached;
|
|
47
|
+
inflight;
|
|
48
|
+
constructor(options) {
|
|
49
|
+
this.getToken = options.getToken;
|
|
50
|
+
this.origin = options.origin;
|
|
51
|
+
this.now = options.now ?? Date.now;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The token to send. `rejected` is the token the Server just refused: a
|
|
55
|
+
* cached token equal to it is dropped and the source read again.
|
|
56
|
+
*/
|
|
57
|
+
async token(rejected) {
|
|
58
|
+
const c = this.cached;
|
|
59
|
+
if (c && c.token !== rejected && this.now() < c.freshUntil)
|
|
60
|
+
return c.token;
|
|
61
|
+
if (!this.inflight) {
|
|
62
|
+
this.inflight = this.read().finally(() => {
|
|
63
|
+
this.inflight = undefined;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return this.inflight;
|
|
67
|
+
}
|
|
68
|
+
async read() {
|
|
69
|
+
let token;
|
|
70
|
+
try {
|
|
71
|
+
token = String(await this.getToken()).trim();
|
|
72
|
+
if (!token)
|
|
73
|
+
throw new OidcTokenSourceError(`${this.origin}: the source returned nothing.`);
|
|
74
|
+
const { exp } = jwtPayloadOf(token, this.origin);
|
|
75
|
+
if (typeof exp === 'number' && exp * 1000 <= this.now()) {
|
|
76
|
+
throw new OidcTokenSourceError(`${this.origin}: the delegation token expired at ${new Date(exp * 1000).toISOString()}; the source must yield a current one.`);
|
|
77
|
+
}
|
|
78
|
+
// No exp: nothing says how long it stays good, so read it every time.
|
|
79
|
+
const freshUntil = typeof exp === 'number' ? exp * 1000 - EXPIRY_MARGIN_MS : 0;
|
|
80
|
+
this.cached = { token, freshUntil };
|
|
81
|
+
return token;
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
this.cached = undefined;
|
|
85
|
+
const message = redactTokens(err instanceof Error ? err.message : String(err));
|
|
86
|
+
throw new DelegationSourceError(message.startsWith(this.origin) ? message : `${this.origin}: ${message}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
export { AgledgerMcpServer } from './server.js';
|
|
3
3
|
export type { AgledgerMcpServerOptions } from './server.js';
|
|
4
|
+
export type { OidcCertCredentialOptions, OidcTokenGetter } from './credentials.js';
|
|
5
|
+
export type { DelegationSourceOptions } from './delegation.js';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { accessSync, constants as fsConstants } from 'node:fs';
|
|
2
3
|
import { parseArgs } from 'node:util';
|
|
3
4
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
5
|
import { AgledgerMcpServer, SERVER_VERSION } from './server.js';
|
|
5
6
|
import { resolveZodCopies, zodSplitWarning } from './zod-integrity.js';
|
|
7
|
+
import { OIDC_ENV, oidcTokenFromCommand, oidcTokenFromFile } from './credentials.js';
|
|
8
|
+
import { ON_BEHALF_OF_ENV } from './delegation.js';
|
|
6
9
|
/**
|
|
7
10
|
* Exit codes. A launcher that supervises this process, or a shell wrapping it,
|
|
8
11
|
* has only the code to go on: stderr is where the MCP client's own diagnostics
|
|
@@ -45,14 +48,36 @@ function main() {
|
|
|
45
48
|
process.stderr.write(`AGLedger MCP Server v${SERVER_VERSION}
|
|
46
49
|
|
|
47
50
|
Usage: agledger-mcp --api-key <key> --api-url <url>
|
|
51
|
+
AGLEDGER_OIDC_TOKEN_FILE=<path> agledger-mcp --api-url <url>
|
|
48
52
|
|
|
49
53
|
Options:
|
|
50
|
-
--api-key, -k AGLedger API key (or AGLEDGER_API_KEY env var).
|
|
54
|
+
--api-key, -k AGLedger API key (or AGLEDGER_API_KEY env var).
|
|
51
55
|
--api-url, -u Base URL of your AGLedger instance (or AGLEDGER_API_URL env
|
|
52
56
|
var). Required: AGLedger is self-hosted, so there is no
|
|
53
57
|
default server to call.
|
|
54
58
|
--help, -h Show this help message
|
|
55
59
|
|
|
60
|
+
Credentials: one is required. An API key wins when set; otherwise an OIDC
|
|
61
|
+
token source is exchanged for a short-lived cert (POST /v1/auth/oidc/cert),
|
|
62
|
+
re-exchanged at half its lifetime and on a 401, and the cert's key signs
|
|
63
|
+
request bodies. Nothing is written to disk.
|
|
64
|
+
AGLEDGER_API_KEY API key (same as --api-key)
|
|
65
|
+
AGLEDGER_OIDC_TOKEN_CMD Shell command whose stdout is an OIDC JWT; run on
|
|
66
|
+
every exchange. Wins over the token file.
|
|
67
|
+
AGLEDGER_OIDC_TOKEN_FILE File holding an OIDC JWT; read on every exchange,
|
|
68
|
+
so a rotated Kubernetes projected token is picked
|
|
69
|
+
up.
|
|
70
|
+
AGLEDGER_OIDC_AGENT_ID Optional agent id to bind the cert to.
|
|
71
|
+
|
|
72
|
+
Delegation (optional): when the agent acts for a person or another party, an
|
|
73
|
+
RFC 8693 token-exchange result token is sent as AGLedger-On-Behalf-Of on every
|
|
74
|
+
POST. It comes from the process, never from a tool argument.
|
|
75
|
+
AGLEDGER_ON_BEHALF_OF_CMD Shell command whose stdout is the token. Wins over
|
|
76
|
+
the file.
|
|
77
|
+
AGLEDGER_ON_BEHALF_OF_FILE File holding the token.
|
|
78
|
+
Either is read again once the token's exp has passed, or when the Server
|
|
79
|
+
refuses the delegation with a 401.
|
|
80
|
+
|
|
56
81
|
Tools:
|
|
57
82
|
agledger_discover Returns API health, your identity, and available scopes
|
|
58
83
|
agledger_api Make any AGLedger API call; the API guides you via nextSteps
|
|
@@ -62,12 +87,49 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
62
87
|
`);
|
|
63
88
|
process.exit(0);
|
|
64
89
|
}
|
|
65
|
-
const apiKey = values['api-key']
|
|
90
|
+
const apiKey = values['api-key'] || process.env.AGLEDGER_API_KEY || undefined;
|
|
66
91
|
const apiUrl = values['api-url'] ?? process.env.AGLEDGER_API_URL;
|
|
67
|
-
|
|
68
|
-
|
|
92
|
+
const tokenCmd = process.env[OIDC_ENV.TOKEN_CMD] || undefined;
|
|
93
|
+
const tokenFile = process.env[OIDC_ENV.TOKEN_FILE] || undefined;
|
|
94
|
+
const agentId = process.env[OIDC_ENV.AGENT_ID] || undefined;
|
|
95
|
+
if (!apiKey && !tokenCmd && !tokenFile) {
|
|
96
|
+
process.stderr.write('Error: no credential configured. Set one of:\n' +
|
|
97
|
+
' --api-key <key> or AGLEDGER_API_KEY an AGLedger API key\n' +
|
|
98
|
+
` ${OIDC_ENV.TOKEN_CMD} a shell command that prints an OIDC JWT\n` +
|
|
99
|
+
` ${OIDC_ENV.TOKEN_FILE} a file holding an OIDC JWT (e.g. a projected token)\n` +
|
|
100
|
+
'Run `agledger-mcp --help` for details.\n');
|
|
69
101
|
process.exit(EXIT_USAGE_ERROR);
|
|
70
102
|
}
|
|
103
|
+
// Precedence: API key, then command, then file. Say which one lost, so a
|
|
104
|
+
// leftover variable is not silently ignored.
|
|
105
|
+
const ignored = [
|
|
106
|
+
apiKey && tokenCmd ? OIDC_ENV.TOKEN_CMD : undefined,
|
|
107
|
+
(apiKey || tokenCmd) && tokenFile ? OIDC_ENV.TOKEN_FILE : undefined,
|
|
108
|
+
].filter(Boolean);
|
|
109
|
+
if (ignored.length) {
|
|
110
|
+
process.stderr.write(`Note: ${ignored.join(' and ')} ${ignored.length === 1 ? 'is' : 'are'} set but not used: ` +
|
|
111
|
+
`${apiKey ? 'the API key' : OIDC_ENV.TOKEN_CMD} takes precedence.\n`);
|
|
112
|
+
}
|
|
113
|
+
let oidc;
|
|
114
|
+
if (!apiKey) {
|
|
115
|
+
if (!tokenCmd && tokenFile) {
|
|
116
|
+
// Caught here rather than on the first tool call: a wrong path is a
|
|
117
|
+
// configuration error, and the MCP client may not call a tool for hours.
|
|
118
|
+
try {
|
|
119
|
+
accessSync(tokenFile, fsConstants.R_OK);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
process.stderr.write(`Error: ${OIDC_ENV.TOKEN_FILE} names a file that cannot be read: ${tokenFile}\n`);
|
|
123
|
+
process.exit(EXIT_USAGE_ERROR);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
oidc = {
|
|
127
|
+
getOidcToken: tokenCmd ? oidcTokenFromCommand(tokenCmd) : oidcTokenFromFile(tokenFile),
|
|
128
|
+
origin: tokenCmd ? OIDC_ENV.TOKEN_CMD : OIDC_ENV.TOKEN_FILE,
|
|
129
|
+
...(agentId ? { agentId } : {}),
|
|
130
|
+
onWarning: (message) => process.stderr.write(`Warning: ${message}\n`),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
71
133
|
// Checked here, alongside the key, rather than left to throw out of the
|
|
72
134
|
// server constructor: the two are the same class of mistake and deserve the
|
|
73
135
|
// same treatment. Letting one exit 2 with a plain message while the other
|
|
@@ -78,7 +140,30 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
|
|
|
78
140
|
'AGLedger is self-hosted, so the MCP server cannot guess your Server.\n');
|
|
79
141
|
process.exit(EXIT_USAGE_ERROR);
|
|
80
142
|
}
|
|
81
|
-
const
|
|
143
|
+
const oboCmd = process.env[ON_BEHALF_OF_ENV.CMD] || undefined;
|
|
144
|
+
const oboFile = process.env[ON_BEHALF_OF_ENV.FILE] || undefined;
|
|
145
|
+
let onBehalfOf;
|
|
146
|
+
if (oboCmd) {
|
|
147
|
+
if (oboFile) {
|
|
148
|
+
process.stderr.write(`Note: ${ON_BEHALF_OF_ENV.FILE} is set but not used: ${ON_BEHALF_OF_ENV.CMD} takes precedence.\n`);
|
|
149
|
+
}
|
|
150
|
+
onBehalfOf = { getToken: oidcTokenFromCommand(oboCmd, ON_BEHALF_OF_ENV.CMD), origin: ON_BEHALF_OF_ENV.CMD };
|
|
151
|
+
}
|
|
152
|
+
else if (oboFile) {
|
|
153
|
+
try {
|
|
154
|
+
accessSync(oboFile, fsConstants.R_OK);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
process.stderr.write(`Error: ${ON_BEHALF_OF_ENV.FILE} names a file that cannot be read: ${oboFile}\n`);
|
|
158
|
+
process.exit(EXIT_USAGE_ERROR);
|
|
159
|
+
}
|
|
160
|
+
onBehalfOf = { getToken: oidcTokenFromFile(oboFile, ON_BEHALF_OF_ENV.FILE), origin: ON_BEHALF_OF_ENV.FILE };
|
|
161
|
+
}
|
|
162
|
+
const server = new AgledgerMcpServer({
|
|
163
|
+
...(apiKey ? { apiKey } : { oidc }),
|
|
164
|
+
apiUrl,
|
|
165
|
+
...(onBehalfOf ? { onBehalfOf } : {}),
|
|
166
|
+
});
|
|
82
167
|
// A version-skewed zod resolution strips every argument description and the
|
|
83
168
|
// type of every JSON-string argument out of the published tool contract, and
|
|
84
169
|
// throws nothing while doing it. Two copies of the SAME version render fine,
|