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