@canton-network/core-wallet-auth 2.0.0 → 2.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.
@@ -23,10 +23,25 @@ export interface AuthAware<T> {
23
23
  authContext: AuthContext | undefined;
24
24
  withAuthContext: (context?: AuthContext) => T;
25
25
  }
26
+ /**
27
+ * Thrown when a token could not be verified because the identity provider
28
+ * could not be reached or returned unusable data, as opposed to the token
29
+ * itself being invalid.
30
+ */
31
+ export declare class IdpUnavailableError extends Error {
32
+ constructor(message: string, options?: {
33
+ cause?: unknown;
34
+ });
35
+ }
26
36
  /**
27
37
  * Interface for verifying access tokens
28
38
  */
29
39
  export interface AuthService {
40
+ /**
41
+ * @returns the auth context, or undefined if the token is missing or invalid
42
+ * @throws {IdpUnavailableError} if the verification depends on an identity
43
+ * provider that is currently unavailable, the token may still be valid
44
+ */
30
45
  verifyToken(accessToken?: string): Promise<AuthContext | undefined>;
31
46
  }
32
47
  /**
@@ -36,9 +51,6 @@ export interface AccessTokenProvider {
36
51
  getAccessToken(): Promise<string>;
37
52
  getAuthContext(): Promise<AuthContext>;
38
53
  }
39
- export interface OIDCConfig {
40
- token_endpoint: string;
41
- }
42
54
  export interface ClientCredentials {
43
55
  clientId: string;
44
56
  clientSecret: string;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-service.d.ts","sourceRoot":"","sources":["../src/auth-service.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,MAAM,GAAG,MAAM,CAAA;AAE3B;;GAEG;AACH,MAAM,MAAM,WAAW,GACjB;IACI,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,KAAK,CAAA;IAChB,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB,GACD;IACI,QAAQ,EAAE,IAAI,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IAC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AAE,MAAM,CAAA;IACjB,WAAW,EAAE,iBAAiB,CAAA;CACjC,CAAA;AAEP;;;;;;;;;;;;GAYG;AACH,qBAAa,iBAAkB,YAAW,mBAAmB;IAU7C,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,mBAAmB;IAT1D,OAAO,CAAC,MAAM,CAMZ;IACF,OAAO,CAAC,WAAW,CAAoB;IAEvC,YAA+B,MAAM,EAAE,mBAAmB,EAAI;IAE9D,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAEjD;IAED,MAAM,CAAC,iBAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,GAAG,iBAAiB,CAoChE;YAEa,WAAW;IAoBzB;;;OAGG;IACU,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,CAc7C;IAED;;;OAGG;IACU,cAAc,IAAI,OAAO,CAAC,WAAW,CAAC,CAUlD;CACJ"}
@@ -1,5 +1,5 @@
1
- import type { AuthContext } from './auth-service';
2
- import type { Idp } from './config/schema.js';
1
+ import { z } from 'zod';
2
+ import { type AuthContext } from './auth-service.js';
3
3
  export declare function assertIsConnected(authContext: AuthContext | undefined): asserts authContext is AuthContext;
4
4
  export declare function assertConnected(authContext: AuthContext | undefined): AuthContext;
5
5
  /**
@@ -17,51 +17,69 @@ export declare function jwtUserId(token: string): string;
17
17
  */
18
18
  export declare function jwtUserEmail(token: string): string | undefined;
