@lumoauth/agent 1.0.0 → 1.2.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/dist/index.js CHANGED
@@ -23,18 +23,48 @@ __export(index_exports, {
23
23
  AAUTH_COVERED_COMPONENTS: () => AAUTH_COVERED_COMPONENTS,
24
24
  AAuthClient: () => AAuthClient,
25
25
  AAuthError: () => AAuthError,
26
+ AccessTokenError: () => AccessTokenError,
27
+ DPOP_NONCE_HEADER: () => import_shared7.DPOP_NONCE_HEADER,
28
+ DPOP_SCHEME: () => import_shared7.DPOP_SCHEME,
29
+ DpopProofSigner: () => DpopProofSigner,
30
+ InMemoryDpopReplayCache: () => InMemoryDpopReplayCache,
31
+ JwksCache: () => JwksCache,
26
32
  LumoAgent: () => LumoAgent,
33
+ LumoAuthApiError: () => import_shared8.LumoAuthApiError,
34
+ LumoAuthApprovalDeniedError: () => import_shared8.LumoAuthApprovalDeniedError,
35
+ LumoAuthApprovalNotDeliveredError: () => import_shared8.LumoAuthApprovalNotDeliveredError,
36
+ LumoAuthApprovalTimeoutError: () => import_shared8.LumoAuthApprovalTimeoutError,
37
+ LumoAuthAuthenticationError: () => import_shared8.LumoAuthAuthenticationError,
38
+ LumoAuthBudgetExceededError: () => import_shared8.LumoAuthBudgetExceededError,
39
+ LumoAuthConfigError: () => import_shared8.LumoAuthConfigError,
40
+ LumoAuthError: () => import_shared8.LumoAuthError,
41
+ LumoAuthNetworkError: () => import_shared8.LumoAuthNetworkError,
42
+ LumoAuthNotFoundError: () => import_shared8.LumoAuthNotFoundError,
43
+ LumoAuthPermissionDeniedError: () => import_shared8.LumoAuthPermissionDeniedError,
44
+ LumoAuthRateLimitError: () => import_shared8.LumoAuthRateLimitError,
45
+ LumoAuthValidationError: () => import_shared8.LumoAuthValidationError,
46
+ USE_DPOP_NONCE: () => import_shared7.USE_DPOP_NONCE,
47
+ accessTokenScopes: () => accessTokenScopes,
48
+ attestWorkload: () => attestWorkload,
49
+ buildDpopHeaders: () => import_shared7.buildDpopHeaders,
27
50
  buildSignatureBase: () => buildSignatureBase,
28
51
  contentDigestSha256: () => contentDigestSha256,
52
+ createAccessTokenVerifier: () => createAccessTokenVerifier,
29
53
  decodeJwt: () => decodeJwt,
54
+ dpopAth: () => dpopAth,
55
+ dpopHtu: () => import_shared7.dpopHtu,
56
+ fetchWithDpop: () => import_shared7.fetchWithDpop,
30
57
  generateKeypair: () => generateKeypair,
31
58
  generateNonce: () => generateNonce,
32
59
  jwkThumbprint: () => jwkThumbprint,
60
+ parseAuthorizationHeader: () => parseAuthorizationHeader,
33
61
  publicJwkFromPrivateKey: () => publicJwkFromPrivateKey,
34
62
  signRequest: () => signRequest,
35
63
  signSignatureBase: () => signSignatureBase,
36
64
  signatureParams: () => signatureParams,
65
+ verifyAccessToken: () => verifyAccessToken,
37
66
  verifyAuthToken: () => verifyAuthToken,
67
+ verifyDpopProof: () => verifyDpopProof,
38
68
  verifySignatureBase: () => verifySignatureBase
39
69
  });
40
70
  module.exports = __toCommonJS(index_exports);
