@lumoauth/agent 1.1.0 → 1.3.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 +145 -5
- package/dist/index.d.mts +458 -4
- package/dist/index.d.ts +458 -4
- package/dist/index.js +858 -57
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +839 -33
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -10,8 +10,167 @@ import {
|
|
|
10
10
|
LumoAuthConfigError,
|
|
11
11
|
LumoAuthNetworkError,
|
|
12
12
|
ROUTES,
|
|
13
|
-
buildPath
|
|
13
|
+
buildPath,
|
|
14
|
+
fetchWithDpop
|
|
14
15
|
} from "@lumoauth/shared";
|
|
16
|
+
|
|
17
|
+
// src/client-assertion.ts
|
|
18
|
+
import {
|
|
19
|
+
createPrivateKey,
|
|
20
|
+
createPublicKey,
|
|
21
|
+
generateKeyPairSync,
|
|
22
|
+
randomBytes,
|
|
23
|
+
sign as cryptoSign,
|
|
24
|
+
constants as cryptoConstants
|
|
25
|
+
} from "crypto";
|
|
26
|
+
var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
27
|
+
var CLIENT_ASSERTION_TYP = "client-authentication+jwt";
|
|
28
|
+
var MAX_ASSERTION_LIFETIME_SECONDS = 600;
|
|
29
|
+
var RSA_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"];
|
|
30
|
+
var EC_ALGORITHM_BY_CURVE = {
|
|
31
|
+
prime256v1: "ES256",
|
|
32
|
+
"P-256": "ES256",
|
|
33
|
+
secp384r1: "ES384",
|
|
34
|
+
"P-384": "ES384",
|
|
35
|
+
secp521r1: "ES512",
|
|
36
|
+
"P-521": "ES512"
|
|
37
|
+
};
|
|
38
|
+
var ClientAssertionSigner = class _ClientAssertionSigner {
|
|
39
|
+
/** Generate a new key: ES256 (default), ES384, ES512, EdDSA, or an RSA algorithm (2048-bit key). */
|
|
40
|
+
static generate(algorithm = "ES256", keyId) {
|
|
41
|
+
let privateKey;
|
|
42
|
+
if (algorithm === "ES256" || algorithm === "ES384" || algorithm === "ES512") {
|
|
43
|
+
const namedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[algorithm];
|
|
44
|
+
privateKey = generateKeyPairSync("ec", { namedCurve }).privateKey;
|
|
45
|
+
} else if (algorithm === "EdDSA") {
|
|
46
|
+
privateKey = generateKeyPairSync("ed25519").privateKey;
|
|
47
|
+
} else if (RSA_ALGORITHMS.includes(algorithm)) {
|
|
48
|
+
privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey;
|
|
49
|
+
} else {
|
|
50
|
+
throw new Error(`Unsupported client assertion algorithm: ${String(algorithm)}`);
|
|
51
|
+
}
|
|
52
|
+
return new _ClientAssertionSigner({ privateKey, keyId, algorithm });
|
|
53
|
+
}
|
|
54
|
+
/** Load a PEM private key. */
|
|
55
|
+
static fromPem(pem, options = {}) {
|
|
56
|
+
return new _ClientAssertionSigner({ ...options, privateKeyPem: pem });
|
|
57
|
+
}
|
|
58
|
+
constructor(options) {
|
|
59
|
+
if (options.privateKey) {
|
|
60
|
+
this.key = options.privateKey;
|
|
61
|
+
} else if (options.privateKeyPem) {
|
|
62
|
+
this.key = createPrivateKey(options.privateKeyPem);
|
|
63
|
+
} else {
|
|
64
|
+
throw new Error("ClientAssertionSigner needs privateKeyPem or privateKey");
|
|
65
|
+
}
|
|
66
|
+
if (this.key.type !== "private") {
|
|
67
|
+
throw new Error("ClientAssertionSigner needs a private key");
|
|
68
|
+
}
|
|
69
|
+
const natural = naturalAlgorithm(this.key);
|
|
70
|
+
const chosen = options.algorithm ?? natural;
|
|
71
|
+
if (this.key.asymmetricKeyType === "rsa") {
|
|
72
|
+
if (!RSA_ALGORITHMS.includes(chosen)) {
|
|
73
|
+
throw new Error(`${chosen} does not fit an RSA key; use one of ${RSA_ALGORITHMS.join(", ")}`);
|
|
74
|
+
}
|
|
75
|
+
const bits = this.key.asymmetricKeyDetails?.modulusLength ?? 0;
|
|
76
|
+
if (bits < 2048) throw new Error("RSA keys must be at least 2048 bits");
|
|
77
|
+
} else if (chosen !== natural) {
|
|
78
|
+
throw new Error(`${chosen} does not fit this key; it signs with ${natural}`);
|
|
79
|
+
}
|
|
80
|
+
const lifetime = options.lifetimeSeconds ?? 60;
|
|
81
|
+
if (!Number.isInteger(lifetime) || lifetime < 1 || lifetime > MAX_ASSERTION_LIFETIME_SECONDS) {
|
|
82
|
+
throw new Error(`lifetimeSeconds must be an integer from 1 to ${MAX_ASSERTION_LIFETIME_SECONDS}`);
|
|
83
|
+
}
|
|
84
|
+
this.algorithm = chosen;
|
|
85
|
+
this.keyId = options.keyId;
|
|
86
|
+
this.lifetimeSeconds = lifetime;
|
|
87
|
+
this.now = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
88
|
+
}
|
|
89
|
+
/** Sign one assertion for `clientId` (the agent ID) and `audience` (the organization's issuer). */
|
|
90
|
+
create(clientId, audience) {
|
|
91
|
+
if (!clientId || !audience) {
|
|
92
|
+
throw new Error("clientId and audience are required for a client assertion");
|
|
93
|
+
}
|
|
94
|
+
const iat = this.now();
|
|
95
|
+
const header = { alg: this.algorithm, typ: CLIENT_ASSERTION_TYP };
|
|
96
|
+
if (this.keyId) header.kid = this.keyId;
|
|
97
|
+
const claims = {
|
|
98
|
+
iss: clientId,
|
|
99
|
+
sub: clientId,
|
|
100
|
+
aud: audience,
|
|
101
|
+
iat,
|
|
102
|
+
exp: iat + this.lifetimeSeconds,
|
|
103
|
+
jti: randomBytes(24).toString("base64url")
|
|
104
|
+
};
|
|
105
|
+
const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
|
|
106
|
+
return `${signingInput}.${signAssertion(this.algorithm, Buffer.from(signingInput, "utf8"), this.key).toString("base64url")}`;
|
|
107
|
+
}
|
|
108
|
+
/** The public key as a JWK with `kid` (when set), `alg` and `use: "sig"`. */
|
|
109
|
+
get jwk() {
|
|
110
|
+
const pub = createPublicKey(this.key).export({ format: "jwk" });
|
|
111
|
+
const out = { kty: pub.kty };
|
|
112
|
+
for (const member of ["crv", "x", "y", "n", "e"]) {
|
|
113
|
+
if (typeof pub[member] === "string") out[member] = pub[member];
|
|
114
|
+
}
|
|
115
|
+
if (this.keyId) out.kid = this.keyId;
|
|
116
|
+
out.alg = this.algorithm;
|
|
117
|
+
out.use = "sig";
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** `{ keys: [jwk] }`: what to register on the agent. */
|
|
121
|
+
get jwks() {
|
|
122
|
+
return { keys: [this.jwk] };
|
|
123
|
+
}
|
|
124
|
+
/** The private key as PKCS#8 PEM, for your secret store. */
|
|
125
|
+
get privateKeyPem() {
|
|
126
|
+
return this.key.export({ type: "pkcs8", format: "pem" }).toString();
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
function issuerFor(baseUrl, orgId) {
|
|
130
|
+
return `${baseUrl.replace(/\/+$/, "")}/orgs/${orgId}/api/v1`;
|
|
131
|
+
}
|
|
132
|
+
function naturalAlgorithm(key) {
|
|
133
|
+
switch (key.asymmetricKeyType) {
|
|
134
|
+
case "ec": {
|
|
135
|
+
const curve = String(key.asymmetricKeyDetails?.namedCurve ?? "");
|
|
136
|
+
const alg = EC_ALGORITHM_BY_CURVE[curve];
|
|
137
|
+
if (!alg) throw new Error(`EC keys must use P-256, P-384 or P-521 (got ${curve})`);
|
|
138
|
+
return alg;
|
|
139
|
+
}
|
|
140
|
+
case "ed25519":
|
|
141
|
+
return "EdDSA";
|
|
142
|
+
case "rsa":
|
|
143
|
+
return "RS256";
|
|
144
|
+
default:
|
|
145
|
+
throw new Error(`Unsupported key type: ${String(key.asymmetricKeyType)}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function signAssertion(alg, data, key) {
|
|
149
|
+
const hash = `sha${alg.slice(2)}`;
|
|
150
|
+
switch (alg) {
|
|
151
|
+
case "ES256":
|
|
152
|
+
case "ES384":
|
|
153
|
+
case "ES512":
|
|
154
|
+
return cryptoSign(hash, data, { key, dsaEncoding: "ieee-p1363" });
|
|
155
|
+
case "EdDSA":
|
|
156
|
+
return cryptoSign(null, data, key);
|
|
157
|
+
case "PS256":
|
|
158
|
+
case "PS384":
|
|
159
|
+
case "PS512":
|
|
160
|
+
return cryptoSign(hash, data, {
|
|
161
|
+
key,
|
|
162
|
+
padding: cryptoConstants.RSA_PKCS1_PSS_PADDING,
|
|
163
|
+
saltLength: cryptoConstants.RSA_PSS_SALTLEN_DIGEST
|
|
164
|
+
});
|
|
165
|
+
default:
|
|
166
|
+
return cryptoSign(hash, data, key);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function b64url(text) {
|
|
170
|
+
return Buffer.from(text, "utf8").toString("base64url");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/agent.ts
|
|
15
174
|
function envVar(name) {
|
|
16
175
|
return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
|
|
17
176
|
}
|
|
@@ -23,12 +182,22 @@ var LumoAgent = class {
|
|
|
23
182
|
this.baseUrl = (options.baseUrl ?? envVar("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
|
|
24
183
|
this.orgId = options.orgId ?? envVar("LUMOAUTH_ORG_ID") ?? "";
|
|
25
184
|
this.clientId = options.clientId ?? envVar("AGENT_CLIENT_ID") ?? "";
|
|
26
|
-
|
|
185
|
+
const privateKey = options.privateKey ?? envVar("AGENT_PRIVATE_KEY");
|
|
186
|
+
const keyId = options.keyId ?? envVar("AGENT_KEY_ID");
|
|
187
|
+
this.assertionSigner = privateKey === void 0 || privateKey === "" ? void 0 : privateKey instanceof ClientAssertionSigner ? privateKey : ClientAssertionSigner.fromPem(privateKey, { keyId });
|
|
188
|
+
this.clientSecret = options.clientSecret ?? (this.assertionSigner ? "" : envVar("AGENT_CLIENT_SECRET") ?? "");
|
|
189
|
+
this.issuer = options.issuer;
|
|
27
190
|
this.scopes = options.scopes;
|
|
28
191
|
this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
29
|
-
|
|
192
|
+
this.dpop = options.dpop;
|
|
193
|
+
if (!this.clientId || !this.clientSecret && !this.assertionSigner) {
|
|
30
194
|
throw new LumoAuthConfigError(
|
|
31
|
-
"Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET
|
|
195
|
+
"Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET (or AGENT_PRIVATE_KEY for a private key JWT agent), or pass clientId with clientSecret or privateKey to the constructor."
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
if (this.clientSecret && this.assertionSigner) {
|
|
199
|
+
throw new LumoAuthConfigError(
|
|
200
|
+
"Pass clientSecret or privateKey, not both: an agent authenticates with one method."
|
|
32
201
|
);
|
|
33
202
|
}
|
|
34
203
|
const tokenProvider = () => this.getAccessToken();
|
|
@@ -36,7 +205,8 @@ var LumoAgent = class {
|
|
|
36
205
|
baseUrl: this.baseUrl,
|
|
37
206
|
token: tokenProvider,
|
|
38
207
|
timeout: options.timeout,
|
|
39
|
-
fetch: options.fetch
|
|
208
|
+
fetch: options.fetch,
|
|
209
|
+
dpop: this.dpop
|
|
40
210
|
});
|
|
41
211
|
this.agents = new AgentsModule(http, this.orgId);
|
|
42
212
|
this.jit = new JitModule(http, this.orgId);
|
|
@@ -45,7 +215,9 @@ var LumoAgent = class {
|
|
|
45
215
|
baseUrl: this.baseUrl,
|
|
46
216
|
orgId: this.orgId,
|
|
47
217
|
token: tokenProvider,
|
|
48
|
-
fetch: options.fetch
|
|
218
|
+
fetch: options.fetch,
|
|
219
|
+
http,
|
|
220
|
+
dpop: this.dpop
|
|
49
221
|
});
|
|
50
222
|
this.delegation = new DelegationModule({
|
|
51
223
|
baseUrl: this.baseUrl,
|
|
@@ -54,7 +226,8 @@ var LumoAgent = class {
|
|
|
54
226
|
clientSecret: this.clientSecret,
|
|
55
227
|
redirectUri: options.redirectUri,
|
|
56
228
|
agentToken: tokenProvider,
|
|
57
|
-
fetch: options.fetch
|
|
229
|
+
fetch: options.fetch,
|
|
230
|
+
dpop: this.dpop
|
|
58
231
|
});
|
|
59
232
|
}
|
|
60
233
|
// ── Authentication ────────────────────────────────────────────────
|
|
@@ -66,19 +239,25 @@ var LumoAgent = class {
|
|
|
66
239
|
async authenticate(scopes) {
|
|
67
240
|
const form = {
|
|
68
241
|
grant_type: "client_credentials",
|
|
69
|
-
client_id: this.clientId
|
|
70
|
-
client_secret: this.clientSecret
|
|
242
|
+
client_id: this.clientId
|
|
71
243
|
};
|
|
244
|
+
if (this.assertionSigner) {
|
|
245
|
+
form.client_assertion_type = CLIENT_ASSERTION_TYPE;
|
|
246
|
+
form.client_assertion = this.createClientAssertion();
|
|
247
|
+
} else {
|
|
248
|
+
form.client_secret = this.clientSecret;
|
|
249
|
+
}
|
|
72
250
|
const requested = scopes ?? this.scopes;
|
|
73
251
|
if (requested?.length) form.scope = requested.join(" ");
|
|
74
252
|
const url = `${this.baseUrl}${buildPath(ROUTES["oauth.token"].path, { orgId: this.requireOrgId() })}`;
|
|
253
|
+
const init = {
|
|
254
|
+
method: "POST",
|
|
255
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
256
|
+
body: new URLSearchParams(form)
|
|
257
|
+
};
|
|
75
258
|
let res;
|
|
76
259
|
try {
|
|
77
|
-
res = await this.fetchFn(url,
|
|
78
|
-
method: "POST",
|
|
79
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
80
|
-
body: new URLSearchParams(form)
|
|
81
|
-
});
|
|
260
|
+
res = this.dpop ? await fetchWithDpop(this.fetchFn, url, init, this.dpop) : await this.fetchFn(url, init);
|
|
82
261
|
} catch (error) {
|
|
83
262
|
throw new LumoAuthNetworkError(
|
|
84
263
|
`Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -97,11 +276,39 @@ var LumoAgent = class {
|
|
|
97
276
|
const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
|
|
98
277
|
this.token = {
|
|
99
278
|
accessToken: body.access_token,
|
|
279
|
+
tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
|
|
100
280
|
refreshAt: Date.now() + expiresIn * 1e3 - TOKEN_REFRESH_BUFFER_MS,
|
|
101
281
|
scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : []
|
|
102
282
|
};
|
|
103
283
|
return this.token.accessToken;
|
|
104
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* `token_type` of the last successful authentication: `DPoP` when the
|
|
287
|
+
* token is sender-constrained, otherwise `Bearer`; `null` before the
|
|
288
|
+
* first sign-in. Present the token with that `Authorization` scheme.
|
|
289
|
+
*/
|
|
290
|
+
get tokenType() {
|
|
291
|
+
return this.token?.tokenType ?? null;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A new `private_key_jwt` client assertion for this agent (single-use),
|
|
295
|
+
* addressed to `issuer` or `{baseUrl}/orgs/{orgId}/api/v1`.
|
|
296
|
+
*/
|
|
297
|
+
createClientAssertion() {
|
|
298
|
+
if (!this.assertionSigner) {
|
|
299
|
+
throw new LumoAuthConfigError("This agent signs no client assertions: create it with privateKey.");
|
|
300
|
+
}
|
|
301
|
+
const audience = this.issuer ?? issuerFor(this.baseUrl, this.requireOrgId());
|
|
302
|
+
return this.assertionSigner.create(this.clientId, audience);
|
|
303
|
+
}
|
|
304
|
+
/** The client assertion signer this agent was configured with, if any. */
|
|
305
|
+
get clientAssertionSigner() {
|
|
306
|
+
return this.assertionSigner;
|
|
307
|
+
}
|
|
308
|
+
/** The DPoP proof signer this agent was configured with, if any. */
|
|
309
|
+
get dpopSigner() {
|
|
310
|
+
return this.dpop;
|
|
311
|
+
}
|
|
105
312
|
/**
|
|
106
313
|
* The current access token, re-authenticating transparently when it is
|
|
107
314
|
* missing or within 60 s of expiry. Concurrent callers share one
|
|
@@ -131,6 +338,13 @@ var LumoAgent = class {
|
|
|
131
338
|
async isAllowed(action, context) {
|
|
132
339
|
return this.agents.isAllowed(action, context);
|
|
133
340
|
}
|
|
341
|
+
/**
|
|
342
|
+
* May this agent run `tool` on the registered MCP server `serverId`?
|
|
343
|
+
* A deny returns `{ allowed: false }` and does not throw.
|
|
344
|
+
*/
|
|
345
|
+
async authorizeMcpTool(serverId, tool) {
|
|
346
|
+
return this.agents.authorizeMcpTool(serverId, tool);
|
|
347
|
+
}
|
|
134
348
|
/** The agent's own identity, capabilities, and workspace. */
|
|
135
349
|
async getCurrentAgent() {
|
|
136
350
|
return this.agents.me();
|
|
@@ -155,9 +369,9 @@ var LumoAgent = class {
|
|
|
155
369
|
};
|
|
156
370
|
|
|
157
371
|
// src/keys.ts
|
|
158
|
-
import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync } from "crypto";
|
|
372
|
+
import { createHash, createPublicKey as createPublicKey2, createPrivateKey as createPrivateKey2, generateKeyPairSync as generateKeyPairSync2 } from "crypto";
|
|
159
373
|
function generateKeypair(kid = "key-1") {
|
|
160
|
-
const { privateKey, publicKey } =
|
|
374
|
+
const { privateKey, publicKey } = generateKeyPairSync2("ed25519");
|
|
161
375
|
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
|
162
376
|
const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
|
|
163
377
|
const rawJwk = publicKey.export({ format: "jwk" });
|
|
@@ -188,7 +402,7 @@ function jwkThumbprint(jwk) {
|
|
|
188
402
|
return createHash("sha256").update(canonical, "utf8").digest("base64url");
|
|
189
403
|
}
|
|
190
404
|
function loadPrivateKey(pem) {
|
|
191
|
-
const key =
|
|
405
|
+
const key = createPrivateKey2(pem);
|
|
192
406
|
if (key.asymmetricKeyType === "ed25519") {
|
|
193
407
|
return { key, type: "ed25519" };
|
|
194
408
|
}
|
|
@@ -200,8 +414,8 @@ function loadPrivateKey(pem) {
|
|
|
200
414
|
);
|
|
201
415
|
}
|
|
202
416
|
function publicJwkFromPrivateKey(pem, kid) {
|
|
203
|
-
const priv =
|
|
204
|
-
const pub =
|
|
417
|
+
const priv = createPrivateKey2(pem);
|
|
418
|
+
const pub = createPublicKey2(priv);
|
|
205
419
|
const jwk = pub.export({ format: "jwk" });
|
|
206
420
|
if (kid) jwk.kid = kid;
|
|
207
421
|
return jwk;
|
|
@@ -211,8 +425,8 @@ function publicJwkFromPrivateKey(pem, kid) {
|
|
|
211
425
|
import {
|
|
212
426
|
constants,
|
|
213
427
|
createHash as createHash2,
|
|
214
|
-
randomBytes,
|
|
215
|
-
sign as
|
|
428
|
+
randomBytes as randomBytes2,
|
|
429
|
+
sign as cryptoSign2,
|
|
216
430
|
verify as cryptoVerify
|
|
217
431
|
} from "crypto";
|
|
218
432
|
var AAUTH_COVERED_COMPONENTS = [
|
|
@@ -230,7 +444,7 @@ function contentDigestSha256(body) {
|
|
|
230
444
|
return `sha-256=:${digest}:`;
|
|
231
445
|
}
|
|
232
446
|
function generateNonce() {
|
|
233
|
-
return
|
|
447
|
+
return randomBytes2(16).toString("base64url");
|
|
234
448
|
}
|
|
235
449
|
function buildSignatureBase(components, values, created, nonce) {
|
|
236
450
|
const lines = components.map((c) => `"${c}": ${values[c] ?? ""}`);
|
|
@@ -245,9 +459,9 @@ function signSignatureBase(signatureBase, privateKey) {
|
|
|
245
459
|
const data = Buffer.from(signatureBase, "utf8");
|
|
246
460
|
let signature;
|
|
247
461
|
if (privateKey.asymmetricKeyType === "ed25519") {
|
|
248
|
-
signature =
|
|
462
|
+
signature = cryptoSign2(null, data, privateKey);
|
|
249
463
|
} else {
|
|
250
|
-
signature =
|
|
464
|
+
signature = cryptoSign2("sha512", data, {
|
|
251
465
|
key: privateKey,
|
|
252
466
|
padding: constants.RSA_PKCS1_PSS_PADDING,
|
|
253
467
|
saltLength: constants.RSA_PSS_SALTLEN_DIGEST
|
|
@@ -310,7 +524,7 @@ function signRequest(privateKeyPem, method, url, options = {}) {
|
|
|
310
524
|
}
|
|
311
525
|
|
|
312
526
|
// src/verify.ts
|
|
313
|
-
import { constants as constants2, createPublicKey as
|
|
527
|
+
import { constants as constants2, createPublicKey as createPublicKey3, verify as cryptoVerify2 } from "crypto";
|
|
314
528
|
|
|
315
529
|
// src/errors.ts
|
|
316
530
|
import { LumoAuthError } from "@lumoauth/shared";
|
|
@@ -382,7 +596,7 @@ async function verifyAuthToken(token, options) {
|
|
|
382
596
|
throw new AAuthError(`Key not found: kid=${kid}`, "invalid_token");
|
|
383
597
|
}
|
|
384
598
|
assertAlgMatchesKey(alg, jwk);
|
|
385
|
-
const publicKey =
|
|
599
|
+
const publicKey = createPublicKey3({ key: jwk, format: "jwk" });
|
|
386
600
|
const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
|
|
387
601
|
const signature = Buffer.from(parts[2], "base64url");
|
|
388
602
|
if (!verifier(data, publicKey, signature)) {
|
|
@@ -697,17 +911,587 @@ var AAuthClient = class {
|
|
|
697
911
|
/** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
|
|
698
912
|
AAuthClient.generateKeypair = generateKeypair;
|
|
699
913
|
|
|
914
|
+
// src/dpop.ts
|
|
915
|
+
import {
|
|
916
|
+
createHash as createHash3,
|
|
917
|
+
createPrivateKey as createPrivateKey3,
|
|
918
|
+
createPublicKey as createPublicKey4,
|
|
919
|
+
generateKeyPairSync as generateKeyPairSync3,
|
|
920
|
+
randomBytes as randomBytes3,
|
|
921
|
+
sign as cryptoSign3
|
|
922
|
+
} from "crypto";
|
|
923
|
+
import { dpopHtu } from "@lumoauth/shared";
|
|
924
|
+
var DpopProofSigner = class _DpopProofSigner {
|
|
925
|
+
constructor(options) {
|
|
926
|
+
this.nonces = /* @__PURE__ */ new Map();
|
|
927
|
+
if (options.privateKey) {
|
|
928
|
+
this.key = options.privateKey;
|
|
929
|
+
} else if (options.privateKeyPem) {
|
|
930
|
+
this.key = createPrivateKey3(options.privateKeyPem);
|
|
931
|
+
} else {
|
|
932
|
+
throw new Error("DpopProofSigner needs privateKeyPem or privateKey");
|
|
933
|
+
}
|
|
934
|
+
if (this.key.type !== "private") {
|
|
935
|
+
throw new Error("DpopProofSigner needs a private key");
|
|
936
|
+
}
|
|
937
|
+
this.algorithm = algorithmFor(this.key);
|
|
938
|
+
this.now = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
939
|
+
const pub = createPublicKey4(this.key).export({ format: "jwk" });
|
|
940
|
+
this.jwk = publicMembers(pub);
|
|
941
|
+
this.thumbprint = jwkThumbprint(this.jwk);
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Generate a fresh key. ES256 (P-256) by default; pass `'EdDSA'` for an
|
|
945
|
+
* Ed25519 key or `'RS256'` for a 2048-bit RSA key.
|
|
946
|
+
*/
|
|
947
|
+
static generate(algorithm = "ES256") {
|
|
948
|
+
let privateKey;
|
|
949
|
+
switch (algorithm) {
|
|
950
|
+
case "ES256":
|
|
951
|
+
privateKey = generateKeyPairSync3("ec", { namedCurve: "P-256" }).privateKey;
|
|
952
|
+
break;
|
|
953
|
+
case "EdDSA":
|
|
954
|
+
privateKey = generateKeyPairSync3("ed25519").privateKey;
|
|
955
|
+
break;
|
|
956
|
+
case "RS256":
|
|
957
|
+
privateKey = generateKeyPairSync3("rsa", { modulusLength: 2048 }).privateKey;
|
|
958
|
+
break;
|
|
959
|
+
default:
|
|
960
|
+
throw new Error(`Unsupported DPoP algorithm: ${String(algorithm)}`);
|
|
961
|
+
}
|
|
962
|
+
return new _DpopProofSigner({ privateKey });
|
|
963
|
+
}
|
|
964
|
+
/** The private key as PKCS#8 PEM, for your secret store. */
|
|
965
|
+
get privateKeyPem() {
|
|
966
|
+
return this.key.export({ type: "pkcs8", format: "pem" }).toString();
|
|
967
|
+
}
|
|
968
|
+
/** Create one proof JWT. See the file comment for the claims. */
|
|
969
|
+
createProof(input) {
|
|
970
|
+
const method = input.method.toUpperCase();
|
|
971
|
+
const htu = dpopHtu(input.url);
|
|
972
|
+
const nonce = input.nonce ?? this.getNonce(input.url);
|
|
973
|
+
const header = { typ: "dpop+jwt", alg: this.algorithm, jwk: this.jwk };
|
|
974
|
+
const claims = {
|
|
975
|
+
jti: randomBytes3(24).toString("base64url"),
|
|
976
|
+
htm: method,
|
|
977
|
+
htu,
|
|
978
|
+
iat: this.now()
|
|
979
|
+
};
|
|
980
|
+
if (input.accessToken) claims.ath = dpopAth(input.accessToken);
|
|
981
|
+
if (nonce) claims.nonce = nonce;
|
|
982
|
+
const signingInput = `${b64url2(JSON.stringify(header))}.${b64url2(JSON.stringify(claims))}`;
|
|
983
|
+
const signature = signJws(this.algorithm, Buffer.from(signingInput, "utf8"), this.key);
|
|
984
|
+
return `${signingInput}.${signature.toString("base64url")}`;
|
|
985
|
+
}
|
|
986
|
+
/** Remember the latest server nonce for the origin of `url`. */
|
|
987
|
+
setNonce(url, nonce) {
|
|
988
|
+
this.nonces.set(originOf(url), nonce);
|
|
989
|
+
}
|
|
990
|
+
/** The remembered nonce for the origin of `url`, if any. */
|
|
991
|
+
getNonce(url) {
|
|
992
|
+
return this.nonces.get(originOf(url));
|
|
993
|
+
}
|
|
994
|
+
/** Forget every remembered nonce. */
|
|
995
|
+
clearNonces() {
|
|
996
|
+
this.nonces.clear();
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
function dpopAth(accessToken) {
|
|
1000
|
+
return createHash3("sha256").update(accessToken, "ascii").digest("base64url");
|
|
1001
|
+
}
|
|
1002
|
+
function signJws(alg, data, key) {
|
|
1003
|
+
switch (alg) {
|
|
1004
|
+
case "ES256":
|
|
1005
|
+
return cryptoSign3("sha256", data, { key, dsaEncoding: "ieee-p1363" });
|
|
1006
|
+
case "EdDSA":
|
|
1007
|
+
return cryptoSign3(null, data, key);
|
|
1008
|
+
case "RS256":
|
|
1009
|
+
return cryptoSign3("sha256", data, key);
|
|
1010
|
+
default:
|
|
1011
|
+
throw new Error(`Unsupported DPoP algorithm: ${String(alg)}`);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
function algorithmFor(key) {
|
|
1015
|
+
switch (key.asymmetricKeyType) {
|
|
1016
|
+
case "ec": {
|
|
1017
|
+
const curve = key.asymmetricKeyDetails?.namedCurve;
|
|
1018
|
+
if (curve !== "prime256v1" && curve !== "P-256") {
|
|
1019
|
+
throw new Error(`DPoP EC keys must use P-256 (got ${String(curve)})`);
|
|
1020
|
+
}
|
|
1021
|
+
return "ES256";
|
|
1022
|
+
}
|
|
1023
|
+
case "ed25519":
|
|
1024
|
+
return "EdDSA";
|
|
1025
|
+
case "rsa":
|
|
1026
|
+
return "RS256";
|
|
1027
|
+
default:
|
|
1028
|
+
throw new Error(`Unsupported DPoP key type: ${String(key.asymmetricKeyType)}`);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
function publicMembers(jwk) {
|
|
1032
|
+
const out = { kty: jwk.kty };
|
|
1033
|
+
for (const member of ["crv", "x", "y", "n", "e"]) {
|
|
1034
|
+
if (typeof jwk[member] === "string") out[member] = jwk[member];
|
|
1035
|
+
}
|
|
1036
|
+
return out;
|
|
1037
|
+
}
|
|
1038
|
+
function originOf(url) {
|
|
1039
|
+
return new URL(url).origin;
|
|
1040
|
+
}
|
|
1041
|
+
function b64url2(text) {
|
|
1042
|
+
return Buffer.from(text, "utf8").toString("base64url");
|
|
1043
|
+
}
|
|
1044
|
+
|
|
700
1045
|
// src/index.ts
|
|
701
1046
|
import {
|
|
702
|
-
|
|
1047
|
+
fetchWithDpop as fetchWithDpop3,
|
|
1048
|
+
buildDpopHeaders,
|
|
1049
|
+
dpopHtu as dpopHtu3,
|
|
1050
|
+
DPOP_SCHEME as DPOP_SCHEME2,
|
|
1051
|
+
DPOP_NONCE_HEADER,
|
|
1052
|
+
USE_DPOP_NONCE
|
|
1053
|
+
} from "@lumoauth/shared";
|
|
1054
|
+
|
|
1055
|
+
// src/attest.ts
|
|
1056
|
+
import {
|
|
703
1057
|
LumoAuthApiError as LumoAuthApiError2,
|
|
1058
|
+
LumoAuthConfigError as LumoAuthConfigError3,
|
|
1059
|
+
LumoAuthNetworkError as LumoAuthNetworkError3,
|
|
1060
|
+
fetchWithDpop as fetchWithDpop2
|
|
1061
|
+
} from "@lumoauth/shared";
|
|
1062
|
+
function envVar3(name) {
|
|
1063
|
+
return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
|
|
1064
|
+
}
|
|
1065
|
+
async function attestWorkload(options) {
|
|
1066
|
+
const baseUrl = (options.baseUrl ?? envVar3("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
|
|
1067
|
+
const orgId = options.orgId ?? envVar3("LUMOAUTH_ORG_ID") ?? "";
|
|
1068
|
+
if (!orgId) {
|
|
1069
|
+
throw new LumoAuthConfigError3("attestWorkload requires orgId (or LUMOAUTH_ORG_ID).");
|
|
1070
|
+
}
|
|
1071
|
+
if (!options.agentId || !options.attestationToken) {
|
|
1072
|
+
throw new LumoAuthConfigError3("attestWorkload requires agentId and attestationToken.");
|
|
1073
|
+
}
|
|
1074
|
+
const url = `${baseUrl}/orgs/${encodeURIComponent(orgId)}/api/v1/agents/${encodeURIComponent(options.agentId)}/attest`;
|
|
1075
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1076
|
+
const init = {
|
|
1077
|
+
method: "POST",
|
|
1078
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1079
|
+
body: JSON.stringify({ attestation_token: options.attestationToken })
|
|
1080
|
+
};
|
|
1081
|
+
let res;
|
|
1082
|
+
try {
|
|
1083
|
+
res = options.dpop ? await fetchWithDpop2(fetchFn, url, init, options.dpop) : await fetchFn(url, init);
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
throw new LumoAuthNetworkError3(
|
|
1086
|
+
`Agent attestation failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1087
|
+
error
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
const body = await res.json().catch(() => ({}));
|
|
1091
|
+
if (!res.ok || typeof body.access_token !== "string") {
|
|
1092
|
+
throw new LumoAuthApiError2(
|
|
1093
|
+
typeof body.error_description === "string" ? body.error_description : `Agent attestation failed (HTTP ${res.status})`,
|
|
1094
|
+
typeof body.error === "string" ? body.error : "ATTESTATION_ERROR",
|
|
1095
|
+
res.status,
|
|
1096
|
+
body
|
|
1097
|
+
);
|
|
1098
|
+
}
|
|
1099
|
+
return {
|
|
1100
|
+
accessToken: body.access_token,
|
|
1101
|
+
tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
|
|
1102
|
+
expiresIn: typeof body.expires_in === "number" ? body.expires_in : null,
|
|
1103
|
+
scope: typeof body.scope === "string" ? body.scope : null,
|
|
1104
|
+
identity: typeof body.identity === "object" && body.identity !== null ? body.identity : {}
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// src/access-token.ts
|
|
1109
|
+
import { constants as constants3, createHash as createHash4, createPublicKey as createPublicKey5, verify as cryptoVerify3 } from "crypto";
|
|
1110
|
+
import { DPOP_SCHEME, LumoAuthError as LumoAuthError2, dpopHtu as dpopHtu2 } from "@lumoauth/shared";
|
|
1111
|
+
var AccessTokenError = class extends LumoAuthError2 {
|
|
1112
|
+
constructor(message, code, statusCode = 401) {
|
|
1113
|
+
super(message, code, statusCode);
|
|
1114
|
+
this.name = "AccessTokenError";
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
var AT_JWT_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
|
|
1118
|
+
var DPOP_PROOF_TYP = "dpop+jwt";
|
|
1119
|
+
var DPOP_IAT_FUTURE_SECONDS = 60;
|
|
1120
|
+
var DPOP_IAT_PAST_SECONDS = 300;
|
|
1121
|
+
var DPOP_JTI_TTL_SECONDS = 300;
|
|
1122
|
+
var DPOP_JTI_MIN_LENGTH = 16;
|
|
1123
|
+
var JWKS_REFETCH_INTERVAL_MS = 3e4;
|
|
1124
|
+
var JWS_VERIFIERS2 = {
|
|
1125
|
+
RS256: (d, k, s) => cryptoVerify3("sha256", d, k, s),
|
|
1126
|
+
RS384: (d, k, s) => cryptoVerify3("sha384", d, k, s),
|
|
1127
|
+
RS512: (d, k, s) => cryptoVerify3("sha512", d, k, s),
|
|
1128
|
+
PS256: (d, k, s) => cryptoVerify3("sha256", d, pss2(k), s),
|
|
1129
|
+
PS384: (d, k, s) => cryptoVerify3("sha384", d, pss2(k), s),
|
|
1130
|
+
PS512: (d, k, s) => cryptoVerify3("sha512", d, pss2(k), s),
|
|
1131
|
+
ES256: (d, k, s) => cryptoVerify3("sha256", d, p13632(k), s),
|
|
1132
|
+
ES384: (d, k, s) => cryptoVerify3("sha384", d, p13632(k), s),
|
|
1133
|
+
ES512: (d, k, s) => cryptoVerify3("sha512", d, p13632(k), s),
|
|
1134
|
+
EdDSA: (d, k, s) => cryptoVerify3(null, d, k, s)
|
|
1135
|
+
};
|
|
1136
|
+
var DPOP_ALG_KEYS = {
|
|
1137
|
+
ES256: { kty: "EC", crv: "P-256" },
|
|
1138
|
+
ES384: { kty: "EC", crv: "P-384" },
|
|
1139
|
+
ES512: { kty: "EC", crv: "P-521" },
|
|
1140
|
+
RS256: { kty: "RSA" },
|
|
1141
|
+
RS384: { kty: "RSA" },
|
|
1142
|
+
RS512: { kty: "RSA" },
|
|
1143
|
+
PS256: { kty: "RSA" },
|
|
1144
|
+
PS384: { kty: "RSA" },
|
|
1145
|
+
PS512: { kty: "RSA" },
|
|
1146
|
+
EdDSA: { kty: "OKP", crv: "Ed25519" }
|
|
1147
|
+
};
|
|
1148
|
+
function pss2(key) {
|
|
1149
|
+
return { key, padding: constants3.RSA_PKCS1_PSS_PADDING, saltLength: constants3.RSA_PSS_SALTLEN_DIGEST };
|
|
1150
|
+
}
|
|
1151
|
+
function p13632(key) {
|
|
1152
|
+
return { key, dsaEncoding: "ieee-p1363" };
|
|
1153
|
+
}
|
|
1154
|
+
var JwksCache = class {
|
|
1155
|
+
constructor(fetchFn) {
|
|
1156
|
+
this.fetchFn = fetchFn;
|
|
1157
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Find `kid` in the issuer's JWKS. An unknown `kid` triggers one refetch
|
|
1161
|
+
* (a key rotation); repeated misses refetch at most every 30 s, so a
|
|
1162
|
+
* stream of bogus tokens cannot hammer the JWKS endpoint.
|
|
1163
|
+
*/
|
|
1164
|
+
async find(issuer, kid, fetchFn) {
|
|
1165
|
+
const doFetch = fetchFn ?? this.fetchFn ?? globalThis.fetch;
|
|
1166
|
+
let entry = this.entries.get(issuer);
|
|
1167
|
+
if (!entry) {
|
|
1168
|
+
entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: 0 };
|
|
1169
|
+
this.entries.set(issuer, entry);
|
|
1170
|
+
}
|
|
1171
|
+
let jwk = entry.keys.find((k) => k.kid === kid);
|
|
1172
|
+
if (!jwk && Date.now() - entry.missRefetchAt >= JWKS_REFETCH_INTERVAL_MS) {
|
|
1173
|
+
entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: Date.now() };
|
|
1174
|
+
this.entries.set(issuer, entry);
|
|
1175
|
+
jwk = entry.keys.find((k) => k.kid === kid);
|
|
1176
|
+
}
|
|
1177
|
+
return jwk;
|
|
1178
|
+
}
|
|
1179
|
+
/** Drop the cached keys of one issuer, or of all when omitted. */
|
|
1180
|
+
clear(issuer) {
|
|
1181
|
+
if (issuer) this.entries.delete(issuer);
|
|
1182
|
+
else this.entries.clear();
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
async function fetchJwks(issuer, doFetch) {
|
|
1186
|
+
const base = issuer.replace(/\/+$/, "");
|
|
1187
|
+
const discovery = await doFetch(`${base}/.well-known/openid-configuration`, {
|
|
1188
|
+
headers: { Accept: "application/json" }
|
|
1189
|
+
});
|
|
1190
|
+
if (!discovery.ok) {
|
|
1191
|
+
throw new AccessTokenError(`Failed to fetch issuer discovery (HTTP ${discovery.status})`, "jwks_fetch_failed", 503);
|
|
1192
|
+
}
|
|
1193
|
+
const metadata = await discovery.json();
|
|
1194
|
+
const jwksUri = typeof metadata.jwks_uri === "string" ? metadata.jwks_uri : `${base}/.well-known/jwks.json`;
|
|
1195
|
+
const response = await doFetch(jwksUri, { headers: { Accept: "application/json" } });
|
|
1196
|
+
if (!response.ok) {
|
|
1197
|
+
throw new AccessTokenError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, "jwks_fetch_failed", 503);
|
|
1198
|
+
}
|
|
1199
|
+
const jwks = await response.json();
|
|
1200
|
+
if (!Array.isArray(jwks.keys)) {
|
|
1201
|
+
throw new AccessTokenError("Issuer JWKS is malformed", "jwks_fetch_failed", 503);
|
|
1202
|
+
}
|
|
1203
|
+
return jwks.keys;
|
|
1204
|
+
}
|
|
1205
|
+
var sharedJwksCache = new JwksCache();
|
|
1206
|
+
var InMemoryDpopReplayCache = class {
|
|
1207
|
+
constructor(now = () => Date.now()) {
|
|
1208
|
+
this.now = now;
|
|
1209
|
+
this.seen = /* @__PURE__ */ new Map();
|
|
1210
|
+
}
|
|
1211
|
+
add(key, ttlSeconds) {
|
|
1212
|
+
const now = this.now();
|
|
1213
|
+
if (this.seen.size > 0 && this.seen.size % 256 === 0) this.prune(now);
|
|
1214
|
+
const expiresAt = this.seen.get(key);
|
|
1215
|
+
if (expiresAt !== void 0 && expiresAt > now) return false;
|
|
1216
|
+
this.seen.set(key, now + ttlSeconds * 1e3);
|
|
1217
|
+
return true;
|
|
1218
|
+
}
|
|
1219
|
+
prune(now) {
|
|
1220
|
+
for (const [key, expiresAt] of this.seen) {
|
|
1221
|
+
if (expiresAt <= now) this.seen.delete(key);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
var sharedReplayCache = new InMemoryDpopReplayCache();
|
|
1226
|
+
function decodeSegment2(segment) {
|
|
1227
|
+
try {
|
|
1228
|
+
return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
|
|
1229
|
+
} catch {
|
|
1230
|
+
throw new AccessTokenError("Invalid JWT encoding", "invalid_token");
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
function isObject(value) {
|
|
1234
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1235
|
+
}
|
|
1236
|
+
function parseAuthorizationHeader(header) {
|
|
1237
|
+
if (!header) return null;
|
|
1238
|
+
const match = /^\s*([A-Za-z][A-Za-z0-9+.-]*)\s+(\S+)\s*$/.exec(header);
|
|
1239
|
+
return match ? { scheme: match[1], token: match[2] } : null;
|
|
1240
|
+
}
|
|
1241
|
+
function accessTokenScopes(claims) {
|
|
1242
|
+
return typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
|
|
1243
|
+
}
|
|
1244
|
+
async function verifyAccessToken(token, options) {
|
|
1245
|
+
if (typeof token !== "string" || token === "") {
|
|
1246
|
+
throw new AccessTokenError("Missing access token", "invalid_token");
|
|
1247
|
+
}
|
|
1248
|
+
const parts = token.split(".");
|
|
1249
|
+
if (parts.length !== 3) {
|
|
1250
|
+
throw new AccessTokenError("Invalid JWT format", "invalid_token");
|
|
1251
|
+
}
|
|
1252
|
+
const header = decodeSegment2(parts[0]);
|
|
1253
|
+
const claims = decodeSegment2(parts[1]);
|
|
1254
|
+
if (!isObject(header) || !isObject(claims)) {
|
|
1255
|
+
throw new AccessTokenError("Invalid JWT format", "invalid_token");
|
|
1256
|
+
}
|
|
1257
|
+
if (typeof header.typ !== "string" || !AT_JWT_TYPES.has(header.typ)) {
|
|
1258
|
+
throw new AccessTokenError(`Unexpected token type: ${String(header.typ)}`, "invalid_token");
|
|
1259
|
+
}
|
|
1260
|
+
const alg = typeof header.alg === "string" ? header.alg : "";
|
|
1261
|
+
const kid = typeof header.kid === "string" ? header.kid : "";
|
|
1262
|
+
if (!alg || !kid) {
|
|
1263
|
+
throw new AccessTokenError("Missing kid or alg in JOSE header", "invalid_token");
|
|
1264
|
+
}
|
|
1265
|
+
const verifier = JWS_VERIFIERS2[alg];
|
|
1266
|
+
if (!verifier) {
|
|
1267
|
+
throw new AccessTokenError(`Disallowed JWS algorithm: ${alg}`, "invalid_token");
|
|
1268
|
+
}
|
|
1269
|
+
if (claims.iss !== options.issuer) {
|
|
1270
|
+
throw new AccessTokenError("Untrusted issuer", "invalid_token");
|
|
1271
|
+
}
|
|
1272
|
+
let jwk;
|
|
1273
|
+
if (options.jwks) {
|
|
1274
|
+
jwk = options.jwks.keys.find((k) => k.kid === kid);
|
|
1275
|
+
} else {
|
|
1276
|
+
const cache = options.jwksCache ?? sharedJwksCache;
|
|
1277
|
+
jwk = await cache.find(options.issuer, kid, options.fetch);
|
|
1278
|
+
}
|
|
1279
|
+
if (!jwk) {
|
|
1280
|
+
throw new AccessTokenError(`Key not found: kid=${kid}`, "invalid_token");
|
|
1281
|
+
}
|
|
1282
|
+
assertAlgMatchesKey2(alg, jwk);
|
|
1283
|
+
const publicKey = createPublicKey5({ key: jwk, format: "jwk" });
|
|
1284
|
+
const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
|
|
1285
|
+
const signature = Buffer.from(parts[2], "base64url");
|
|
1286
|
+
if (!verifier(data, publicKey, signature)) {
|
|
1287
|
+
throw new AccessTokenError("Signature verification failed", "invalid_token");
|
|
1288
|
+
}
|
|
1289
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1290
|
+
const skew = options.clockSkew ?? 60;
|
|
1291
|
+
if (typeof claims.exp !== "number" || claims.exp < now - skew) {
|
|
1292
|
+
throw new AccessTokenError("Access token expired", "invalid_token");
|
|
1293
|
+
}
|
|
1294
|
+
if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || claims.nbf > now + skew)) {
|
|
1295
|
+
throw new AccessTokenError("Access token not yet valid", "invalid_token");
|
|
1296
|
+
}
|
|
1297
|
+
const aud = claims.aud;
|
|
1298
|
+
const audiences = typeof aud === "string" ? [aud] : Array.isArray(aud) ? aud : [];
|
|
1299
|
+
if (!audiences.includes(options.resource)) {
|
|
1300
|
+
throw new AccessTokenError("Invalid audience", "invalid_token");
|
|
1301
|
+
}
|
|
1302
|
+
if (typeof claims.sub !== "string" || claims.sub === "") {
|
|
1303
|
+
throw new AccessTokenError("Missing sub claim", "invalid_token");
|
|
1304
|
+
}
|
|
1305
|
+
if (claims.token_use === "test") {
|
|
1306
|
+
throw new AccessTokenError("Test tokens are not accepted by resource servers", "invalid_token");
|
|
1307
|
+
}
|
|
1308
|
+
const cnf = isObject(claims.cnf) ? claims.cnf : void 0;
|
|
1309
|
+
const jkt = typeof cnf?.jkt === "string" ? cnf.jkt : void 0;
|
|
1310
|
+
if (jkt) {
|
|
1311
|
+
await verifyDpopBinding(token, jkt, options);
|
|
1312
|
+
} else if (options.requireDpop) {
|
|
1313
|
+
throw new AccessTokenError("Access token is not DPoP-bound", "invalid_token");
|
|
1314
|
+
} else if (options.dpop?.authorizationScheme && options.dpop.authorizationScheme.toLowerCase() === DPOP_SCHEME.toLowerCase()) {
|
|
1315
|
+
throw new AccessTokenError("Access token is not DPoP-bound but was presented with the DPoP scheme", "invalid_token");
|
|
1316
|
+
}
|
|
1317
|
+
return claims;
|
|
1318
|
+
}
|
|
1319
|
+
async function verifyDpopBinding(token, jkt, options) {
|
|
1320
|
+
const incoming = options.dpop;
|
|
1321
|
+
if (!incoming) {
|
|
1322
|
+
throw new AccessTokenError(
|
|
1323
|
+
"Access token is DPoP-bound: pass the incoming request (method, url, proof, authorizationScheme) in `dpop`",
|
|
1324
|
+
"invalid_dpop_proof"
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
if ((incoming.authorizationScheme ?? "").toLowerCase() !== DPOP_SCHEME.toLowerCase()) {
|
|
1328
|
+
throw new AccessTokenError("DPoP-bound access token must be presented with the DPoP scheme", "invalid_token");
|
|
1329
|
+
}
|
|
1330
|
+
if (!incoming.proof) {
|
|
1331
|
+
throw new AccessTokenError("DPoP proof required for sender-constrained token", "invalid_dpop_proof");
|
|
1332
|
+
}
|
|
1333
|
+
const proof = await verifyDpopProof(incoming.proof, {
|
|
1334
|
+
method: incoming.method,
|
|
1335
|
+
url: incoming.url,
|
|
1336
|
+
accessToken: token,
|
|
1337
|
+
nonce: incoming.nonce,
|
|
1338
|
+
replayCache: options.replayCache
|
|
1339
|
+
});
|
|
1340
|
+
if (proof.thumbprint !== jkt) {
|
|
1341
|
+
throw new AccessTokenError("DPoP key does not match token binding", "invalid_dpop_proof");
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
function assertAlgMatchesKey2(alg, jwk) {
|
|
1345
|
+
const compatible = jwk.kty === "RSA" && (alg.startsWith("RS") || alg.startsWith("PS")) || jwk.kty === "EC" && alg.startsWith("ES") || jwk.kty === "OKP" && alg === "EdDSA";
|
|
1346
|
+
if (!compatible) {
|
|
1347
|
+
throw new AccessTokenError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, "invalid_token");
|
|
1348
|
+
}
|
|
1349
|
+
if (jwk.alg && jwk.alg !== alg) {
|
|
1350
|
+
throw new AccessTokenError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, "invalid_token");
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
async function verifyDpopProof(proof, options) {
|
|
1354
|
+
const parts = proof.split(".");
|
|
1355
|
+
if (parts.length !== 3) {
|
|
1356
|
+
throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
|
|
1357
|
+
}
|
|
1358
|
+
let header;
|
|
1359
|
+
let claims;
|
|
1360
|
+
try {
|
|
1361
|
+
header = decodeSegment2(parts[0]);
|
|
1362
|
+
claims = decodeSegment2(parts[1]);
|
|
1363
|
+
} catch {
|
|
1364
|
+
throw new AccessTokenError("Invalid DPoP proof encoding", "invalid_dpop_proof");
|
|
1365
|
+
}
|
|
1366
|
+
if (!isObject(header) || !isObject(claims)) {
|
|
1367
|
+
throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
|
|
1368
|
+
}
|
|
1369
|
+
if (header.typ !== DPOP_PROOF_TYP) {
|
|
1370
|
+
throw new AccessTokenError("DPoP proof typ must be dpop+jwt", "invalid_dpop_proof");
|
|
1371
|
+
}
|
|
1372
|
+
const alg = typeof header.alg === "string" ? header.alg : "";
|
|
1373
|
+
const expectedKey = DPOP_ALG_KEYS[alg];
|
|
1374
|
+
if (!expectedKey) {
|
|
1375
|
+
throw new AccessTokenError(`Disallowed DPoP proof algorithm: ${alg || "(none)"}`, "invalid_dpop_proof");
|
|
1376
|
+
}
|
|
1377
|
+
const jwk = header.jwk;
|
|
1378
|
+
if (!isObject(jwk) || typeof jwk.kty !== "string") {
|
|
1379
|
+
throw new AccessTokenError("DPoP proof is missing its jwk", "invalid_dpop_proof");
|
|
1380
|
+
}
|
|
1381
|
+
if ("d" in jwk) {
|
|
1382
|
+
throw new AccessTokenError("DPoP proof jwk must not carry private members", "invalid_dpop_proof");
|
|
1383
|
+
}
|
|
1384
|
+
if (jwk.kty !== expectedKey.kty || expectedKey.crv && jwk.crv !== expectedKey.crv) {
|
|
1385
|
+
throw new AccessTokenError(`DPoP proof jwk does not match ${alg}`, "invalid_dpop_proof");
|
|
1386
|
+
}
|
|
1387
|
+
if (typeof jwk.alg === "string" && jwk.alg !== alg) {
|
|
1388
|
+
throw new AccessTokenError("DPoP proof jwk alg does not match the header", "invalid_dpop_proof");
|
|
1389
|
+
}
|
|
1390
|
+
let publicKey;
|
|
1391
|
+
try {
|
|
1392
|
+
publicKey = createPublicKey5({ key: jwk, format: "jwk" });
|
|
1393
|
+
} catch {
|
|
1394
|
+
throw new AccessTokenError("DPoP proof jwk is not a valid public key", "invalid_dpop_proof");
|
|
1395
|
+
}
|
|
1396
|
+
const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
|
|
1397
|
+
const signature = Buffer.from(parts[2], "base64url");
|
|
1398
|
+
let valid = false;
|
|
1399
|
+
try {
|
|
1400
|
+
valid = JWS_VERIFIERS2[alg](data, publicKey, signature);
|
|
1401
|
+
} catch {
|
|
1402
|
+
valid = false;
|
|
1403
|
+
}
|
|
1404
|
+
if (!valid) {
|
|
1405
|
+
throw new AccessTokenError("DPoP proof signature verification failed", "invalid_dpop_proof");
|
|
1406
|
+
}
|
|
1407
|
+
if (typeof claims.htm !== "string" || claims.htm.toUpperCase() !== options.method.toUpperCase()) {
|
|
1408
|
+
throw new AccessTokenError("DPoP proof htm does not match the request method", "invalid_dpop_proof");
|
|
1409
|
+
}
|
|
1410
|
+
if (typeof claims.htu !== "string" || !htuMatches(claims.htu, options.url)) {
|
|
1411
|
+
throw new AccessTokenError("DPoP proof htu does not match the request URL", "invalid_dpop_proof");
|
|
1412
|
+
}
|
|
1413
|
+
const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
|
|
1414
|
+
if (typeof claims.iat !== "number" || claims.iat > now + DPOP_IAT_FUTURE_SECONDS || claims.iat < now - DPOP_IAT_PAST_SECONDS) {
|
|
1415
|
+
throw new AccessTokenError("DPoP proof iat is outside the accepted window", "invalid_dpop_proof");
|
|
1416
|
+
}
|
|
1417
|
+
if (typeof claims.jti !== "string" || claims.jti.length < DPOP_JTI_MIN_LENGTH) {
|
|
1418
|
+
throw new AccessTokenError("DPoP proof jti is missing or too short", "invalid_dpop_proof");
|
|
1419
|
+
}
|
|
1420
|
+
if (options.nonce !== void 0 && claims.nonce !== options.nonce) {
|
|
1421
|
+
throw new AccessTokenError("DPoP proof nonce does not match", "invalid_dpop_proof");
|
|
1422
|
+
}
|
|
1423
|
+
if (options.accessToken !== void 0) {
|
|
1424
|
+
const expectedAth = createHash4("sha256").update(options.accessToken, "ascii").digest("base64url");
|
|
1425
|
+
if (claims.ath !== expectedAth) {
|
|
1426
|
+
throw new AccessTokenError("DPoP proof ath does not match the access token", "invalid_dpop_proof");
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
const thumbprint = jwkThumbprint(jwk);
|
|
1430
|
+
const cache = options.replayCache ?? sharedReplayCache;
|
|
1431
|
+
if (!await cache.add(`${thumbprint}:${claims.jti}`, DPOP_JTI_TTL_SECONDS)) {
|
|
1432
|
+
throw new AccessTokenError("DPoP proof jti was already used", "invalid_dpop_proof");
|
|
1433
|
+
}
|
|
1434
|
+
return { jwk, thumbprint, claims };
|
|
1435
|
+
}
|
|
1436
|
+
function htuMatches(htu, requestUrl) {
|
|
1437
|
+
try {
|
|
1438
|
+
return dpopHtu2(htu) === dpopHtu2(requestUrl);
|
|
1439
|
+
} catch {
|
|
1440
|
+
return false;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
function createAccessTokenVerifier(options) {
|
|
1444
|
+
const jwksCache = new JwksCache(options.fetch);
|
|
1445
|
+
const replayCache = options.replayCache ?? new InMemoryDpopReplayCache();
|
|
1446
|
+
const base = { ...options, jwksCache, replayCache };
|
|
1447
|
+
return {
|
|
1448
|
+
verify: (token, dpop) => verifyAccessToken(token, dpop ? { ...base, dpop } : base),
|
|
1449
|
+
verifyRequest: async (request) => {
|
|
1450
|
+
const authorization = parseAuthorizationHeader(headerValue(request.headers, "authorization"));
|
|
1451
|
+
if (!authorization) {
|
|
1452
|
+
throw new AccessTokenError("Missing or malformed Authorization header", "invalid_token");
|
|
1453
|
+
}
|
|
1454
|
+
if (!["bearer", "dpop"].includes(authorization.scheme.toLowerCase())) {
|
|
1455
|
+
throw new AccessTokenError(`Unsupported authorization scheme: ${authorization.scheme}`, "invalid_token");
|
|
1456
|
+
}
|
|
1457
|
+
return verifyAccessToken(authorization.token, {
|
|
1458
|
+
...base,
|
|
1459
|
+
dpop: {
|
|
1460
|
+
method: request.method,
|
|
1461
|
+
url: request.url,
|
|
1462
|
+
proof: headerValue(request.headers, "dpop"),
|
|
1463
|
+
authorizationScheme: authorization.scheme,
|
|
1464
|
+
nonce: request.nonce
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
},
|
|
1468
|
+
clearCache: () => jwksCache.clear()
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
function headerValue(headers, name) {
|
|
1472
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
1473
|
+
return headers.get(name);
|
|
1474
|
+
}
|
|
1475
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
1476
|
+
if (key.toLowerCase() === name) {
|
|
1477
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
1478
|
+
return value ?? null;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
return null;
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// src/index.ts
|
|
1485
|
+
import {
|
|
1486
|
+
LumoAuthError as LumoAuthError3,
|
|
1487
|
+
LumoAuthApiError as LumoAuthApiError3,
|
|
704
1488
|
LumoAuthAuthenticationError,
|
|
705
1489
|
LumoAuthPermissionDeniedError,
|
|
706
1490
|
LumoAuthNotFoundError,
|
|
707
1491
|
LumoAuthRateLimitError,
|
|
708
1492
|
LumoAuthValidationError,
|
|
709
|
-
LumoAuthConfigError as
|
|
710
|
-
LumoAuthNetworkError as
|
|
1493
|
+
LumoAuthConfigError as LumoAuthConfigError4,
|
|
1494
|
+
LumoAuthNetworkError as LumoAuthNetworkError4,
|
|
711
1495
|
LumoAuthApprovalDeniedError,
|
|
712
1496
|
LumoAuthApprovalTimeoutError,
|
|
713
1497
|
LumoAuthApprovalNotDeliveredError,
|
|
@@ -717,31 +1501,53 @@ export {
|
|
|
717
1501
|
AAUTH_COVERED_COMPONENTS,
|
|
718
1502
|
AAuthClient,
|
|
719
1503
|
AAuthError,
|
|
1504
|
+
AccessTokenError,
|
|
1505
|
+
CLIENT_ASSERTION_TYP,
|
|
1506
|
+
CLIENT_ASSERTION_TYPE,
|
|
1507
|
+
ClientAssertionSigner,
|
|
1508
|
+
DPOP_NONCE_HEADER,
|
|
1509
|
+
DPOP_SCHEME2 as DPOP_SCHEME,
|
|
1510
|
+
DpopProofSigner,
|
|
1511
|
+
InMemoryDpopReplayCache,
|
|
1512
|
+
JwksCache,
|
|
720
1513
|
LumoAgent,
|
|
721
|
-
|
|
1514
|
+
LumoAuthApiError3 as LumoAuthApiError,
|
|
722
1515
|
LumoAuthApprovalDeniedError,
|
|
723
1516
|
LumoAuthApprovalNotDeliveredError,
|
|
724
1517
|
LumoAuthApprovalTimeoutError,
|
|
725
1518
|
LumoAuthAuthenticationError,
|
|
726
1519
|
LumoAuthBudgetExceededError,
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
1520
|
+
LumoAuthConfigError4 as LumoAuthConfigError,
|
|
1521
|
+
LumoAuthError3 as LumoAuthError,
|
|
1522
|
+
LumoAuthNetworkError4 as LumoAuthNetworkError,
|
|
730
1523
|
LumoAuthNotFoundError,
|
|
731
1524
|
LumoAuthPermissionDeniedError,
|
|
732
1525
|
LumoAuthRateLimitError,
|
|
733
1526
|
LumoAuthValidationError,
|
|
1527
|
+
MAX_ASSERTION_LIFETIME_SECONDS,
|
|
1528
|
+
USE_DPOP_NONCE,
|
|
1529
|
+
accessTokenScopes,
|
|
1530
|
+
attestWorkload,
|
|
1531
|
+
buildDpopHeaders,
|
|
734
1532
|
buildSignatureBase,
|
|
735
1533
|
contentDigestSha256,
|
|
1534
|
+
createAccessTokenVerifier,
|
|
736
1535
|
decodeJwt,
|
|
1536
|
+
dpopAth,
|
|
1537
|
+
dpopHtu3 as dpopHtu,
|
|
1538
|
+
fetchWithDpop3 as fetchWithDpop,
|
|
737
1539
|
generateKeypair,
|
|
738
1540
|
generateNonce,
|
|
1541
|
+
issuerFor,
|
|
739
1542
|
jwkThumbprint,
|
|
1543
|
+
parseAuthorizationHeader,
|
|
740
1544
|
publicJwkFromPrivateKey,
|
|
741
1545
|
signRequest,
|
|
742
1546
|
signSignatureBase,
|
|
743
1547
|
signatureParams,
|
|
1548
|
+
verifyAccessToken,
|
|
744
1549
|
verifyAuthToken,
|
|
1550
|
+
verifyDpopProof,
|
|
745
1551
|
verifySignatureBase
|
|
746
1552
|
};
|
|
747
1553
|
//# sourceMappingURL=index.mjs.map
|