19
19
  /**
20
- * Standard OIDC UserInfo claims as defined by OpenID Connect Core 1.0.
20
+ * Extract the expiry from the `exp` claim of a JWT. Throws if `exp` is missing.
21
+ *
22
+ * @param token a base64url encoded JWT token
23
+ * @returns the expiry
24
+ */
25
+ export declare function jwtExpiresAt(token: string): Date;
26
+ /**
27
+ * The parts of the OIDC discovery document (/.well-known/openid-configuration)
28
+ * we rely on. Every field is optional because IDPs differ in what they expose;
29
+ * callers must check the fields they need.
30
+ * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
31
+ */
32
+ export declare const oidcDiscoverySchema: z.ZodObject<{
33
+ issuer: z.ZodOptional<z.ZodString>;
34
+ authorization_endpoint: z.ZodCatch<z.ZodOptional<z.ZodURL>>;
35
+ token_endpoint: z.ZodCatch<z.ZodOptional<z.ZodURL>>;
36
+ userinfo_endpoint: z.ZodCatch<z.ZodOptional<z.ZodURL>>;
37
+ jwks_uri: z.ZodCatch<z.ZodOptional<z.ZodURL>>;
38
+ }, z.core.$loose>;
39
+ export type OidcDiscovery = z.infer<typeof oidcDiscoverySchema>;
40
+ /**
41
+ * The UserInfo claims we rely on, other standard claims are passed through
42
+ * untouched. Only `sub` is required by the spec; `email_verified` and friends
43
+ * are deliberately not validated since IDPs disagree on their type (e.g. the
44
+ * string "true").
21
45
  * https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
22
46
  */
23
- export interface OidcUserInfo {
24
- sub: string;
25
- name?: string;
26
- given_name?: string;
27
- family_name?: string;
28
- middle_name?: string;
29
- nickname?: string;
30
- preferred_username?: string;
31
- profile?: string;
32
- picture?: string;
33
- website?: string;
34
- email?: string;
35
- email_verified?: boolean;
36
- gender?: string;
37
- birthdate?: string;
38
- zoneinfo?: string;
39
- locale?: string;
40
- phone_number?: string;
41
- phone_number_verified?: boolean;
42
- updated_at?: number;
43
- address?: Record<string, string>;
44
- [key: string]: unknown;
45
- }
47
+ export declare const oidcUserInfoSchema: z.ZodObject<{
48
+ sub: z.ZodString;
49
+ name: z.ZodOptional<z.ZodString>;
50
+ preferred_username: z.ZodOptional<z.ZodString>;
51
+ email: z.ZodOptional<z.ZodString>;
52
+ }, z.core.$loose>;
53
+ export type OidcUserInfo = z.infer<typeof oidcUserInfoSchema>;
54
+ /**
55
+ * The successful response of an OAuth token endpoint.
56
+ * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
57
+ */
58
+ export declare const oidcTokenResponseSchema: z.ZodObject<{
59
+ access_token: z.ZodString;
60
+ }, z.core.$loose>;
61
+ export type OidcTokenResponse = z.infer<typeof oidcTokenResponseSchema>;
62
+ /**
63
+ * Validate a JSON response received from an IDP, throwing a readable error
64
+ * instead of a raw ZodError.
65
+ */
66
+ export declare function parseIdpResponse<T extends z.ZodType>(schema: T, data: unknown, description: string): z.infer<T>;
46
67
  /**
47
- * Fetches user claims from the OIDC UserInfo endpoint.
48
- * Discovers the endpoint via the OIDC discovery document at configUrl.
68
+ * Fetches and validates the OIDC discovery document.
49
69
  *
50
- * @param configUrl - The OIDC discovery document URL (/.well-known/openid-configuration)
51
- * @param accessToken - The user's bearer access token
52
- * @returns The UserInfo claims, or undefined if the IDP does not expose a userinfo endpoint
53
- * @throws If any network request fails
70
+ * @param configUrl - The OIDC discovery document URL (/.well-known/openid-configuration)
71
+ * @throws {IdpUnavailableError} If the request fails or the response is not a valid discovery document
54
72
  */
55
- export declare function fetchOidcUserInfo(configUrl: string, accessToken: string): Promise<OidcUserInfo | undefined>;
73
+ export declare function fetchOidcDiscovery(configUrl: string): Promise<OidcDiscovery>;
56
74
  /**
57
- * Resolve the user email from the OIDC userinfo endpoint.
75
+ * Fetches user claims from an OIDC UserInfo endpoint.
58
76
  *
59
- * @param authContext - The authentication context
60
- * @param idp - The IDP configuration
61
- * @param logger - The logger
62
- * @returns The user email, or undefined if the email is not found
77
+ * @param userinfoEndpoint - The `userinfo_endpoint` from the discovery document
78
+ * @param accessToken - The user's bearer access token
79
+ * @returns The UserInfo claims
80
+ * @throws If the request fails or the response is malformed
63
81
  */