@@ -55,6 +85,7 @@ var LumoAgent = class {
55
85
  this.clientSecret = options.clientSecret ?? envVar("AGENT_CLIENT_SECRET") ?? "";
56
86
  this.scopes = options.scopes;
57
87
  this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
88
+ this.dpop = options.dpop;
58
89
  if (!this.clientId || !this.clientSecret) {
59
90
  throw new import_shared.LumoAuthConfigError(
60
91
  "Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET environment variables or pass clientId/clientSecret to the constructor."
@@ -65,7 +96,8 @@ var LumoAgent = class {
65
96
  baseUrl: this.baseUrl,
66
97
  token: tokenProvider,
67
98
  timeout: options.timeout,
68
- fetch: options.fetch
99
+ fetch: options.fetch,
100
+ dpop: this.dpop
69
101
  });
70
102
  this.agents = new import_shared.AgentsModule(http, this.orgId);
71
103
  this.jit = new import_shared.JitModule(http, this.orgId);
@@ -74,7 +106,9 @@ var LumoAgent = class {
74
106
  baseUrl: this.baseUrl,
75
107
  orgId: this.orgId,
76
108
  token: tokenProvider,
77
- fetch: options.fetch
109
+ fetch: options.fetch,
110
+ http,
111
+ dpop: this.dpop
78
112
  });
79
113
  this.delegation = new import_shared.DelegationModule({
80
114
  baseUrl: this.baseUrl,
@@ -83,7 +117,8 @@ var LumoAgent = class {
83
117
  clientSecret: this.clientSecret,
84
118
  redirectUri: options.redirectUri,
85
119
  agentToken: tokenProvider,
86
- fetch: options.fetch
120
+ fetch: options.fetch,
121
+ dpop: this.dpop
87
122
  });
88
123
  }
89
124
  // ── Authentication ────────────────────────────────────────────────
@@ -101,13 +136,14 @@ var LumoAgent = class {
101
136
  const requested = scopes ?? this.scopes;
102
137
  if (requested?.length) form.scope = requested.join(" ");
103
138
  const url = `${this.baseUrl}${(0, import_shared.buildPath)(import_shared.ROUTES["oauth.token"].path, { orgId: this.requireOrgId() })}`;
139
+ const init = {
140
+ method: "POST",
141
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
142
+ body: new URLSearchParams(form)
143
+ };
104
144
  let res;
105
145
  try {
106
- res = await this.fetchFn(url, {
107
- method: "POST",
108
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
109
- body: new URLSearchParams(form)
110
- });
146
+ res = this.dpop ? await (0, import_shared.fetchWithDpop)(this.fetchFn, url, init, this.dpop) : await this.fetchFn(url, init);
111
147
  } catch (error) {
112
148
  throw new import_shared.LumoAuthNetworkError(
113
149
  `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -126,11 +162,24 @@ var LumoAgent = class {
126
162
  const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
127
163
  this.token = {
128
164
  accessToken: body.access_token,
165
+ tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
129
166
  refreshAt: Date.now() + expiresIn * 1e3 - TOKEN_REFRESH_BUFFER_MS,
130
167
  scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : []
131
168
  };
132
169
  return this.token.accessToken;
133
170
  }
171
+ /**
172
+ * `token_type` of the last successful authentication: `DPoP` when the
173
+ * token is sender-constrained, otherwise `Bearer`; `null` before the
174
+ * first sign-in. Present the token with that `Authorization` scheme.
175
+ */
176
+ get tokenType() {
177
+ return this.token?.tokenType ?? null;
178
+ }
179
+ /** The DPoP proof signer this agent was configured with, if any. */
180
+ get dpopSigner() {
181
+ return this.dpop;
182
+ }
134
183
  /**
135
184
  * The current access token, re-authenticating transparently when it is
136
185
  * missing or within 60 s of expiry. Concurrent callers share one
@@ -160,6 +209,13 @@ var LumoAgent = class {
160
209
  async isAllowed(action, context) {
161
210
  return this.agents.isAllowed(action, context);
162
211
  }
212
+ /**
213
+ * May this agent run `tool` on the registered MCP server `serverId`?
214
+ * A deny returns `{ allowed: false }` and does not throw.
215
+ */
216
+ async authorizeMcpTool(serverId, tool) {
217
+ return this.agents.authorizeMcpTool(serverId, tool);
218
+ }
163
219
  /** The agent's own identity, capabilities, and workspace. */
164
220
  async getCurrentAgent() {
165
221
  return this.agents.me();
@@ -719,23 +775,607 @@ var AAuthClient = class {
719
775
  };
720
776
  /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
721
777
  AAuthClient.generateKeypair = generateKeypair;
778
+
779
+ // src/dpop.ts
780
+ var import_node_crypto4 = require("crypto");
781
+ var import_shared4 = require("@lumoauth/shared");
782
+ var DpopProofSigner = class _DpopProofSigner {
783
+ constructor(options) {
784
+ this.nonces = /* @__PURE__ */ new Map();
785
+ if (options.privateKey) {
786
+ this.key = options.privateKey;
787
+ } else if (options.privateKeyPem) {
788
+ this.key = (0, import_node_crypto4.createPrivateKey)(options.privateKeyPem);
789
+ } else {
790
+ throw new Error("DpopProofSigner needs privateKeyPem or privateKey");
791
+ }
792
+ if (this.key.type !== "private") {
793
+ throw new Error("DpopProofSigner needs a private key");
794
+ }
795
+ this.algorithm = algorithmFor(this.key);
796
+ this.now = options.now ?? (() => Math.floor(Date.now() / 1e3));
797
+ const pub = (0, import_node_crypto4.createPublicKey)(this.key).export({ format: "jwk" });
798
+ this.jwk = publicMembers(pub);
799
+ this.thumbprint = jwkThumbprint(this.jwk);
800
+ }
801
+ /**
802
+ * Generate a fresh key. ES256 (P-256) by default; pass `'EdDSA'` for an
803
+ * Ed25519 key or `'RS256'` for a 2048-bit RSA key.
804
+ */
805
+ static generate(algorithm = "ES256") {
806
+ let privateKey;
807
+ switch (algorithm) {
808
+ case "ES256":
809
+ privateKey = (0, import_node_crypto4.generateKeyPairSync)("ec", { namedCurve: "P-256" }).privateKey;
810
+ break;
811
+ case "EdDSA":
812
+ privateKey = (0, import_node_crypto4.generateKeyPairSync)("ed25519").privateKey;
813
+ break;
814
+ case "RS256":
815
+ privateKey = (0, import_node_crypto4.generateKeyPairSync)("rsa", { modulusLength: 2048 }).privateKey;
816
+ break;
817
+ default:
818
+ throw new Error(`Unsupported DPoP algorithm: ${String(algorithm)}`);
819
+ }
820
+ return new _DpopProofSigner({ privateKey });
821
+ }
822
+ /** The private key as PKCS#8 PEM, for your secret store. */
823
+ get privateKeyPem() {
824
+ return this.key.export({ type: "pkcs8", format: "pem" }).toString();
825
+ }
826
+ /** Create one proof JWT. See the file comment for the claims. */
827
+ createProof(input) {
828
+ const method = input.method.toUpperCase();
829
+ const htu = (0, import_shared4.dpopHtu)(input.url);
830
+ const nonce = input.nonce ?? this.getNonce(input.url);
831
+ const header = { typ: "dpop+jwt", alg: this.algorithm, jwk: this.jwk };
832
+ const claims = {
833
+ jti: (0, import_node_crypto4.randomBytes)(24).toString("base64url"),
834
+ htm: method,
835
+ htu,
836
+ iat: this.now()
837
+ };
838
+ if (input.accessToken) claims.ath = dpopAth(input.accessToken);
839
+ if (nonce) claims.nonce = nonce;
840
+ const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
841
+ const signature = signJws(this.algorithm, Buffer.from(signingInput, "utf8"), this.key);
842
+ return `${signingInput}.${signature.toString("base64url")}`;
843
+ }
844
+ /** Remember the latest server nonce for the origin of `url`. */
845
+ setNonce(url, nonce) {
846
+ this.nonces.set(originOf(url), nonce);
847
+ }
848
+ /** The remembered nonce for the origin of `url`, if any. */
849
+ getNonce(url) {
850
+ return this.nonces.get(originOf(url));
851
+ }
852
+ /** Forget every remembered nonce. */
853
+ clearNonces() {
854
+ this.nonces.clear();
855
+ }
856
+ };
857
+ function dpopAth(accessToken) {
858
+ return (0, import_node_crypto4.createHash)("sha256").update(accessToken, "ascii").digest("base64url");
859
+ }
860
+ function signJws(alg, data, key) {
861
+ switch (alg) {
862
+ case "ES256":
863
+ return (0, import_node_crypto4.sign)("sha256", data, { key, dsaEncoding: "ieee-p1363" });
864
+ case "EdDSA":
865
+ return (0, import_node_crypto4.sign)(null, data, key);
866
+ case "RS256":
867
+ return (0, import_node_crypto4.sign)("sha256", data, key);
868
+ default:
869
+ throw new Error(`Unsupported DPoP algorithm: ${String(alg)}`);
870
+ }
871
+ }
872
+ function algorithmFor(key) {
873
+ switch (key.asymmetricKeyType) {
874
+ case "ec": {
875
+ const curve = key.asymmetricKeyDetails?.namedCurve;
876
+ if (curve !== "prime256v1" && curve !== "P-256") {
877
+ throw new Error(`DPoP EC keys must use P-256 (got ${String(curve)})`);
878
+ }
879
+ return "ES256";
880
+ }
881
+ case "ed25519":
882
+ return "EdDSA";
883
+ case "rsa":
884
+ return "RS256";
885
+ default:
886
+ throw new Error(`Unsupported DPoP key type: ${String(key.asymmetricKeyType)}`);
887
+ }
888
+ }
889
+ function publicMembers(jwk) {
890
+ const out = { kty: jwk.kty };
891
+ for (const member of ["crv", "x", "y", "n", "e"]) {
892
+ if (typeof jwk[member] === "string") out[member] = jwk[member];
893
+ }
894
+ return out;
895
+ }
896
+ function originOf(url) {
897
+ return new URL(url).origin;
898
+ }
899
+ function b64url(text) {
900
+ return Buffer.from(text, "utf8").toString("base64url");
901
+ }
902
+
903
+ // src/index.ts
904
+ var import_shared7 = require("@lumoauth/shared");
905
+
906
+ // src/attest.ts
907
+ var import_shared5 = require("@lumoauth/shared");
908
+ function envVar3(name) {
909
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
910
+ }
911
+ async function attestWorkload(options) {
912
+ const baseUrl = (options.baseUrl ?? envVar3("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
913
+ const orgId = options.orgId ?? envVar3("LUMOAUTH_ORG_ID") ?? "";
914
+ if (!orgId) {
915
+ throw new import_shared5.LumoAuthConfigError("attestWorkload requires orgId (or LUMOAUTH_ORG_ID).");
916
+ }
917
+ if (!options.agentId || !options.attestationToken) {
918
+ throw new import_shared5.LumoAuthConfigError("attestWorkload requires agentId and attestationToken.");
919
+ }
920
+ const url = `${baseUrl}/orgs/${encodeURIComponent(orgId)}/api/v1/agents/${encodeURIComponent(options.agentId)}/attest`;
921
+ const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
922
+ const init = {
923
+ method: "POST",
924
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
925
+ body: JSON.stringify({ attestation_token: options.attestationToken })
926
+ };
927
+ let res;
928
+ try {
929
+ res = options.dpop ? await (0, import_shared5.fetchWithDpop)(fetchFn, url, init, options.dpop) : await fetchFn(url, init);
930
+ } catch (error) {
931
+ throw new import_shared5.LumoAuthNetworkError(
932
+ `Agent attestation failed: ${error instanceof Error ? error.message : String(error)}`,
933
+ error
934
+ );
935
+ }
936
+ const body = await res.json().catch(() => ({}));
937
+ if (!res.ok || typeof body.access_token !== "string") {
938
+ throw new import_shared5.LumoAuthApiError(
939
+ typeof body.error_description === "string" ? body.error_description : `Agent attestation failed (HTTP ${res.status})`,
940
+ typeof body.error === "string" ? body.error : "ATTESTATION_ERROR",
941
+ res.status,
942
+ body
943
+ );
944
+ }
945
+ return {
946
+ accessToken: body.access_token,
947
+ tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
948
+ expiresIn: typeof body.expires_in === "number" ? body.expires_in : null,
949
+ scope: typeof body.scope === "string" ? body.scope : null,
950
+ identity: typeof body.identity === "object" && body.identity !== null ? body.identity : {}
951
+ };
952
+ }
953
+
954
+ // src/access-token.ts
955
+ var import_node_crypto5 = require("crypto");
956
+ var import_shared6 = require("@lumoauth/shared");
957
+ var AccessTokenError = class extends import_shared6.LumoAuthError {
958
+ constructor(message, code, statusCode = 401) {
959
+ super(message, code, statusCode);
960
+ this.name = "AccessTokenError";
961
+ }
962
+ };
963
+ var AT_JWT_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
964
+ var DPOP_PROOF_TYP = "dpop+jwt";
965
+ var DPOP_IAT_FUTURE_SECONDS = 60;
966
+ var DPOP_IAT_PAST_SECONDS = 300;
967
+ var DPOP_JTI_TTL_SECONDS = 300;
968
+ var DPOP_JTI_MIN_LENGTH = 16;
969
+ var JWKS_REFETCH_INTERVAL_MS = 3e4;
970
+ var JWS_VERIFIERS2 = {
971
+ RS256: (d, k, s) => (0, import_node_crypto5.verify)("sha256", d, k, s),
972
+ RS384: (d, k, s) => (0, import_node_crypto5.verify)("sha384", d, k, s),
973
+ RS512: (d, k, s) => (0, import_node_crypto5.verify)("sha512", d, k, s),
974
+ PS256: (d, k, s) => (0, import_node_crypto5.verify)("sha256", d, pss2(k), s),
975
+ PS384: (d, k, s) => (0, import_node_crypto5.verify)("sha384", d, pss2(k), s),
976
+ PS512: (d, k, s) => (0, import_node_crypto5.verify)("sha512", d, pss2(k), s),
977
+ ES256: (d, k, s) => (0, import_node_crypto5.verify)("sha256", d, p13632(k), s),
978
+ ES384: (d, k, s) => (0, import_node_crypto5.verify)("sha384", d, p13632(k), s),
979
+ ES512: (d, k, s) => (0, import_node_crypto5.verify)("sha512", d, p13632(k), s),
980
+ EdDSA: (d, k, s) => (0, import_node_crypto5.verify)(null, d, k, s)
981
+ };
982
+ var DPOP_ALG_KEYS = {
983
+ ES256: { kty: "EC", crv: "P-256" },
984
+ ES384: { kty: "EC", crv: "P-384" },
985
+ ES512: { kty: "EC", crv: "P-521" },
986
+ RS256: { kty: "RSA" },
987
+ RS384: { kty: "RSA" },
988
+ RS512: { kty: "RSA" },
989
+ PS256: { kty: "RSA" },
990
+ PS384: { kty: "RSA" },
991
+ PS512: { kty: "RSA" },
992
+ EdDSA: { kty: "OKP", crv: "Ed25519" }
993
+ };
994
+ function pss2(key) {
995
+ return { key, padding: import_node_crypto5.constants.RSA_PKCS1_PSS_PADDING, saltLength: import_node_crypto5.constants.RSA_PSS_SALTLEN_DIGEST };
996
+ }
997
+ function p13632(key) {
998
+ return { key, dsaEncoding: "ieee-p1363" };
999
+ }
1000
+ var JwksCache = class {
1001
+ constructor(fetchFn) {
1002
+ this.fetchFn = fetchFn;
1003
+ this.entries = /* @__PURE__ */ new Map();
1004
+ }
1005
+ /**
1006
+ * Find `kid` in the issuer's JWKS. An unknown `kid` triggers one refetch
1007
+ * (a key rotation); repeated misses refetch at most every 30 s, so a
1008
+ * stream of bogus tokens cannot hammer the JWKS endpoint.
1009
+ */
1010
+ async find(issuer, kid, fetchFn) {
1011
+ const doFetch = fetchFn ?? this.fetchFn ?? globalThis.fetch;
1012
+ let entry = this.entries.get(issuer);
1013
+ if (!entry) {
1014
+ entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: 0 };
1015
+ this.entries.set(issuer, entry);
1016
+ }
1017
+ let jwk = entry.keys.find((k) => k.kid === kid);
1018
+ if (!jwk && Date.now() - entry.missRefetchAt >= JWKS_REFETCH_INTERVAL_MS) {
1019
+ entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: Date.now() };
1020
+ this.entries.set(issuer, entry);
1021
+ jwk = entry.keys.find((k) => k.kid === kid);
1022
+ }
1023
+ return jwk;
1024
+ }
1025
+ /** Drop the cached keys of one issuer, or of all when omitted. */
1026
+ clear(issuer) {
1027
+ if (issuer) this.entries.delete(issuer);
1028
+ else this.entries.clear();
1029
+ }
1030
+ };
1031
+ async function fetchJwks(issuer, doFetch) {
1032
+ const base = issuer.replace(/\/+$/, "");
1033
+ const discovery = await doFetch(`${base}/.well-known/openid-configuration`, {
1034
+ headers: { Accept: "application/json" }
1035
+ });
1036
+ if (!discovery.ok) {
1037
+ throw new AccessTokenError(`Failed to fetch issuer discovery (HTTP ${discovery.status})`, "jwks_fetch_failed", 503);
1038
+ }
1039
+ const metadata = await discovery.json();
1040
+ const jwksUri = typeof metadata.jwks_uri === "string" ? metadata.jwks_uri : `${base}/.well-known/jwks.json`;
1041
+ const response = await doFetch(jwksUri, { headers: { Accept: "application/json" } });
1042
+ if (!response.ok) {
1043
+ throw new AccessTokenError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, "jwks_fetch_failed", 503);
1044
+ }
1045
+ const jwks = await response.json();
1046
+ if (!Array.isArray(jwks.keys)) {
1047
+ throw new AccessTokenError("Issuer JWKS is malformed", "jwks_fetch_failed", 503);
1048
+ }
1049
+ return jwks.keys;
1050
+ }
1051
+ var sharedJwksCache = new JwksCache();
1052
+ var InMemoryDpopReplayCache = class {
1053
+ constructor(now = () => Date.now()) {
1054
+ this.now = now;
1055
+ this.seen = /* @__PURE__ */ new Map();
1056
+ }
1057
+ add(key, ttlSeconds) {
1058
+ const now = this.now();
1059
+ if (this.seen.size > 0 && this.seen.size % 256 === 0) this.prune(now);
1060
+ const expiresAt = this.seen.get(key);
1061
+ if (expiresAt !== void 0 && expiresAt > now) return false;
1062
+ this.seen.set(key, now + ttlSeconds * 1e3);
1063
+ return true;
1064
+ }
1065
+ prune(now) {
1066
+ for (const [key, expiresAt] of this.seen) {
1067
+ if (expiresAt <= now) this.seen.delete(key);
1068
+ }
1069
+ }
1070
+ };
1071
+ var sharedReplayCache = new InMemoryDpopReplayCache();
1072
+ function decodeSegment2(segment) {
1073
+ try {
1074
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
1075
+ } catch {
1076
+ throw new AccessTokenError("Invalid JWT encoding", "invalid_token");
1077
+ }
1078
+ }
1079
+ function isObject(value) {
1080
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1081
+ }
1082
+ function parseAuthorizationHeader(header) {
1083
+ if (!header) return null;
1084
+ const match = /^\s*([A-Za-z][A-Za-z0-9+.-]*)\s+(\S+)\s*$/.exec(header);
1085
+ return match ? { scheme: match[1], token: match[2] } : null;
1086
+ }
1087
+ function accessTokenScopes(claims) {
1088
+ return typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
1089
+ }
1090
+ async function verifyAccessToken(token, options) {
1091
+ if (typeof token !== "string" || token === "") {
1092
+ throw new AccessTokenError("Missing access token", "invalid_token");
1093
+ }
1094
+ const parts = token.split(".");
1095
+ if (parts.length !== 3) {
1096
+ throw new AccessTokenError("Invalid JWT format", "invalid_token");
1097
+ }
1098
+ const header = decodeSegment2(parts[0]);
1099
+ const claims = decodeSegment2(parts[1]);
1100
+ if (!isObject(header) || !isObject(claims)) {
1101
+ throw new AccessTokenError("Invalid JWT format", "invalid_token");
1102
+ }
1103
+ if (typeof header.typ !== "string" || !AT_JWT_TYPES.has(header.typ)) {
1104
+ throw new AccessTokenError(`Unexpected token type: ${String(header.typ)}`, "invalid_token");
1105
+ }
1106
+ const alg = typeof header.alg === "string" ? header.alg : "";
1107
+ const kid = typeof header.kid === "string" ? header.kid : "";
1108
+ if (!alg || !kid) {
1109
+ throw new AccessTokenError("Missing kid or alg in JOSE header", "invalid_token");
1110
+ }
1111
+ const verifier = JWS_VERIFIERS2[alg];
1112
+ if (!verifier) {
1113
+ throw new AccessTokenError(`Disallowed JWS algorithm: ${alg}`, "invalid_token");
1114
+ }
1115
+ if (claims.iss !== options.issuer) {
1116
+ throw new AccessTokenError("Untrusted issuer", "invalid_token");
1117
+ }
1118
+ let jwk;
1119
+ if (options.jwks) {
1120
+ jwk = options.jwks.keys.find((k) => k.kid === kid);
1121
+ } else {
1122
+ const cache = options.jwksCache ?? sharedJwksCache;
1123
+ jwk = await cache.find(options.issuer, kid, options.fetch);
1124
+ }
1125
+ if (!jwk) {
1126
+ throw new AccessTokenError(`Key not found: kid=${kid}`, "invalid_token");
1127
+ }
1128
+ assertAlgMatchesKey2(alg, jwk);
1129
+ const publicKey = (0, import_node_crypto5.createPublicKey)({ key: jwk, format: "jwk" });
1130
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
1131
+ const signature = Buffer.from(parts[2], "base64url");
1132
+ if (!verifier(data, publicKey, signature)) {
1133
+ throw new AccessTokenError("Signature verification failed", "invalid_token");
1134
+ }
1135
+ const now = Math.floor(Date.now() / 1e3);
1136
+ const skew = options.clockSkew ?? 60;
1137
+ if (typeof claims.exp !== "number" || claims.exp < now - skew) {
1138
+ throw new AccessTokenError("Access token expired", "invalid_token");
1139
+ }
1140
+ if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || claims.nbf > now + skew)) {
1141
+ throw new AccessTokenError("Access token not yet valid", "invalid_token");
1142
+ }
1143
+ const aud = claims.aud;
1144
+ const audiences = typeof aud === "string" ? [aud] : Array.isArray(aud) ? aud : [];
1145
+ if (!audiences.includes(options.resource)) {
1146
+ throw new AccessTokenError("Invalid audience", "invalid_token");
1147
+ }
1148
+ if (typeof claims.sub !== "string" || claims.sub === "") {
1149
+ throw new AccessTokenError("Missing sub claim", "invalid_token");
1150
+ }
1151
+ if (claims.token_use === "test") {
1152
+ throw new AccessTokenError("Test tokens are not accepted by resource servers", "invalid_token");
1153
+ }
1154
+ const cnf = isObject(claims.cnf) ? claims.cnf : void 0;
1155
+ const jkt = typeof cnf?.jkt === "string" ? cnf.jkt : void 0;
1156
+ if (jkt) {
1157
+ await verifyDpopBinding(token, jkt, options);
1158
+ } else if (options.requireDpop) {
1159
+ throw new AccessTokenError("Access token is not DPoP-bound", "invalid_token");
1160
+ } else if (options.dpop?.authorizationScheme && options.dpop.authorizationScheme.toLowerCase() === import_shared6.DPOP_SCHEME.toLowerCase()) {
1161
+ throw new AccessTokenError("Access token is not DPoP-bound but was presented with the DPoP scheme", "invalid_token");
1162
+ }
1163
+ return claims;
1164
+ }
1165
+ async function verifyDpopBinding(token, jkt, options) {
1166
+ const incoming = options.dpop;
1167
+ if (!incoming) {
1168
+ throw new AccessTokenError(
1169
+ "Access token is DPoP-bound: pass the incoming request (method, url, proof, authorizationScheme) in `dpop`",
1170
+ "invalid_dpop_proof"
1171
+ );
1172
+ }
1173
+ if ((incoming.authorizationScheme ?? "").toLowerCase() !== import_shared6.DPOP_SCHEME.toLowerCase()) {
1174
+ throw new AccessTokenError("DPoP-bound access token must be presented with the DPoP scheme", "invalid_token");
1175
+ }
1176
+ if (!incoming.proof) {
1177
+ throw new AccessTokenError("DPoP proof required for sender-constrained token", "invalid_dpop_proof");
1178
+ }
1179
+ const proof = await verifyDpopProof(incoming.proof, {
1180
+ method: incoming.method,
1181
+ url: incoming.url,
1182
+ accessToken: token,
1183
+ nonce: incoming.nonce,
1184
+ replayCache: options.replayCache
1185
+ });
1186
+ if (proof.thumbprint !== jkt) {
1187
+ throw new AccessTokenError("DPoP key does not match token binding", "invalid_dpop_proof");
1188
+ }
1189
+ }
1190
+ function assertAlgMatchesKey2(alg, jwk) {
1191
+ const compatible = jwk.kty === "RSA" && (alg.startsWith("RS") || alg.startsWith("PS")) || jwk.kty === "EC" && alg.startsWith("ES") || jwk.kty === "OKP" && alg === "EdDSA";
1192
+ if (!compatible) {
1193
+ throw new AccessTokenError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, "invalid_token");
1194
+ }
1195
+ if (jwk.alg && jwk.alg !== alg) {
1196
+ throw new AccessTokenError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, "invalid_token");
1197
+ }
1198
+ }
1199
+ async function verifyDpopProof(proof, options) {
1200
+ const parts = proof.split(".");
1201
+ if (parts.length !== 3) {
1202
+ throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
1203
+ }
1204
+ let header;
1205
+ let claims;
1206
+ try {
1207
+ header = decodeSegment2(parts[0]);
1208
+ claims = decodeSegment2(parts[1]);
1209
+ } catch {
1210
+ throw new AccessTokenError("Invalid DPoP proof encoding", "invalid_dpop_proof");
1211
+ }
1212
+ if (!isObject(header) || !isObject(claims)) {
1213
+ throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
1214
+ }
1215
+ if (header.typ !== DPOP_PROOF_TYP) {
1216
+ throw new AccessTokenError("DPoP proof typ must be dpop+jwt", "invalid_dpop_proof");
1217
+ }
1218
+ const alg = typeof header.alg === "string" ? header.alg : "";
1219
+ const expectedKey = DPOP_ALG_KEYS[alg];
1220
+ if (!expectedKey) {
1221
+ throw new AccessTokenError(`Disallowed DPoP proof algorithm: ${alg || "(none)"}`, "invalid_dpop_proof");
1222
+ }
1223
+ const jwk = header.jwk;
1224
+ if (!isObject(jwk) || typeof jwk.kty !== "string") {
1225
+ throw new AccessTokenError("DPoP proof is missing its jwk", "invalid_dpop_proof");
1226
+ }
1227
+ if ("d" in jwk) {
1228
+ throw new AccessTokenError("DPoP proof jwk must not carry private members", "invalid_dpop_proof");
1229
+ }
1230
+ if (jwk.kty !== expectedKey.kty || expectedKey.crv && jwk.crv !== expectedKey.crv) {
1231
+ throw new AccessTokenError(`DPoP proof jwk does not match ${alg}`, "invalid_dpop_proof");
1232
+ }
1233
+ if (typeof jwk.alg === "string" && jwk.alg !== alg) {
1234
+ throw new AccessTokenError("DPoP proof jwk alg does not match the header", "invalid_dpop_proof");
1235
+ }
1236
+ let publicKey;
1237
+ try {
1238
+ publicKey = (0, import_node_crypto5.createPublicKey)({ key: jwk, format: "jwk" });
1239
+ } catch {
1240
+ throw new AccessTokenError("DPoP proof jwk is not a valid public key", "invalid_dpop_proof");
1241
+ }
1242
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
1243
+ const signature = Buffer.from(parts[2], "base64url");
1244
+ let valid = false;
1245
+ try {
1246
+ valid = JWS_VERIFIERS2[alg](data, publicKey, signature);
1247
+ } catch {
1248
+ valid = false;
1249
+ }
1250
+ if (!valid) {
1251
+ throw new AccessTokenError("DPoP proof signature verification failed", "invalid_dpop_proof");
1252
+ }
1253
+ if (typeof claims.htm !== "string" || claims.htm.toUpperCase() !== options.method.toUpperCase()) {
1254
+ throw new AccessTokenError("DPoP proof htm does not match the request method", "invalid_dpop_proof");
1255
+ }
1256
+ if (typeof claims.htu !== "string" || !htuMatches(claims.htu, options.url)) {
1257
+ throw new AccessTokenError("DPoP proof htu does not match the request URL", "invalid_dpop_proof");
1258
+ }
1259
+ const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
1260
+ if (typeof claims.iat !== "number" || claims.iat > now + DPOP_IAT_FUTURE_SECONDS || claims.iat < now - DPOP_IAT_PAST_SECONDS) {
1261
+ throw new AccessTokenError("DPoP proof iat is outside the accepted window", "invalid_dpop_proof");
1262
+ }
1263
+ if (typeof claims.jti !== "string" || claims.jti.length < DPOP_JTI_MIN_LENGTH) {
1264
+ throw new AccessTokenError("DPoP proof jti is missing or too short", "invalid_dpop_proof");
1265
+ }
1266
+ if (options.nonce !== void 0 && claims.nonce !== options.nonce) {
1267
+ throw new AccessTokenError("DPoP proof nonce does not match", "invalid_dpop_proof");
1268
+ }
1269
+ if (options.accessToken !== void 0) {
1270
+ const expectedAth = (0, import_node_crypto5.createHash)("sha256").update(options.accessToken, "ascii").digest("base64url");
1271
+ if (claims.ath !== expectedAth) {
1272
+ throw new AccessTokenError("DPoP proof ath does not match the access token", "invalid_dpop_proof");
1273
+ }
1274
+ }
1275
+ const thumbprint = jwkThumbprint(jwk);
1276
+ const cache = options.replayCache ?? sharedReplayCache;
1277
+ if (!await cache.add(`${thumbprint}:${claims.jti}`, DPOP_JTI_TTL_SECONDS)) {
1278
+ throw new AccessTokenError("DPoP proof jti was already used", "invalid_dpop_proof");
1279
+ }
1280
+ return { jwk, thumbprint, claims };
1281
+ }
1282
+ function htuMatches(htu, requestUrl) {
1283
+ try {
1284
+ return (0, import_shared6.dpopHtu)(htu) === (0, import_shared6.dpopHtu)(requestUrl);
1285
+ } catch {
1286
+ return false;
1287
+ }
1288
+ }
1289
+ function createAccessTokenVerifier(options) {
1290
+ const jwksCache = new JwksCache(options.fetch);
1291
+ const replayCache = options.replayCache ?? new InMemoryDpopReplayCache();
1292
+ const base = { ...options, jwksCache, replayCache };
1293
+ return {
1294
+ verify: (token, dpop) => verifyAccessToken(token, dpop ? { ...base, dpop } : base),
1295
+ verifyRequest: async (request) => {
1296
+ const authorization = parseAuthorizationHeader(headerValue(request.headers, "authorization"));
1297
+ if (!authorization) {
1298
+ throw new AccessTokenError("Missing or malformed Authorization header", "invalid_token");
1299
+ }
1300
+ if (!["bearer", "dpop"].includes(authorization.scheme.toLowerCase())) {
1301
+ throw new AccessTokenError(`Unsupported authorization scheme: ${authorization.scheme}`, "invalid_token");
1302
+ }
1303
+ return verifyAccessToken(authorization.token, {
1304
+ ...base,
1305
+ dpop: {
1306
+ method: request.method,
1307
+ url: request.url,
1308
+ proof: headerValue(request.headers, "dpop"),
1309
+ authorizationScheme: authorization.scheme,
1310
+ nonce: request.nonce
1311
+ }
1312
+ });
1313
+ },
1314
+ clearCache: () => jwksCache.clear()
1315
+ };
1316
+ }
1317
+ function headerValue(headers, name) {
1318
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
1319
+ return headers.get(name);
1320
+ }
1321
+ for (const [key, value] of Object.entries(headers)) {
1322
+ if (key.toLowerCase() === name) {
1323
+ if (Array.isArray(value)) return value[0] ?? null;
1324
+ return value ?? null;
1325
+ }
1326
+ }
1327
+ return null;
1328
+ }
1329
+
1330
+ // src/index.ts
1331
+ var import_shared8 = require("@lumoauth/shared");
722
1332
  // Annotate the CommonJS export names for ESM import in node:
723
1333
  0 && (module.exports = {
724
1334
  AAUTH_COVERED_COMPONENTS,
725
1335
  AAuthClient,
726
1336
  AAuthError,
1337
+ AccessTokenError,
1338
+ DPOP_NONCE_HEADER,
1339
+ DPOP_SCHEME,
1340
+ DpopProofSigner,
1341
+ InMemoryDpopReplayCache,
1342
+ JwksCache,
727
1343
  LumoAgent,
1344
+ LumoAuthApiError,
1345
+ LumoAuthApprovalDeniedError,
1346
+ LumoAuthApprovalNotDeliveredError,
1347
+ LumoAuthApprovalTimeoutError,
1348
+ LumoAuthAuthenticationError,
1349
+ LumoAuthBudgetExceededError,
1350
+ LumoAuthConfigError,
1351
+ LumoAuthError,
1352
+ LumoAuthNetworkError,
1353
+ LumoAuthNotFoundError,
1354
+ LumoAuthPermissionDeniedError,
1355
+ LumoAuthRateLimitError,
1356
+ LumoAuthValidationError,
1357
+ USE_DPOP_NONCE,
1358
+ accessTokenScopes,
1359
+ attestWorkload,
1360
+ buildDpopHeaders,
728
1361
  buildSignatureBase,
729
1362
  contentDigestSha256,
1363
+ createAccessTokenVerifier,
730
1364
  decodeJwt,
1365
+ dpopAth,
1366
+ dpopHtu,
1367
+ fetchWithDpop,
731
1368
  generateKeypair,
732
1369
  generateNonce,
733
1370
  jwkThumbprint,
1371
+ parseAuthorizationHeader,
734
1372
  publicJwkFromPrivateKey,
735
1373
  signRequest,
736
1374
  signSignatureBase,
737
1375
  signatureParams,
1376
+ verifyAccessToken,
738
1377
  verifyAuthToken,
1378
+ verifyDpopProof,
739
1379
  verifySignatureBase
740
1380
  });
741
1381
  //# sourceMappingURL=index.js.map