64
- export declare function resolveUserEmail(authContext: AuthContext, idp: Idp): Promise<string | undefined>;
82
+ export declare function fetchOidcUserInfo(userinfoEndpoint: string, accessToken: string): Promise<OidcUserInfo>;
65
83
  /**
66
84
  * Determine if a given JWT is still valid based on its expiry time.
67
85
  *
@@ -1 +1 @@
1
- {"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../src/auth-utils.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAEjD,OAA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AO,kBAAkB,CAAC,CAAA;AAE7D;;;GAGG;AACH,eAAO,MAAM,uBAAuB;;iBAElC,CAAA;AACF,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAA;AAEvE;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO,EAChD,MAAM,EAAE,CAAC,EACT,IAAI,EAAE,OAAO,EACb,WAAW,EAAE,MAAM,GACpB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAQZ;AAED;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACpC,SAAS,EAAE,MAAM,GAClB,OAAO,CAAC,aAAa,CAAC,CAwCxB;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CACnC,gBAAgB,EAAE,MAAM,EACxB,WAAW,EAAE,MAAM,GACpB,OAAO,CAAC,YAAY,CAAC,CAkBvB;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQjD"}
@@ -1,4 +1,4 @@
1
- import type { ClientCredentials, OIDCConfig } from './auth-service.js';
1
+ import type { ClientCredentials } from './auth-service.js';
2
2
  export declare class ClientCredentialsService {
3
3
  private configUrl;
4
4
  private logger;
@@ -11,7 +11,13 @@ export declare class ClientCredentialsService {
11
11
  */
12
12
  fetchToken(credentials: ClientCredentials): Promise<string>;
13
13
  fetchTokenEndpoint(tokenEndpoint: string, credentials: ClientCredentials): Promise<Response>;
14
- getOIDCConfig(url: string): Promise<OIDCConfig>;
14
+ getOIDCConfig(url: string): Promise<{
15
+ issuer?: string | undefined;
16
+ authorization_endpoint?: string | undefined;
17
+ userinfo_endpoint?: string | undefined;
18
+ jwks_uri?: string | undefined;
19
+ token_endpoint: string;
20
+ }>;
15
21
  }
16
22
  export declare const clientCredentialsService: (configUrl: string) => {
17
23
  fetchToken: (credentials: ClientCredentials) => Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"client-credentials-service.d.ts","sourceRoot":"","sources":["../src/client-credentials-service.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAEtE,qBAAa,wBAAwB;IAOrB,OAAO,CAAC,SAAS;IAN7B,OAAO,CAAC,MAAM,CAIoC;gBAE9B,SAAS,EAAE,MAAM;IAErC;;;;;OAKG;IACG,UAAU,CAAC,WAAW,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IAkC3D,kBAAkB,CACpB,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,iBAAiB,GAC/B,OAAO,CAAC,QAAQ,CAAC;IAmCd,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;CAgBxD;AAOD,eAAO,MAAM,wBAAwB,GAAI,WAAW,MAAM;8BACtB,iBAAiB;CAEnD,CAAA"}
1
+ {"version":3,"file":"client-credentials-service.d.ts","sourceRoot":"","sources":["../src/client-credentials-service.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAQ1D,qBAAa,wBAAwB;IAOrB,OAAO,CAAC,SAAS;IAN7B,OAAO,CAAC,MAAM,CAIoC;IAElD,YAAoB,SAAS,EAAE,MAAM,EAAI;IAEzC;;;;;OAKG;IACG,UAAU,CAAC,WAAW,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CAgChE;IAEK,kBAAkB,CACpB,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,iBAAiB,GAC/B,OAAO,CAAC,QAAQ,CAAC,CAkCnB;IAEK,aAAa,CAAC,GAAG,EAAE,MAAM;;;;;;OAe9B;CACJ;AAOD,eAAO,MAAM,wBAAwB,cAAe,MAAM;IACtD,UAAU,gBAAsB,iBAAiB;CAEnD,CAAA"}
@@ -92,7 +92,7 @@ export declare const idpSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
92
92
  id: z.ZodString;
93
93
  type: z.ZodLiteral<"oauth">;
94
94
  issuer: z.ZodString;
95
- configUrl: z.ZodString;
95
+ configUrl: z.ZodURL;
96
96
  }, z.core.$strip>], "type">;
97
97
  export type Idp = z.infer<typeof idpSchema>;
98
98
  export {};
package/dist/index.cjs CHANGED
@@ -1,9 +1,22 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let jose = require("jose");
3
+ let zod = require("zod");
3
4
  let _canton_network_core_rpc_errors = require("@canton-network/core-rpc-errors");
4
5
  let _logtape_logtape = require("@logtape/logtape");
5
- let zod = require("zod");
6
- //#region src/auth-utils.ts
6
+ let typescript_lru_cache = require("typescript-lru-cache");
7
+ // src/auth-service.ts
8
+ /**
9
+ * Thrown when a token could not be verified because the identity provider
10
+ * could not be reached or returned unusable data, as opposed to the token
11
+ * itself being invalid.
12
+ */
13
+ var IdpUnavailableError = class extends Error {
14
+ constructor(message, options) {
15
+ super(message, options);
16
+ this.name = "IdpUnavailableError";
17
+ }
18
+ };
19
+ // src/auth-utils.ts
7
20
  function assertIsConnected(authContext) {
8
21
  if (!authContext) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "User is not connected" });
9
22
  }
@@ -34,46 +47,104 @@ function jwtUserEmail(token) {
34
47
  return email;
35
48
  }
36
49
  /**
37
- * Fetches user claims from the OIDC UserInfo endpoint.
38
- * Discovers the endpoint via the OIDC discovery document at configUrl.
50
+ * Extract the expiry from the `exp` claim of a JWT. Throws if `exp` is missing.
39
51
  *
40
- * @param configUrl - The OIDC discovery document URL (/.well-known/openid-configuration)
41
- * @param accessToken - The user's bearer access token
42
- * @returns The UserInfo claims, or undefined if the IDP does not expose a userinfo endpoint
43
- * @throws If any network request fails
52
+ * @param token a base64url encoded JWT token
53
+ * @returns the expiry
44
54
  */
45
- async function fetchOidcUserInfo(configUrl, accessToken) {
46
- const configResponse = await fetch(configUrl);
47
- if (!configResponse.ok) throw new Error(`Failed to fetch OIDC discovery document: ${configResponse.status} ${configResponse.statusText}`);
48
- const config = await configResponse.json();
49
- if (!config.userinfo_endpoint) return;
50
- const userInfoResponse = await fetch(config.userinfo_endpoint, { headers: { Authorization: `Bearer ${accessToken}` } });
51
- if (!userInfoResponse.ok) throw new Error(`Failed to fetch OIDC userinfo: ${userInfoResponse.status} ${userInfoResponse.statusText}`);
52
- return await userInfoResponse.json();
55
+ function jwtExpiresAt(token) {
56
+ const { exp } = (0, jose.decodeJwt)(token);
57
+ if (typeof exp !== "number") throw new Error("token did not contain an expiry field");
58
+ return /* @__PURE__ */ new Date(exp * 1e3);
59
+ }
60
+ /**
61
+ * An invalid endpoint is treated as missing, so it only fails the callers
62
+ * that actually need it
63
+ */
64
+ const endpointSchema = zod.z.url({ protocol: /^https?$/ }).optional().catch(void 0);
65
+ /**
66
+ * The parts of the OIDC discovery document (/.well-known/openid-configuration)
67
+ * we rely on. Every field is optional because IDPs differ in what they expose;
68
+ * callers must check the fields they need.
69
+ * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
70
+ */
71
+ const oidcDiscoverySchema = zod.z.looseObject({
72
+ issuer: zod.z.string().optional(),
73
+ authorization_endpoint: endpointSchema,
74
+ token_endpoint: endpointSchema,
75
+ userinfo_endpoint: endpointSchema,
76
+ jwks_uri: endpointSchema
77
+ });
78
+ /**
79
+ * The UserInfo claims we rely on, other standard claims are passed through
80
+ * untouched. Only `sub` is required by the spec; `email_verified` and friends
81
+ * are deliberately not validated since IDPs disagree on their type (e.g. the
82
+ * string "true").
83
+ * https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
84
+ */
85
+ const oidcUserInfoSchema = zod.z.looseObject({
86
+ sub: zod.z.string(),
87
+ name: zod.z.string().optional(),
88
+ preferred_username: zod.z.string().optional(),
89
+ email: zod.z.string().optional()
90
+ });
91
+ /**
92
+ * The successful response of an OAuth token endpoint.
93
+ * https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
94
+ */
95
+ const oidcTokenResponseSchema = zod.z.looseObject({ access_token: zod.z.string().min(1) });
96
+ /**
97
+ * Validate a JSON response received from an IDP, throwing a readable error
98
+ * instead of a raw ZodError.
99
+ */
100
+ function parseIdpResponse(schema, data, description) {
101
+ const result = schema.safeParse(data);
102
+ if (!result.success) throw new Error(`Invalid ${description}: ${zod.z.prettifyError(result.error)}`);
103
+ return result.data;
53
104
  }
54
105
  /**
55
- * Resolve the user email from the OIDC userinfo endpoint.
106
+ * Fetches and validates the OIDC discovery document.
56
107
  *
57
- * @param authContext - The authentication context
58
- * @param idp - The IDP configuration
59
- * @param logger - The logger
60
- * @returns The user email, or undefined if the email is not found
108
+ * @param configUrl - The OIDC discovery document URL (/.well-known/openid-configuration)
109
+ * @throws {IdpUnavailableError} If the request fails or the response is not a valid discovery document
61
110
  */
62
- async function resolveUserEmail(authContext, idp) {
63
- if (authContext.email) return authContext.email;
111
+ async function fetchOidcDiscovery(configUrl) {
112
+ let response;
64
113
  try {
65
- if (idp.type !== "oauth") return;
66
- return (await fetchOidcUserInfo(idp.configUrl, authContext.accessToken))?.email;
114
+ response = await fetch(configUrl, { headers: { Accept: "application/json" } });
67
115
  } catch (error) {
68
- (0, _logtape_logtape.getLogger)([
69
- "core",
70
- "wallet-auth",
71
- "resolveUserEmail"
72
- ]).warn("Failed to resolve user email from OIDC userinfo", { error });
73
- return;
116
+ throw new IdpUnavailableError(`Failed to fetch OIDC discovery document: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
117
+ }
118
+ if (!response.ok) throw new IdpUnavailableError(`Failed to fetch OIDC discovery document: ${response.status} ${response.statusText}`);
119
+ let data;
120
+ try {
121
+ data = await response.json();
122
+ } catch (error) {
123
+ throw new IdpUnavailableError(`Failed to parse OIDC discovery document: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
124
+ }
125
+ try {
126
+ return parseIdpResponse(oidcDiscoverySchema, data, "OIDC discovery document");
127
+ } catch (error) {
128
+ throw new IdpUnavailableError(error instanceof Error ? error.message : String(error), { cause: error });
74
129
  }
75
130
  }
76
131
  /**
132
+ * Fetches user claims from an OIDC UserInfo endpoint.
133
+ *
134
+ * @param userinfoEndpoint - The `userinfo_endpoint` from the discovery document
135
+ * @param accessToken - The user's bearer access token
136
+ * @returns The UserInfo claims
137
+ * @throws If the request fails or the response is malformed
138
+ */
139
+ async function fetchOidcUserInfo(userinfoEndpoint, accessToken) {
140
+ const userInfoResponse = await fetch(userinfoEndpoint, { headers: {
141
+ Accept: "application/json",
142
+ Authorization: `Bearer ${accessToken}`
143
+ } });
144
+ if (!userInfoResponse.ok) throw new Error(`Failed to fetch OIDC userinfo: ${userInfoResponse.status} ${userInfoResponse.statusText}`);
145
+ return parseIdpResponse(oidcUserInfoSchema, await userInfoResponse.json(), "OIDC userinfo response");
146
+ }
147
+ /**
77
148
  * Determine if a given JWT is still valid based on its expiry time.
78
149
  *
79
150
  * @param token a base64 encoded JWT token
@@ -88,8 +159,7 @@ function jwtExpired(token) {
88
159
  return true;
89
160
  }
90
161
  }
91
- //#endregion
92
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
162
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
93
163
  function _typeof(o) {
94
164
  "@babel/helpers - typeof";
95
165
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -98,8 +168,7 @@ function _typeof(o) {
98
168
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
99
169
  }, _typeof(o);
100
170
  }
101
- //#endregion
102
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
171
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
103
172
  function toPrimitive(t, r) {
104
173
  if ("object" != _typeof(t) || !t) return t;
105
174
  var e = t[Symbol.toPrimitive];
@@ -110,14 +179,12 @@ function toPrimitive(t, r) {
110
179
  }
111
180
  return ("string" === r ? String : Number)(t);
112
181
  }
113
- //#endregion
114
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
182
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
115
183
  function toPropertyKey(t) {
116
184
  var i = toPrimitive(t, "string");
117
185
  return "symbol" == _typeof(i) ? i : i + "";
118
186
  }
119
- //#endregion
120
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
187
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
121
188
  function _defineProperty(e, r, t) {
122
189
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
123
190
  value: t,
@@ -126,8 +193,7 @@ function _defineProperty(e, r, t) {
126
193
  writable: !0
127
194
  }) : e[r] = t, e;
128
195
  }
129
- //#endregion
130
- //#region src/client-credentials-service.ts
196
+ // src/client-credentials-service.ts
131
197
  var ClientCredentialsService = class {
132
198
  constructor(configUrl) {
133
199
  this.configUrl = configUrl;
@@ -147,13 +213,13 @@ var ClientCredentialsService = class {
147
213
  try {
148
214
  const oidcConfig = await this.getOIDCConfig(this.configUrl);
149
215
  this.logger.debug("Fetched OIDC config", { oidcConfig });
150
- const json = await (await this.fetchTokenEndpoint(oidcConfig.token_endpoint, credentials)).json();
216
+ const res = await this.fetchTokenEndpoint(oidcConfig.token_endpoint, credentials);
217
+ const json = parseIdpResponse(oidcTokenResponseSchema, await res.json(), "token endpoint response");
151
218
  if (this.logger.isEnabledFor("debug")) this.logger.debug(`Fetched admin token for clientId: {clientId}`, { clientId: credentials.clientId });
152
219
  else this.logger.info(`Fetched admin token for clientId: {clientId}`, {
153
220
  clientId: credentials.clientId,
154
221
  response: json
155
222
  });
156
- if (!json.access_token) throw new Error("No access_token in token endpoint response");
157
223
  return json.access_token;
158
224
  } catch (error) {
159
225
  this.logger.warn("Failed to fetch admin token", { error });
@@ -171,6 +237,7 @@ var ClientCredentialsService = class {
171
237
  method: "POST",
172
238
  headers: {
173
239
  "Content-Type": "application/x-www-form-urlencoded",
240
+ Accept: "application/json",
174
241
  Authorization: `Basic ${password}`
175
242
  },
176
243
  body: params.toString()
@@ -185,17 +252,18 @@ var ClientCredentialsService = class {
185
252
  return res;
186
253
  }
187
254
  async getOIDCConfig(url) {
188
- const res = await fetch(url);
189
- if (!res.ok) {
190
- const text = await res.text();
191
- this.logger.warn("Failed to fetch OIDC config", {
192
- status: res.status,
193
- statusText: res.statusText,
194
- body: text
195
- });
196
- throw new Error(`OIDC config error: ${res.status} ${res.statusText}`);
255
+ let config;
256
+ try {
257
+ config = await fetchOidcDiscovery(url);
258
+ } catch (error) {
259
+ this.logger.error("Failed to fetch OIDC config", { error });
260
+ throw error;
197
261
  }
198
- return res.json();
262
+ if (!config.token_endpoint) throw new Error("OIDC config has no token_endpoint");
263
+ return {
264
+ ...config,
265
+ token_endpoint: config.token_endpoint
266
+ };
199
267
  }
200
268
  };
201
269
  const toClientPassword = (clientId, clientSecret) => {
@@ -203,8 +271,7 @@ const toClientPassword = (clientId, clientSecret) => {
203
271
  return btoa(credentials);
204
272
  };
205
273
  const clientCredentialsService = (configUrl) => ({ fetchToken: async (credentials) => new ClientCredentialsService(configUrl).fetchToken(credentials) });
206
- //#endregion
207
- //#region src/self-signed-token-service.ts
274
+ // src/self-signed-token-service.ts
208
275
  var SelfSignedTokenService = class {
209
276
  static async fetchToken(credentials, issuer, expirySeconds = 3600, keyId) {
210
277
  const secret = new TextEncoder().encode(credentials.clientSecret);
@@ -229,8 +296,7 @@ _defineProperty(SelfSignedTokenService, "logger", (0, _logtape_logtape.getLogger
229
296
  "wallet-auth",
230
297
  "SelfSignedTokenService"
231
298
  ]));
232
- //#endregion
233
- //#region src/auth-token-provider.ts
299
+ // src/auth-token-provider.ts
234
300
  /**
235
301
  * AuthTokenProvider provides some common functionality across token providers.
236
302
  *
@@ -322,8 +388,7 @@ var AuthTokenProvider = class AuthTokenProvider {
322
388
  };
323
389
  }
324
390
  };
325
- //#endregion
326
- //#region src/config/schema.ts
391
+ // src/config/schema.ts
327
392
  const authorizationCodeAuthSchema = zod.z.object({
328
393
  method: zod.z.literal("authorization_code"),
329
394
  audience: zod.z.string().meta({ description: "Participant ID prefixed with \"https://daml.com/jwt/aud/participant/\"." }),
@@ -396,11 +461,82 @@ const idpSchema = zod.z.discriminatedUnion("type", [
396
461
  id: zod.z.string(),
397
462
  type: zod.z.literal("oauth"),
398
463
  issuer: zod.z.string(),
399
- configUrl: zod.z.string().url()
464
+ configUrl: zod.z.url()
400
465
  })
401
466
  ]);
402
- //#endregion
403
- //#region src/self-issued-token-service.ts
467
+ // src/oidc-client.ts
468
+ /**
469
+ * How long discovery documents and userinfo responses are reused. Matches
470
+ * jose's default `cacheMaxAge` for remote JWKS.
471
+ */
472
+ const OIDC_CACHE_TTL_MS = 6e5;
473
+ const OIDC_CACHE_MAX_ENTRIES = 1e4;
474
+ /**
475
+ * Identifies an access token without keeping it, so the cache doesn't hold
476
+ * usable tokens after their requests are done.
477
+ */
478
+ async function hashToken(accessToken) {
479
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
480
+ return jose.base64url.encode(new Uint8Array(digest));
481
+ }
482
+ /**
483
+ * Creates an OIDC client that reuses discovery documents and userinfo
484
+ * responses for {@link OIDC_CACHE_TTL_MS}, so the IDP isn't contacted on
485
+ * every request. Failures aren't cached.
486
+ */
487
+ function createOidcClient() {
488
+ const discoveries = new typescript_lru_cache.LRUCache({
489
+ maxSize: OIDC_CACHE_MAX_ENTRIES,
490
+ entryExpirationTimeInMS: OIDC_CACHE_TTL_MS
491
+ });
492
+ const userInfos = new typescript_lru_cache.LRUCache({
493
+ maxSize: OIDC_CACHE_MAX_ENTRIES,
494
+ entryExpirationTimeInMS: OIDC_CACHE_TTL_MS
495
+ });
496
+ /**
497
+ * Cached {@link fetchOidcDiscovery}
498
+ *
499
+ * @throws {IdpUnavailableError} If the request fails, or the document's
500
+ * issuer isn't `issuer` or it has no `jwks_uri`
501
+ */
502
+ async function fetchDiscovery(configUrl, issuer) {
503
+ const key = `${configUrl}|${issuer}`;
504
+ let config = discoveries.get(key);
505
+ if (!config) {
506
+ const fetched = await fetchOidcDiscovery(configUrl);
507
+ if (fetched.issuer !== issuer) throw new IdpUnavailableError(`OIDC discovery document issuer ${fetched.issuer} does not match the identity provider issuer ${issuer}`);
508
+ if (!fetched.jwks_uri) throw new IdpUnavailableError("OIDC discovery document has no jwks_uri");
509
+ config = {
510
+ ...fetched,
511
+ jwks_uri: fetched.jwks_uri
512
+ };
513
+ discoveries.set(key, config);
514
+ }
515
+ return config;
516
+ }
517
+ /**
518
+ * Cached {@link fetchOidcUserInfo}
519
+ *
520
+ * @param subject - The verified `sub` of `accessToken`
521
+ * @throws If the response's `sub` isn't `subject`, its claims may be about
522
+ * another user (OpenID Connect Core 1.0, 5.3.2)
523
+ */
524
+ async function fetchUserInfo(userinfoEndpoint, accessToken, subject) {
525
+ const key = `${userinfoEndpoint}|${subject}|${await hashToken(accessToken)}`;
526
+ let userInfo = userInfos.get(key);
527
+ if (!userInfo) {
528
+ userInfo = await fetchOidcUserInfo(userinfoEndpoint, accessToken);
529
+ if (userInfo.sub !== subject) throw new Error(`OIDC userinfo subject ${userInfo.sub} does not match the token subject ${subject}`);
530
+ userInfos.set(key, userInfo);
531
+ }
532
+ return userInfo;
533
+ }
534
+ return {
535
+ fetchDiscovery,
536
+ fetchUserInfo
537
+ };
538
+ }
539
+ // src/self-issued-token-service.ts
404
540
  var SelfIssuedTokenService = class SelfIssuedTokenService {
405
541
  static publicKeyToEd25519Jwk(publicKeyBase64) {
406
542
  return {
@@ -439,21 +575,28 @@ var SelfIssuedTokenService = class SelfIssuedTokenService {
439
575
  return jose.base64url.encode(new TextEncoder().encode(JSON.stringify(value)));
440
576
  }
441
577
  };
442
- //#endregion
443
578
  exports.AuthTokenProvider = AuthTokenProvider;
444
579
  exports.ClientCredentialsService = ClientCredentialsService;
580
+ exports.IdpUnavailableError = IdpUnavailableError;
581
+ exports.OIDC_CACHE_TTL_MS = OIDC_CACHE_TTL_MS;
445
582
  exports.SelfIssuedTokenService = SelfIssuedTokenService;
446
583
  exports.assertConnected = assertConnected;
447
584
  exports.assertIsConnected = assertIsConnected;
448
585
  exports.authFromEnvSchema = authFromEnvSchema;
449
586
  exports.authSchema = authSchema;
450
587
  exports.clientCredentialsService = clientCredentialsService;
588
+ exports.createOidcClient = createOidcClient;
589
+ exports.fetchOidcDiscovery = fetchOidcDiscovery;
451
590
  exports.fetchOidcUserInfo = fetchOidcUserInfo;
452
591
  exports.idpSchema = idpSchema;
453
592
  exports.jwtExpired = jwtExpired;
593
+ exports.jwtExpiresAt = jwtExpiresAt;
454
594
  exports.jwtUserEmail = jwtUserEmail;
455
595
  exports.jwtUserId = jwtUserId;
596
+ exports.oidcDiscoverySchema = oidcDiscoverySchema;
597
+ exports.oidcTokenResponseSchema = oidcTokenResponseSchema;
598
+ exports.oidcUserInfoSchema = oidcUserInfoSchema;
599
+ exports.parseIdpResponse = parseIdpResponse;
456
600
  exports.resolveAuthIdentityProviderId = resolveAuthIdentityProviderId;
457
- exports.resolveUserEmail = resolveUserEmail;
458
601
 
459
602
  //# sourceMappingURL=index.cjs.map