@strivacity/sdk-core 3.0.1 → 3.0.3

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +54 -1
  3. package/dist/flows/BaseFlow.cjs +1 -1
  4. package/dist/flows/BaseFlow.cjs.map +1 -1
  5. package/dist/flows/BaseFlow.mjs +1 -1
  6. package/dist/flows/BaseFlow.mjs.map +1 -1
  7. package/dist/flows/EmbeddedFlow.cjs +1 -1
  8. package/dist/flows/EmbeddedFlow.cjs.map +1 -1
  9. package/dist/flows/EmbeddedFlow.mjs +1 -1
  10. package/dist/flows/EmbeddedFlow.mjs.map +1 -1
  11. package/dist/flows/NativeFlow.cjs +1 -1
  12. package/dist/flows/NativeFlow.cjs.map +1 -1
  13. package/dist/flows/NativeFlow.mjs +1 -1
  14. package/dist/flows/NativeFlow.mjs.map +1 -1
  15. package/dist/flows/PopupFlow.cjs +1 -1
  16. package/dist/flows/PopupFlow.cjs.map +1 -1
  17. package/dist/flows/PopupFlow.mjs +1 -1
  18. package/dist/flows/PopupFlow.mjs.map +1 -1
  19. package/dist/flows/RedirectFlow.cjs +1 -1
  20. package/dist/flows/RedirectFlow.cjs.map +1 -1
  21. package/dist/flows/RedirectFlow.mjs +1 -1
  22. package/dist/flows/RedirectFlow.mjs.map +1 -1
  23. package/dist/handlers/BaseFlowHandler.cjs +1 -1
  24. package/dist/handlers/BaseFlowHandler.cjs.map +1 -1
  25. package/dist/handlers/BaseFlowHandler.d.ts +4 -3
  26. package/dist/handlers/BaseFlowHandler.mjs +1 -1
  27. package/dist/handlers/BaseFlowHandler.mjs.map +1 -1
  28. package/dist/handlers/EmbeddedFlowHandler.cjs +1 -1
  29. package/dist/handlers/EmbeddedFlowHandler.cjs.map +1 -1
  30. package/dist/handlers/EmbeddedFlowHandler.d.ts +0 -1
  31. package/dist/handlers/EmbeddedFlowHandler.mjs +1 -1
  32. package/dist/handlers/EmbeddedFlowHandler.mjs.map +1 -1
  33. package/dist/handlers/NativeFlowHandler.cjs +1 -1
  34. package/dist/handlers/NativeFlowHandler.cjs.map +1 -1
  35. package/dist/handlers/NativeFlowHandler.d.ts +2 -1
  36. package/dist/handlers/NativeFlowHandler.mjs +1 -1
  37. package/dist/handlers/NativeFlowHandler.mjs.map +1 -1
  38. package/dist/types.cjs.map +1 -1
  39. package/dist/types.d.ts +4 -4
  40. package/dist/types.mjs.map +1 -1
  41. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,24 @@
1
+ ## 3.0.3 (2026-08-03)
2
+
3
+ ### 🩹 Fixes
4
+
5
+ - unnecessary scope validation removed ([2c3536a](https://github.com/Strivacity/sdk-js/commit/2c3536a))
6
+ - openid scope handling fixed ([9c0e012](https://github.com/Strivacity/sdk-js/commit/9c0e012))
7
+
8
+ ### 🧱 Updated Dependencies
9
+
10
+ - Updated testing to 3.0.3
11
+
12
+ ## 3.0.2 (2026-05-12)
13
+
14
+ ### 🩹 Fixes
15
+
16
+ - language parameter added to the login renderer component ([c8f18d9](https://github.com/Strivacity/sdk-js/commit/c8f18d9))
17
+
18
+ ### 🧱 Updated Dependencies
19
+
20
+ - Updated testing to 3.0.2
21
+
1
22
  ## 3.0.1 (2026-04-20)
2
23
 
3
24
  ### 🩹 Fixes
package/README.md CHANGED
@@ -255,12 +255,16 @@ import { CustomNativeFlow } from './CustomNativeFlow';
255
255
  export class CustomNativeFlowHandler extends NativeFlowHandler {
256
256
  declare sdk: CustomNativeFlow;
257
257
 
258
- override async startSession(sessionId?: string | null): Promise<LoginFlowState | void> {
258
+ override async startSession(sessionId?: string | null, language?: string | null): Promise<LoginFlowState | void> {
259
259
  if (sessionId) {
260
260
  this.sessionId = sessionId;
261
261
  return this.submitForm();
262
262
  }
263
263
 
264
+ if (language) {
265
+ this.language = language;
266
+ }
267
+
264
268
  const response = await this.sdk.httpClient.request(new URL('/api/session/start', location.origin).toString(), {
265
269
  method: 'POST',
266
270
  credentials: 'include',
@@ -387,6 +391,55 @@ const sdk = initFlow({
387
391
 
388
392
  The `SDKLogging` interface requires `debug`, `info`, `warn`, and `error` methods. The optional `xEventId` property, when set by the SDK, provides a correlation ID to trace related log messages across the authentication flow.
389
393
 
394
+ ## HTTP Client
395
+
396
+ The SDK uses a built-in `fetch`-based HTTP client for all requests. You can replace it with your own implementation by extending `SDKHttpClient` and passing your class via the `httpClient` option. This is useful when you need to attach custom headers (e.g. `x-sty-app-id`) to every outgoing request, route traffic through a proxy, or use a platform-specific transport such as Capacitor's `CapacitorHttp`.
397
+
398
+ ### Adding custom headers to every request
399
+
400
+ ```typescript
401
+ import { initFlow, SDKHttpClient, type HttpClientResponse } from '@strivacity/sdk-core';
402
+
403
+ class CustomHttpClient extends SDKHttpClient {
404
+ async request<T>(url: string, options?: RequestInit): Promise<HttpClientResponse<T>> {
405
+ const mergedOptions: RequestInit = {
406
+ ...options,
407
+ headers: {
408
+ 'x-sty-app-id': 'my-app',
409
+ ...(options?.headers as Record<string, string>),
410
+ },
411
+ };
412
+
413
+ const response = await fetch(url, mergedOptions);
414
+
415
+ return {
416
+ headers: response.headers,
417
+ ok: response.ok,
418
+ status: response.status,
419
+ statusText: response.statusText,
420
+ url: response.url,
421
+ json: async () => (await response.json()) as T,
422
+ text: async () => await response.text(),
423
+ };
424
+ }
425
+ }
426
+
427
+ const sdk = initFlow({
428
+ // ...other options
429
+ httpClient: CustomHttpClient,
430
+ });
431
+ ```
432
+
433
+ Any header you add inside `request()` is automatically included in every SDK request
434
+
435
+ ### CORS configuration
436
+
437
+ For custom request headers to reach the Strivacity cluster, the cluster must be configured to explicitly allow them. Add the header name(s) to the **Access-Control-Allow-Headers** list in the cluster settings. Without this, browsers will block the preflight `OPTIONS` request and the SDK call will fail with a CORS error.
438
+
439
+ ```
440
+ Access-Control-Allow-Headers: x-sty-app-id, <any other custom headers>
441
+ ```
442
+
390
443
  ## API Documentation
391
444
 
392
445
  ### `initFlow(options)`
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../utils/jwt.cjs"),h=require("../utils/date.cjs"),c=require("../utils/Metadata.cjs"),a=require("../utils/Session.cjs"),d=require("../utils/State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const n={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class l{#i;#e=null;#s=!1;httpClient;storage;logging;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=h.timestamp()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#o(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,i,t,s){if(!e.issuer){const o=new Error("Missing option: issuer");throw s?.error("Required option missing",o),o}if(!e.clientId){const o=new Error("Missing option: clientId");throw s?.error("Required option missing",o),o}if(!e.redirectUri){const o=new Error("Missing option: redirectUri");throw s?.error("Required option missing",o),o}if(!e.urlHandler){const o=new Error("Missing option: urlHandler");throw s?.error("Required option missing",o),o}if(!e.callbackHandler){const o=new Error("Missing option: callbackHandler");throw s?.error("Required option missing",o),o}if(e.scopes&&!Array.isArray(e.scopes)){const o=new Error("Invalid option: scopes");throw s?.error("Invalid option provided",o),o}e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=i,this.httpClient=t,this.logging=s,this.metadata=new c.Metadata(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#i=this.#t()}async#t(){this.session=a.Session.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.logging?.debug("SDK initialized"),this.session||this.logging?.debug("No session found in storage"),this.session&&this.accessToken&&this.idTokenClaims&&(this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.debug("Session loaded from storage")),this.accessToken&&this.accessTokenExpired&&(this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),this.logging?.debug("Access token has expired"))}async#o(){let e=!1;try{await this.waitToInitialize()}catch{this.logging?.warn("Initialization failed")}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function"){const s=new Error("Missing option: urlHandler");throw this.logging?.error("Required option missing",s),s}await this.waitToInitialize(),this.logging?.debug("Attempting to logout");const i=this.session;if(!i?.id_token){this.logging?.debug("Logout called without session");return}await this.storage.delete(this.options.storageTokenName),this.session=null;const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",i?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:i.id_token,claims:i.claims}]),this.logging?.debug("Logout initiated"),await this.options.urlHandler(t.toString(),e)}async refresh(){if(await this.waitToInitialize(),this.logging?.debug("Attempting to refresh session"),typeof this.session?.refresh_token!="string"){this.logging?.debug("Session refresh not possible - session not found");return}const e=this.session;try{const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});if(!i.ok){const t=await i.json();throw new Error(`${t.error}: ${t.error_description}`)}Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=r.jwt.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&(this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.info("Session refreshed successfully"))}catch(i){this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}]),this.logging?.info(`Session refresh failed - ${i}`)}}async revoke(){await this.waitToInitialize();const e=this.session;let i=!0;try{let t;if(e?.refresh_token?(this.logging?.debug("Attempting to revoke refresh token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token})):e?.access_token&&(this.logging?.debug("Attempting to revoke access token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})),t&&!t.ok){const s=await t.json();throw new Error(`${s.error}: ${s.error_description}`)}}catch(t){i=!1,this.logging?.info(`Token revocation failed - ${t}`)}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?(this.dispatchEvent(i?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]),i&&this.logging?.info("Refresh token successfully revoked")):e?.access_token&&(this.dispatchEvent(i?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}]),i&&this.logging?.info("Access token successfully revoked"))}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.logging?.debug("Exchanging authorization code for tokens"),this.session=new a.Session,Object.assign(this.session,e),this.session.error){const s=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Authorization error",s),s}if(!this.session.code){const s=new Error("Invalid or missing code");throw this.logging?.error("Authorization error",s),s}let i;try{const s=await this.storage.get(`sty.${this.session.state}`);if(!s)throw new Error;i=d.State.fromSerializedData(s),await this.storage.delete(`sty.${this.session.state}`)}catch{const s=new Error("Invalid or missing state");throw this.logging?.error("Validation failed",s),s}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:i.codeVerifier,code:this.session.code});if(!t.ok){const s=await t.json(),o=new Error(`${s.error}: ${s.error_description}`);throw this.logging?.error("Token exchange failed",o),o}if(Object.assign(this.session,await t.json()),this.session.id_token&&(this.session.claims=r.jwt.decode(this.session.id_token)),this.session.error){const s=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Validation failed",s),s}if(this.session.scope!==this.options.scopes?.join(" ")){const s=new Error("Invalid scope");throw this.logging?.error("Validation failed",s),s}if(this.session.claims?.nonce!==i.nonce){const s=new Error("Invalid nonce");throw this.logging?.error("Validation failed",s),s}if(this.session.claims?.iss!==await this.metadata.issuer){const s=new Error("Invalid iss");throw this.logging?.error("Validation failed",s),s}if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId){const s=new Error("Invalid aud");throw this.logging?.error("Validation failed",s),s}await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&(this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging&&(this.logging.xEventId=void 0,this.logging.info("Login successful")))}async getAuthorizationUrl(e={}){const i=new URL(await this.metadata.authorizationEndpoint);return i.searchParams.append("client_id",this.options.clientId),i.searchParams.append("redirect_uri",this.options.redirectUri),i.searchParams.append("response_type",this.options.responseType||"code"),i.searchParams.append("response_mode",this.options.responseMode||"fragment"),i.searchParams.append("scope",this.options.scopes?.join(" ")||""),i.searchParams.append("code_challenge_method","S256"),e.prompt&&i.searchParams.append("prompt",e.prompt),e.acrValues?.length&&i.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint?.length&&i.searchParams.append("login_hint",e.loginHint),e.uiLocales?.length&&i.searchParams.append("ui_locales",e.uiLocales.join(" ")),e.audiences?.length&&i.searchParams.append("audience",e.audiences.join(" ")),i}async waitToInitialize(){await this.#i}async sendTokenRequest(e,i={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(i).toString()})}subscribeToEvent(e,i){return n[e].add(i),{dispose:()=>{n[e].delete(i)}}}dispatchEvent(e,i){for(const t of n[e])t(...i)}}exports.BaseFlow=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../utils/jwt.cjs"),h=require("../utils/date.cjs"),c=require("../utils/Metadata.cjs"),a=require("../utils/Session.cjs"),d=require("../utils/State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const n={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class l{#i;#e=null;#s=!1;httpClient;storage;logging;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=h.timestamp()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#o(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,s,t,i){if(!e.issuer){const o=new Error("Missing option: issuer");throw i?.error("Required option missing",o),o}if(!e.clientId){const o=new Error("Missing option: clientId");throw i?.error("Required option missing",o),o}if(!e.redirectUri){const o=new Error("Missing option: redirectUri");throw i?.error("Required option missing",o),o}if(!e.urlHandler){const o=new Error("Missing option: urlHandler");throw i?.error("Required option missing",o),o}if(!e.callbackHandler){const o=new Error("Missing option: callbackHandler");throw i?.error("Required option missing",o),o}if(e.scopes&&!Array.isArray(e.scopes)){const o=new Error("Invalid option: scopes");throw i?.error("Invalid option provided",o),o}e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=t,this.logging=i,this.metadata=new c.Metadata(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#i=this.#t()}async#t(){this.session=a.Session.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.logging?.debug("SDK initialized"),this.session||this.logging?.debug("No session found in storage"),this.session&&this.accessToken&&(this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.debug("Session loaded from storage")),this.accessToken&&this.accessTokenExpired&&(this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),this.logging?.debug("Access token has expired"))}async#o(){let e=!1;try{await this.waitToInitialize()}catch{this.logging?.warn("Initialization failed")}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function"){const i=new Error("Missing option: urlHandler");throw this.logging?.error("Required option missing",i),i}await this.waitToInitialize(),this.logging?.debug("Attempting to logout");const s=this.session;if(await this.storage.delete(this.options.storageTokenName),this.session=null,!s?.id_token){this.logging?.debug("Logout called without session");return}const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",s?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]),this.logging?.debug("Logout initiated"),await this.options.urlHandler(t.toString(),e)}async refresh(){if(await this.waitToInitialize(),this.logging?.debug("Attempting to refresh session"),typeof this.session?.refresh_token!="string"){this.logging?.debug("Session refresh not possible - session not found");return}const e=this.session;try{const s=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});if(!s.ok){const t=await s.json();throw new Error(`${t.error}: ${t.error_description}`)}Object.assign(this.session,await s.json()),this.session.id_token&&(this.session.claims=r.jwt.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&(this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.info("Session refreshed successfully"))}catch(s){this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}]),this.logging?.info(`Session refresh failed - ${s}`)}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{let t;if(e?.refresh_token?(this.logging?.debug("Attempting to revoke refresh token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token})):e?.access_token&&(this.logging?.debug("Attempting to revoke access token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})),t&&!t.ok){const i=await t.json();throw new Error(`${i.error}: ${i.error_description}`)}}catch(t){s=!1,this.logging?.info(`Token revocation failed - ${t}`)}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?(this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]),s&&this.logging?.info("Refresh token successfully revoked")):e?.access_token&&(this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}]),s&&this.logging?.info("Access token successfully revoked"))}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.logging?.debug("Exchanging authorization code for tokens"),this.session=new a.Session,Object.assign(this.session,e),this.session.error){const i=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Authorization error",i),i}if(!this.session.code){const i=new Error("Invalid or missing code");throw this.logging?.error("Authorization error",i),i}let s;try{const i=await this.storage.get(`sty.${this.session.state}`);if(!i)throw new Error;s=d.State.fromSerializedData(i),await this.storage.delete(`sty.${this.session.state}`)}catch{const i=new Error("Invalid or missing state");throw this.logging?.error("Validation failed",i),i}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(!t.ok){const i=await t.json(),o=new Error(`${i.error}: ${i.error_description}`);throw this.logging?.error("Token exchange failed",o),o}if(Object.assign(this.session,await t.json()),this.session.error){const i=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Validation failed",i),i}if(this.session.id_token){if(this.session.claims=r.jwt.decode(this.session.id_token),this.session.claims?.nonce!==s.nonce){const i=new Error("Invalid nonce");throw this.logging?.error("Validation failed",i),i}if(this.session.claims?.iss!==await this.metadata.issuer){const i=new Error("Invalid iss");throw this.logging?.error("Validation failed",i),i}if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId){const i=new Error("Invalid aud");throw this.logging?.error("Validation failed",i),i}}await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&(this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging&&(this.logging.xEventId=void 0,this.logging.info("Login successful")))}async getAuthorizationUrl(e={}){const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",this.options.scopes?.join(" ")||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues?.length&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint?.length&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales?.length&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),e.audiences?.length&&s.searchParams.append("audience",e.audiences.join(" ")),s}async waitToInitialize(){await this.#i}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return n[e].add(s),{dispose:()=>{n[e].delete(s)}}}dispatchEvent(e,s){for(const t of n[e])t(...s)}}exports.BaseFlow=l;
2
2
  //# sourceMappingURL=BaseFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseFlow.cjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type {\n\tIdTokenClaims,\n\tSDKOptions,\n\tSDKStorage,\n\tEventFunctions,\n\tExtraRequestArgs,\n\tLogoutParams,\n\tSDKHttpClient,\n\tHttpClientResponse,\n\tSDKLogging,\n} from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Logging utility for the SDK.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t * @param {SDKHttpClient} httpClient - HTTP client for making requests.\n\t * @param {SDKLogging} [logging] - Optional logging utility.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.issuer) {\n\t\t\tconst error = new Error('Missing option: issuer');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tconst error = new Error('Missing option: clientId');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tconst error = new Error('Missing option: redirectUri');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tconst error = new Error('Invalid option: scopes');\n\t\t\tlogging?.error('Invalid option provided', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.logging = logging;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\t\tthis.logging?.debug('SDK initialized');\n\n\t\tif (!this.session) {\n\t\t\tthis.logging?.debug('No session found in storage');\n\t\t}\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\tthis.logging?.debug('Session loaded from storage');\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\tthis.logging?.debug('Access token has expired');\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\tthis.logging?.warn('Initialization failed');\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t *\n\t * @throws {Error} Throws an error if URL handler is not defined.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to logout');\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\tthis.logging?.debug('Logout called without session');\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\t\tthis.logging?.debug('Logout initiated');\n\n\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to refresh session');\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthis.logging?.debug('Session refresh not possible - session not found');\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\n\t\t\tObject.assign(this.session, await response.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t\tthis.logging?.info('Session refreshed successfully');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t\tthis.logging?.info(`Session refresh failed - ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tlet response: HttpClientResponse<Record<string, string>> | undefined;\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke refresh token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke access token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (response && !response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tsuccess = false;\n\t\t\tthis.logging?.info(`Token revocation failed - ${error}`);\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Refresh token successfully revoked');\n\t\t\t\t}\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Access token successfully revoked');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Exchanging authorization code for tokens');\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tconst error = new Error('Invalid or missing code');\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tconst error = new Error('Invalid or missing state');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst data = await response.json();\n\t\t\tconst error = new Error(`${data.error}: ${data.error_description}`);\n\t\t\tthis.logging?.error('Token exchange failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tObject.assign(this.session, await response.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tconst error = new Error('Invalid scope');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tconst error = new Error('Invalid nonce');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tconst error = new Error('Invalid iss');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tconst error = new Error('Invalid aud');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\n\t\t\tif (this.logging) {\n\t\t\t\tthis.logging.xEventId = undefined;\n\t\t\t\tthis.logging.info('Login successful');\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t *\n\t * @throws {Error} Throws an error if metadata retrieval fails.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues?.length) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint?.length) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales?.length) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\t\tif (params.audiences?.length) {\n\t\t\turl.searchParams.append('audience', params.audiences.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tasync waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<T>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest<T>(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<T>> {\n\t\treturn this.httpClient.request<T>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","logging","error","Metadata","#init","Session","isAuthenticated","params","session","url","response","data","jwt","success","state","serializedState","State","eventName","callbackFn","args","eventFn"],"mappings":"yTAkBA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAgH,CAIrIC,GAKAC,GAAmD,KAOnDC,GAA0B,GAO1B,WAOA,QAKA,QAOA,SAOA,QAA0B,KAO1B,QAOA,IAAI,eAAkD,CACrD,OAAO,KAAK,SAAS,MACtB,CAOA,IAAI,aAAyC,CAC5C,OAAO,KAAK,SAAS,YACtB,CAOA,IAAI,cAA0C,CAC7C,OAAO,KAAK,SAAS,aACtB,CAOA,IAAI,mBAA6B,CAChC,OAAO,KAAKA,EACb,CAOA,IAAI,oBAA8B,CACjC,MAAO,CAAC,KAAK,SAAS,cAAgB,CAAC,KAAK,SAAS,YAAc,KAAK,QAAQ,YAAcC,EAAAA,UAAA,CAC/F,CAOA,IAAI,2BAAuD,CAC1D,OAAO,KAAK,SAAS,UACtB,CAOA,IAAI,iBAAoC,CACvC,OAAI,KAAKF,GACD,KAAKA,IAGb,KAAKA,GAA0B,KAAKG,GAAA,EAE7B,KAAKH,GACb,CAQA,IAAI,qBAA+B,CAClC,MAAO,GAAQ,KAAK,SAAS,cAAgB,CAAC,KAAK,mBACpD,CAYA,YAAYI,EAAkBC,EAAqBC,EAA2BC,EAAsB,CACnG,GAAI,CAACH,EAAQ,OAAQ,CACpB,MAAMI,EAAQ,IAAI,MAAM,wBAAwB,EAChD,MAAAD,GAAS,MAAM,0BAA2BC,CAAK,EACzCA,CACP,CACA,GAAI,CAACJ,EAAQ,SAAU,CACtB,MAAMI,EAAQ,IAAI,MAAM,0BAA0B,EAClD,MAAAD,GAAS,MAAM,0BAA2BC,CAAK,EACzCA,CACP,CACA,GAAI,CAACJ,EAAQ,YAAa,CACzB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],"sourcesContent":["import type {\n\tIdTokenClaims,\n\tSDKOptions,\n\tSDKStorage,\n\tEventFunctions,\n\tExtraRequestArgs,\n\tLogoutParams,\n\tSDKHttpClient,\n\tHttpClientResponse,\n\tSDKLogging,\n} from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Logging utility for the SDK.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t * @param {SDKHttpClient} httpClient - HTTP client for making requests.\n\t * @param {SDKLogging} [logging] - Optional logging utility.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.issuer) {\n\t\t\tconst error = new Error('Missing option: issuer');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tconst error = new Error('Missing option: clientId');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tconst error = new Error('Missing option: redirectUri');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tconst error = new Error('Invalid option: scopes');\n\t\t\tlogging?.error('Invalid option provided', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.logging = logging;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\t\tthis.logging?.debug('SDK initialized');\n\n\t\tif (!this.session) {\n\t\t\tthis.logging?.debug('No session found in storage');\n\t\t}\n\n\t\tif (this.session && this.accessToken) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\tthis.logging?.debug('Session loaded from storage');\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\tthis.logging?.debug('Access token has expired');\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\tthis.logging?.warn('Initialization failed');\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t *\n\t * @throws {Error} Throws an error if URL handler is not defined.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to logout');\n\n\t\tconst session = this.session;\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tif (!session?.id_token) {\n\t\t\tthis.logging?.debug('Logout called without session');\n\t\t\treturn;\n\t\t}\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\t\tthis.logging?.debug('Logout initiated');\n\n\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to refresh session');\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthis.logging?.debug('Session refresh not possible - session not found');\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\n\t\t\tObject.assign(this.session, await response.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t\tthis.logging?.info('Session refreshed successfully');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t\tthis.logging?.info(`Session refresh failed - ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tlet response: HttpClientResponse<Record<string, string>> | undefined;\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke refresh token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke access token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (response && !response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tsuccess = false;\n\t\t\tthis.logging?.info(`Token revocation failed - ${error}`);\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Refresh token successfully revoked');\n\t\t\t\t}\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Access token successfully revoked');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Exchanging authorization code for tokens');\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tconst error = new Error('Invalid or missing code');\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tconst error = new Error('Invalid or missing state');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst data = await response.json();\n\t\t\tconst error = new Error(`${data.error}: ${data.error_description}`);\n\t\t\tthis.logging?.error('Token exchange failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tObject.assign(this.session, await response.json());\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\n\t\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\t\tconst error = new Error('Invalid nonce');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\t\tconst error = new Error('Invalid iss');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tArray.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId\n\t\t\t) {\n\t\t\t\tconst error = new Error('Invalid aud');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\n\t\t\tif (this.logging) {\n\t\t\t\tthis.logging.xEventId = undefined;\n\t\t\t\tthis.logging.info('Login successful');\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t *\n\t * @throws {Error} Throws an error if metadata retrieval fails.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues?.length) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint?.length) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales?.length) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\t\tif (params.audiences?.length) {\n\t\t\turl.searchParams.append('audience', params.audiences.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tasync waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<T>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest<T>(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<T>> {\n\t\treturn this.httpClient.request<T>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","logging","error","Metadata","#init","Session","isAuthenticated","params","session","url","response","data","jwt","success","state","serializedState","State","eventName","callbackFn","args","eventFn"],"mappings":"yTAkBA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAgH,CAIrIC,GAKAC,GAAmD,KAOnDC,GAA0B,GAO1B,WAOA,QAKA,QAOA,SAOA,QAA0B,KAO1B,QAOA,IAAI,eAAkD,CACrD,OAAO,KAAK,SAAS,MACtB,CAOA,IAAI,aAAyC,CAC5C,OAAO,KAAK,SAAS,YACtB,CAOA,IAAI,cAA0C,CAC7C,OAAO,KAAK,SAAS,aACtB,CAOA,IAAI,mBAA6B,CAChC,OAAO,KAAKA,EACb,CAOA,IAAI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oBgB,EAAaE,EAA+B,GAAoC,CACzG,OAAO,KAAK,WAAW,QAAWF,EAAK,CACtC,OAAQ,OACR,QAAS,CAAE,eAAgB,mCAAA,EAC3B,KAAM,IAAI,gBAAgBE,CAAI,EAAE,SAAA,CAAS,CACzC,CACF,CASA,iBACCM,EACAC,EAC0B,CAC1B,OAAA3B,EAAe0B,CAAS,EAAE,IAAIC,CAAU,EAEjC,CACN,QAAS,IAAM,CACd3B,EAAe0B,CAAS,EAAE,OAAOC,CAAU,CAC5C,CAAA,CAEF,CAQU,cAA8CD,EAAcE,EAA2C,CAChH,UAAWC,KAAW7B,EAAe0B,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CAEtB,CACD"}
@@ -1,2 +1,2 @@
1
- import{jwt as r}from"../utils/jwt.mjs";import{timestamp as h}from"../utils/date.mjs";import{Metadata as c}from"../utils/Metadata.mjs";import{Session as a}from"../utils/Session.mjs";import{State as d}from"../utils/State.mjs";import"../utils/base64Url.mjs";import"../utils/crypto.mjs";const n={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class T{#i;#e=null;#s=!1;httpClient;storage;logging;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=h()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#o(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,i,t,s){if(!e.issuer){const o=new Error("Missing option: issuer");throw s?.error("Required option missing",o),o}if(!e.clientId){const o=new Error("Missing option: clientId");throw s?.error("Required option missing",o),o}if(!e.redirectUri){const o=new Error("Missing option: redirectUri");throw s?.error("Required option missing",o),o}if(!e.urlHandler){const o=new Error("Missing option: urlHandler");throw s?.error("Required option missing",o),o}if(!e.callbackHandler){const o=new Error("Missing option: callbackHandler");throw s?.error("Required option missing",o),o}if(e.scopes&&!Array.isArray(e.scopes)){const o=new Error("Invalid option: scopes");throw s?.error("Invalid option provided",o),o}e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=i,this.httpClient=t,this.logging=s,this.metadata=new c(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#i=this.#t()}async#t(){this.session=a.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.logging?.debug("SDK initialized"),this.session||this.logging?.debug("No session found in storage"),this.session&&this.accessToken&&this.idTokenClaims&&(this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.debug("Session loaded from storage")),this.accessToken&&this.accessTokenExpired&&(this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),this.logging?.debug("Access token has expired"))}async#o(){let e=!1;try{await this.waitToInitialize()}catch{this.logging?.warn("Initialization failed")}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function"){const s=new Error("Missing option: urlHandler");throw this.logging?.error("Required option missing",s),s}await this.waitToInitialize(),this.logging?.debug("Attempting to logout");const i=this.session;if(!i?.id_token){this.logging?.debug("Logout called without session");return}await this.storage.delete(this.options.storageTokenName),this.session=null;const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",i?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:i.id_token,claims:i.claims}]),this.logging?.debug("Logout initiated"),await this.options.urlHandler(t.toString(),e)}async refresh(){if(await this.waitToInitialize(),this.logging?.debug("Attempting to refresh session"),typeof this.session?.refresh_token!="string"){this.logging?.debug("Session refresh not possible - session not found");return}const e=this.session;try{const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});if(!i.ok){const t=await i.json();throw new Error(`${t.error}: ${t.error_description}`)}Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=r.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&(this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.info("Session refreshed successfully"))}catch(i){this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}]),this.logging?.info(`Session refresh failed - ${i}`)}}async revoke(){await this.waitToInitialize();const e=this.session;let i=!0;try{let t;if(e?.refresh_token?(this.logging?.debug("Attempting to revoke refresh token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token})):e?.access_token&&(this.logging?.debug("Attempting to revoke access token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})),t&&!t.ok){const s=await t.json();throw new Error(`${s.error}: ${s.error_description}`)}}catch(t){i=!1,this.logging?.info(`Token revocation failed - ${t}`)}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?(this.dispatchEvent(i?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]),i&&this.logging?.info("Refresh token successfully revoked")):e?.access_token&&(this.dispatchEvent(i?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}]),i&&this.logging?.info("Access token successfully revoked"))}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.logging?.debug("Exchanging authorization code for tokens"),this.session=new a,Object.assign(this.session,e),this.session.error){const s=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Authorization error",s),s}if(!this.session.code){const s=new Error("Invalid or missing code");throw this.logging?.error("Authorization error",s),s}let i;try{const s=await this.storage.get(`sty.${this.session.state}`);if(!s)throw new Error;i=d.fromSerializedData(s),await this.storage.delete(`sty.${this.session.state}`)}catch{const s=new Error("Invalid or missing state");throw this.logging?.error("Validation failed",s),s}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:i.codeVerifier,code:this.session.code});if(!t.ok){const s=await t.json(),o=new Error(`${s.error}: ${s.error_description}`);throw this.logging?.error("Token exchange failed",o),o}if(Object.assign(this.session,await t.json()),this.session.id_token&&(this.session.claims=r.decode(this.session.id_token)),this.session.error){const s=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Validation failed",s),s}if(this.session.scope!==this.options.scopes?.join(" ")){const s=new Error("Invalid scope");throw this.logging?.error("Validation failed",s),s}if(this.session.claims?.nonce!==i.nonce){const s=new Error("Invalid nonce");throw this.logging?.error("Validation failed",s),s}if(this.session.claims?.iss!==await this.metadata.issuer){const s=new Error("Invalid iss");throw this.logging?.error("Validation failed",s),s}if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId){const s=new Error("Invalid aud");throw this.logging?.error("Validation failed",s),s}await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&(this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging&&(this.logging.xEventId=void 0,this.logging.info("Login successful")))}async getAuthorizationUrl(e={}){const i=new URL(await this.metadata.authorizationEndpoint);return i.searchParams.append("client_id",this.options.clientId),i.searchParams.append("redirect_uri",this.options.redirectUri),i.searchParams.append("response_type",this.options.responseType||"code"),i.searchParams.append("response_mode",this.options.responseMode||"fragment"),i.searchParams.append("scope",this.options.scopes?.join(" ")||""),i.searchParams.append("code_challenge_method","S256"),e.prompt&&i.searchParams.append("prompt",e.prompt),e.acrValues?.length&&i.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint?.length&&i.searchParams.append("login_hint",e.loginHint),e.uiLocales?.length&&i.searchParams.append("ui_locales",e.uiLocales.join(" ")),e.audiences?.length&&i.searchParams.append("audience",e.audiences.join(" ")),i}async waitToInitialize(){await this.#i}async sendTokenRequest(e,i={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(i).toString()})}subscribeToEvent(e,i){return n[e].add(i),{dispose:()=>{n[e].delete(i)}}}dispatchEvent(e,i){for(const t of n[e])t(...i)}}export{T as BaseFlow};
1
+ import{jwt as r}from"../utils/jwt.mjs";import{timestamp as h}from"../utils/date.mjs";import{Metadata as c}from"../utils/Metadata.mjs";import{Session as a}from"../utils/Session.mjs";import{State as d}from"../utils/State.mjs";import"../utils/base64Url.mjs";import"../utils/crypto.mjs";const n={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};class T{#i;#e=null;#s=!1;httpClient;storage;logging;metadata;session=null;options;get idTokenClaims(){return this.session?.claims}get accessToken(){return this.session?.access_token}get refreshToken(){return this.session?.refresh_token}get refreshInProgress(){return this.#s}get accessTokenExpired(){return!this.session?.access_token||!this.session?.expires_at||this.session.expires_at<=h()}get accessTokenExpirationDate(){return this.session?.expires_at}get isAuthenticated(){return this.#e?this.#e:(this.#e=this.#o(),this.#e)}get isAuthenticatedSync(){return!!(this.session?.access_token&&!this.accessTokenExpired)}constructor(e,s,t,i){if(!e.issuer){const o=new Error("Missing option: issuer");throw i?.error("Required option missing",o),o}if(!e.clientId){const o=new Error("Missing option: clientId");throw i?.error("Required option missing",o),o}if(!e.redirectUri){const o=new Error("Missing option: redirectUri");throw i?.error("Required option missing",o),o}if(!e.urlHandler){const o=new Error("Missing option: urlHandler");throw i?.error("Required option missing",o),o}if(!e.callbackHandler){const o=new Error("Missing option: callbackHandler");throw i?.error("Required option missing",o),o}if(e.scopes&&!Array.isArray(e.scopes)){const o=new Error("Invalid option: scopes");throw i?.error("Invalid option provided",o),o}e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=t,this.logging=i,this.metadata=new c(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),this.#i=this.#t()}async#t(){this.session=a.load(await this.storage.get(this.options.storageTokenName)),this.dispatchEvent("init",[]),this.logging?.debug("SDK initialized"),this.session||this.logging?.debug("No session found in storage"),this.session&&this.accessToken&&(this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.debug("Session loaded from storage")),this.accessToken&&this.accessTokenExpired&&(this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),this.logging?.debug("Access token has expired"))}async#o(){let e=!1;try{await this.waitToInitialize()}catch{this.logging?.warn("Initialization failed")}if(this.accessTokenExpired&&this.refreshToken&&!this.refreshInProgress)try{this.#s=!0,await this.refresh()}catch{}finally{this.#s=!1}return this.accessTokenExpired||(e=!0),this.#e=null,e}async logout(e){if(typeof this.options.urlHandler!="function"){const i=new Error("Missing option: urlHandler");throw this.logging?.error("Required option missing",i),i}await this.waitToInitialize(),this.logging?.debug("Attempting to logout");const s=this.session;if(await this.storage.delete(this.options.storageTokenName),this.session=null,!s?.id_token){this.logging?.debug("Logout called without session");return}const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",s?.id_token),e?.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]),this.logging?.debug("Logout initiated"),await this.options.urlHandler(t.toString(),e)}async refresh(){if(await this.waitToInitialize(),this.logging?.debug("Attempting to refresh session"),typeof this.session?.refresh_token!="string"){this.logging?.debug("Session refresh not possible - session not found");return}const e=this.session;try{const s=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:this.session?.refresh_token});if(!s.ok){const t=await s.json();throw new Error(`${t.error}: ${t.error_description}`)}Object.assign(this.session,await s.json()),this.session.id_token&&(this.session.claims=r.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&(this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging?.info("Session refreshed successfully"))}catch(s){this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}]),this.logging?.info(`Session refresh failed - ${s}`)}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{let t;if(e?.refresh_token?(this.logging?.debug("Attempting to revoke refresh token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token})):e?.access_token&&(this.logging?.debug("Attempting to revoke access token"),t=await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})),t&&!t.ok){const i=await t.json();throw new Error(`${i.error}: ${i.error_description}`)}}catch(t){s=!1,this.logging?.info(`Token revocation failed - ${t}`)}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e?.refresh_token?(this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]),s&&this.logging?.info("Refresh token successfully revoked")):e?.access_token&&(this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}]),s&&this.logging?.info("Access token successfully revoked"))}}async tokenExchange(e={}){if(await this.waitToInitialize(),this.logging?.debug("Exchanging authorization code for tokens"),this.session=new a,Object.assign(this.session,e),this.session.error){const i=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Authorization error",i),i}if(!this.session.code){const i=new Error("Invalid or missing code");throw this.logging?.error("Authorization error",i),i}let s;try{const i=await this.storage.get(`sty.${this.session.state}`);if(!i)throw new Error;s=d.fromSerializedData(i),await this.storage.delete(`sty.${this.session.state}`)}catch{const i=new Error("Invalid or missing state");throw this.logging?.error("Validation failed",i),i}const t=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(!t.ok){const i=await t.json(),o=new Error(`${i.error}: ${i.error_description}`);throw this.logging?.error("Token exchange failed",o),o}if(Object.assign(this.session,await t.json()),this.session.error){const i=new Error(`${this.session.error}: ${this.session.error_description}`);throw this.logging?.error("Validation failed",i),i}if(this.session.id_token){if(this.session.claims=r.decode(this.session.id_token),this.session.claims?.nonce!==s.nonce){const i=new Error("Invalid nonce");throw this.logging?.error("Validation failed",i),i}if(this.session.claims?.iss!==await this.metadata.issuer){const i=new Error("Invalid iss");throw this.logging?.error("Validation failed",i),i}if(Array.isArray(this.session.claims?.aud)?this.session.claims?.aud[0]!==this.options.clientId:this.session.claims?.aud!==this.options.clientId){const i=new Error("Invalid aud");throw this.logging?.error("Validation failed",i),i}}await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&(this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.logging&&(this.logging.xEventId=void 0,this.logging.info("Login successful")))}async getAuthorizationUrl(e={}){const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",this.options.scopes?.join(" ")||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues?.length&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint?.length&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales?.length&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),e.audiences?.length&&s.searchParams.append("audience",e.audiences.join(" ")),s}async waitToInitialize(){await this.#i}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return n[e].add(s),{dispose:()=>{n[e].delete(s)}}}dispatchEvent(e,s){for(const t of n[e])t(...s)}}export{T as BaseFlow};
2
2
  //# sourceMappingURL=BaseFlow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type {\n\tIdTokenClaims,\n\tSDKOptions,\n\tSDKStorage,\n\tEventFunctions,\n\tExtraRequestArgs,\n\tLogoutParams,\n\tSDKHttpClient,\n\tHttpClientResponse,\n\tSDKLogging,\n} from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Logging utility for the SDK.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t * @param {SDKHttpClient} httpClient - HTTP client for making requests.\n\t * @param {SDKLogging} [logging] - Optional logging utility.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.issuer) {\n\t\t\tconst error = new Error('Missing option: issuer');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tconst error = new Error('Missing option: clientId');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tconst error = new Error('Missing option: redirectUri');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tconst error = new Error('Invalid option: scopes');\n\t\t\tlogging?.error('Invalid option provided', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.logging = logging;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\t\tthis.logging?.debug('SDK initialized');\n\n\t\tif (!this.session) {\n\t\t\tthis.logging?.debug('No session found in storage');\n\t\t}\n\n\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\tthis.logging?.debug('Session loaded from storage');\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\tthis.logging?.debug('Access token has expired');\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\tthis.logging?.warn('Initialization failed');\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t *\n\t * @throws {Error} Throws an error if URL handler is not defined.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to logout');\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\tthis.logging?.debug('Logout called without session');\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\t\tthis.logging?.debug('Logout initiated');\n\n\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to refresh session');\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthis.logging?.debug('Session refresh not possible - session not found');\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\n\t\t\tObject.assign(this.session, await response.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t\tthis.logging?.info('Session refreshed successfully');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t\tthis.logging?.info(`Session refresh failed - ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tlet response: HttpClientResponse<Record<string, string>> | undefined;\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke refresh token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke access token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (response && !response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tsuccess = false;\n\t\t\tthis.logging?.info(`Token revocation failed - ${error}`);\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Refresh token successfully revoked');\n\t\t\t\t}\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Access token successfully revoked');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Exchanging authorization code for tokens');\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tconst error = new Error('Invalid or missing code');\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tconst error = new Error('Invalid or missing state');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst data = await response.json();\n\t\t\tconst error = new Error(`${data.error}: ${data.error_description}`);\n\t\t\tthis.logging?.error('Token exchange failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tObject.assign(this.session, await response.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tconst error = new Error('Invalid scope');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tconst error = new Error('Invalid nonce');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tconst error = new Error('Invalid iss');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tconst error = new Error('Invalid aud');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\n\t\t\tif (this.logging) {\n\t\t\t\tthis.logging.xEventId = undefined;\n\t\t\t\tthis.logging.info('Login successful');\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t *\n\t * @throws {Error} Throws an error if metadata retrieval fails.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues?.length) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint?.length) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales?.length) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\t\tif (params.audiences?.length) {\n\t\t\turl.searchParams.append('audience', params.audiences.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tasync waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<T>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest<T>(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<T>> {\n\t\treturn this.httpClient.request<T>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","logging","error","Metadata","#init","Session","isAuthenticated","params","session","url","response","data","jwt","success","state","serializedState","State","eventName","callbackFn","args","eventFn"],"mappings":"2RAkBA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAgH,CAIrIC,GAKAC,GAAmD,KAOnDC,GAA0B,GAO1B,WAOA,QAKA,QAOA,SAOA,QAA0B,KAO1B,QAOA,IAAI,eAAkD,CACrD,OAAO,KAAK,SAAS,MACtB,CAOA,IAAI,aAAyC,CAC5C,OAAO,KAAK,SAAS,YACtB,CAOA,IAAI,cAA0C,CAC7C,OAAO,KAAK,SAAS,aACtB,CAOA,IAAI,mBAA6B,CAChC,OAAO,KAAKA,EACb,CAOA,IAAI,oBAA8B,CACjC,MAAO,CAAC,KAAK,SAAS,cAAgB,CAAC,KAAK,SAAS,YAAc,KAAK,QAAQ,YAAcC,EAAA,CAC/F,CAOA,IAAI,2BAAuD,CAC1D,OAAO,KAAK,SAAS,UACtB,CAOA,IAAI,iBAAoC,CACvC,OAAI,KAAKF,GACD,KAAKA,IAGb,KAAKA,GAA0B,KAAKG,GAAA,EAE7B,KAAKH,GACb,CAQA,IAAI,qBAA+B,CAClC,MAAO,GAAQ,KAAK,SAAS,cAAgB,CAAC,KAAK,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M,EACAC,EAC0B,CAC1B,OAAA3B,EAAe0B,CAAS,EAAE,IAAIC,CAAU,EAEjC,CACN,QAAS,IAAM,CACd3B,EAAe0B,CAAS,EAAE,OAAOC,CAAU,CAC5C,CAAA,CAEF,CAQU,cAA8CD,EAAcE,EAA2C,CAChH,UAAWC,KAAW7B,EAAe0B,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CAEtB,CACD"}
1
+ {"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type {\n\tIdTokenClaims,\n\tSDKOptions,\n\tSDKStorage,\n\tEventFunctions,\n\tExtraRequestArgs,\n\tLogoutParams,\n\tSDKHttpClient,\n\tHttpClientResponse,\n\tSDKLogging,\n} from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initializationPromise: Promise<void>;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\t#refreshInProgressState = false;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Logging utility for the SDK.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Indicates whether a token refresh operation is currently in progress.\n\t *\n\t * @type {boolean}\n\t */\n\tget refreshInProgress(): boolean {\n\t\treturn this.#refreshInProgressState;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = this.#checkAuthentication();\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Checks authentication status without attempting token refresh.\n\t * Useful when you want to avoid side effects.\n\t *\n\t * @returns {boolean} - Returns `true` if the user has a valid, non-expired access token.\n\t */\n\tget isAuthenticatedSync(): boolean {\n\t\treturn Boolean(this.session?.access_token && !this.accessTokenExpired);\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t * @param {SDKHttpClient} httpClient - HTTP client for making requests.\n\t * @param {SDKLogging} [logging] - Optional logging utility.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.issuer) {\n\t\t\tconst error = new Error('Missing option: issuer');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tconst error = new Error('Missing option: clientId');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tconst error = new Error('Missing option: redirectUri');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tlogging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tconst error = new Error('Invalid option: scopes');\n\t\t\tlogging?.error('Invalid option provided', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.logging = logging;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tthis.#initializationPromise = this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tthis.dispatchEvent('init', []);\n\t\tthis.logging?.debug('SDK initialized');\n\n\t\tif (!this.session) {\n\t\t\tthis.logging?.debug('No session found in storage');\n\t\t}\n\n\t\tif (this.session && this.accessToken) {\n\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\tthis.logging?.debug('Session loaded from storage');\n\t\t}\n\n\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\tthis.logging?.debug('Access token has expired');\n\t\t}\n\t}\n\n\t/**\n\t * Internal method to check authentication status with proper error handling.\n\t * @ignore\n\t */\n\tasync #checkAuthentication(): Promise<boolean> {\n\t\tlet isAuthenticated = false;\n\n\t\ttry {\n\t\t\tawait this.waitToInitialize();\n\t\t} catch {\n\t\t\tthis.logging?.warn('Initialization failed');\n\t\t}\n\n\t\t// Attempt to refresh the token if it has expired\n\t\tif (this.accessTokenExpired && this.refreshToken && !this.refreshInProgress) {\n\t\t\ttry {\n\t\t\t\tthis.#refreshInProgressState = true;\n\t\t\t\tawait this.refresh();\n\t\t\t} catch {\n\t\t\t\t// Token refresh failed - if you want to log errors use the tokenRefreshFailed event\n\t\t\t} finally {\n\t\t\t\tthis.#refreshInProgressState = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!this.accessTokenExpired) {\n\t\t\tisAuthenticated = true;\n\t\t}\n\n\t\tthis.#isAuthenticatedPromise = null;\n\n\t\treturn isAuthenticated;\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Initiates the entry process.\n\t * @param {string} url Optional URL to use for the entry process. If not provided, the current window location will be used.\n\t * @returns {Promise<void>} A promise that resolves when the entry process completes.\n\t */\n\tabstract entry(url?: string): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t *\n\t * @throws {Error} Throws an error if URL handler is not defined.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: urlHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to logout');\n\n\t\tconst session = this.session;\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tif (!session?.id_token) {\n\t\t\tthis.logging?.debug('Logout called without session');\n\t\t\treturn;\n\t\t}\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\t\tthis.logging?.debug('Logout initiated');\n\n\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Attempting to refresh session');\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthis.logging?.debug('Session refresh not possible - session not found');\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\n\t\t\tObject.assign(this.session, await response.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t\tthis.logging?.info('Session refreshed successfully');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t\tthis.logging?.info(`Session refresh failed - ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tlet response: HttpClientResponse<Record<string, string>> | undefined;\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke refresh token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.logging?.debug('Attempting to revoke access token');\n\n\t\t\t\tresponse = await this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (response && !response.ok) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tthrow new Error(`${data.error}: ${data.error_description}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tsuccess = false;\n\t\t\tthis.logging?.info(`Token revocation failed - ${error}`);\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Refresh token successfully revoked');\n\t\t\t\t}\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\n\t\t\t\tif (success) {\n\t\t\t\t\tthis.logging?.info('Access token successfully revoked');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.logging?.debug('Exchanging authorization code for tokens');\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tconst error = new Error('Invalid or missing code');\n\t\t\tthis.logging?.error('Authorization error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tconst error = new Error('Invalid or missing state');\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst response = await this.sendTokenRequest<Session>(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst data = await response.json();\n\t\t\tconst error = new Error(`${data.error}: ${data.error_description}`);\n\t\t\tthis.logging?.error('Token exchange failed', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tObject.assign(this.session, await response.json());\n\n\t\tif (this.session.error) {\n\t\t\tconst error = new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\n\t\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\t\tconst error = new Error('Invalid nonce');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\t\tconst error = new Error('Invalid iss');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tArray.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId\n\t\t\t) {\n\t\t\t\tconst error = new Error('Invalid aud');\n\t\t\t\tthis.logging?.error('Validation failed', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\n\t\t\tif (this.logging) {\n\t\t\t\tthis.logging.xEventId = undefined;\n\t\t\t\tthis.logging.info('Login successful');\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t *\n\t * @throws {Error} Throws an error if metadata retrieval fails.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues?.length) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint?.length) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales?.length) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\t\tif (params.audiences?.length) {\n\t\t\turl.searchParams.append('audience', params.audiences.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tasync waitToInitialize(): Promise<void> {\n\t\tawait this.#initializationPromise;\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<T>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest<T>(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<T>> {\n\t\treturn this.httpClient.request<T>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","#initializationPromise","#isAuthenticatedPromise","#refreshInProgressState","timestamp","#checkAuthentication","options","storage","httpClient","logging","error","Metadata","#init","Session","isAuthenticated","params","session","url","response","data","jwt","success","state","serializedState","State","eventName","callbackFn","args","eventFn"],"mappings":"2RAkBA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB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I,aAAa,OAAO,aAAcF,EAAO,SAAS,EAEnDA,EAAO,WAAW,QACrBE,EAAI,aAAa,OAAO,aAAcF,EAAO,UAAU,KAAK,GAAG,CAAC,EAE7DA,EAAO,WAAW,QACrBE,EAAI,aAAa,OAAO,WAAYF,EAAO,UAAU,KAAK,GAAG,CAAC,EAGxDE,CACR,CAEA,MAAM,kBAAkC,CACvC,MAAM,KAAKhB,EACZ,CASA,MAAM,iBAAoBgB,EAAaE,EAA+B,GAAoC,CACzG,OAAO,KAAK,WAAW,QAAWF,EAAK,CACtC,OAAQ,OACR,QAAS,CAAE,eAAgB,mCAAA,EAC3B,KAAM,IAAI,gBAAgBE,CAAI,EAAE,SAAA,CAAS,CACzC,CACF,CASA,iBACCM,EACAC,EAC0B,CAC1B,OAAA3B,EAAe0B,CAAS,EAAE,IAAIC,CAAU,EAEjC,CACN,QAAS,IAAM,CACd3B,EAAe0B,CAAS,EAAE,OAAOC,CAAU,CAC5C,CAAA,CAEF,CAQU,cAA8CD,EAAcE,EAA2C,CAChH,UAAWC,KAAW7B,EAAe0B,CAAS,EACxCG,EAAQ,GAAGD,CAAI,CAEtB,CACD"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../utils/handlers.cjs"),g=require("../handlers/EmbeddedFlowHandler.cjs"),u=require("./BaseFlow.cjs");require("../utils/errors.cjs");require("../handlers/BaseFlowHandler.cjs");require("../utils/State.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class p extends u.BaseFlow{constructor(r,e,s,i){r.urlHandler||(r.urlHandler=c.redirectUrlHandler),r.callbackHandler||(r.callbackHandler=c.redirectCallbackHandler),super(r,e,s,i),globalThis.sty||(globalThis.sty={}),globalThis.sty.oidcService=this}login(r={}){return this.dispatchEvent("loginInitiated",[]),new g.EmbeddedFlowHandler(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){r||(r=globalThis.window?.location.href);const e=new URL(r);e.searchParams.append("sdk","web-embedded"),e.searchParams.append("client_id",this.options.clientId),e.searchParams.append("redirect_uri",this.options.redirectUri);const s=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${e.searchParams.toString()}`,{headers:{"Accept-Language":"*"}});if(!s.ok){if(s.status===400){const o=await s.json();let n="Entry request failed with status 400";typeof o=="object"&&(o.error?n=`${o.error}: ${o.error_description}`:o.errorKey&&(n=o.errorKey));const d=new Error(n);throw this.logging?.error("Entry request error",d),d}const t=new Error(`Entry request failed with status ${s.status}`);throw this.logging?.error("Entry request error",t),t}let i;try{i=new URL(await s.text())}catch{i=new URL(s.url)}const a=i.searchParams.get("short_app_id"),l=i.searchParams.get("session_id"),h=i.searchParams.get("language")||navigator.language;if(!a){const t=new Error('"short_app_id" is missing from the response');throw this.logging?.error("Entry response error",t),t}if(!l){const t=new Error('"session_id" is missing from the response');throw this.logging?.error("Entry response error",t),t}return{session_id:l,short_app_id:a,language:h}}async handleCallback(r){if(typeof this.options.callbackHandler!="function"){const e=new Error("Missing option: callbackHandler");throw this.logging?.error("Required option missing",e),e}r||(r=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}exports.EmbeddedFlow=p;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../utils/handlers.cjs"),g=require("../handlers/EmbeddedFlowHandler.cjs"),u=require("./BaseFlow.cjs");require("../utils/errors.cjs");require("../handlers/BaseFlowHandler.cjs");require("../utils/State.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class w extends u.BaseFlow{constructor(r,e,s,i){r.urlHandler||(r.urlHandler=c.redirectUrlHandler),r.callbackHandler||(r.callbackHandler=c.redirectCallbackHandler),super(r,e,s,i),globalThis.sty||(globalThis.sty={}),globalThis.sty.oidcService=this}login(r={}){return this.dispatchEvent("loginInitiated",[]),new g.EmbeddedFlowHandler(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){r||(r=globalThis.window?.location.href);const e=new URL(r);e.searchParams.append("sdk","web-embedded"),e.searchParams.append("client_id",this.options.clientId),e.searchParams.append("redirect_uri",this.options.redirectUri);const s=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${e.searchParams.toString()}`);if(!s.ok){if(s.status===400){const o=await s.json();let n="Entry request failed with status 400";typeof o=="object"&&(o.error?n=`${o.error}: ${o.error_description}`:o.errorKey&&(n=o.errorKey));const d=new Error(n);throw this.logging?.error("Entry request error",d),d}const t=new Error(`Entry request failed with status ${s.status}`);throw this.logging?.error("Entry request error",t),t}let i;try{i=new URL(await s.text())}catch{i=new URL(s.url)}const a=i.searchParams.get("short_app_id"),l=i.searchParams.get("session_id"),h=i.searchParams.get("language")||navigator.language;if(!a){const t=new Error('"short_app_id" is missing from the response');throw this.logging?.error("Entry response error",t),t}if(!l){const t=new Error('"session_id" is missing from the response');throw this.logging?.error("Entry response error",t),t}return{session_id:l,short_app_id:a,language:h}}async handleCallback(r){if(typeof this.options.callbackHandler!="function"){const e=new Error("Missing option: callbackHandler");throw this.logging?.error("Required option missing",e),e}r||(r=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}exports.EmbeddedFlow=w;
2
2
  //# sourceMappingURL=EmbeddedFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"EmbeddedFlow.cjs","sources":["../../src/flows/EmbeddedFlow.ts"],"sourcesContent":["import type { SDKOptions, SDKStorage, SDKHttpClient, SDKLogging, ExtraRequestArgs } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { EmbeddedFlowHandler } from '../handlers/EmbeddedFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class EmbeddedFlow extends BaseFlow<SDKOptions, ExtraRequestArgs> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient, logging);\n\n\t\tif (!globalThis.sty) {\n\t\t\tglobalThis.sty = {};\n\t\t}\n\n\t\t// NOTE: Register the OIDC service instance globally for use in the login component\n\t\tglobalThis.sty.oidcService = this;\n\t}\n\n\t/**\n\t * Initiates the login process via embedded UI.\n\t * @param {ExtraRequestArgs} [params={}] Optional parameters for the login request.\n\t * @returns {EmbeddedFlowHandler} Returns with an embedded login handler.\n\t */\n\toverride login(params: ExtraRequestArgs = {}): EmbeddedFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new EmbeddedFlowHandler(this, params);\n\t}\n\n\toverride register(params: ExtraRequestArgs = {}) {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\toverride async entry(url?: string) {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web-embedded');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\t'Accept-Language': '*',\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst error = new Error(message);\n\t\t\t\tthis.logging?.error('Entry request error', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tconst error = new Error(`Entry request failed with status ${response.status}`);\n\t\t\tthis.logging?.error('Entry request error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet uri: URL;\n\n\t\ttry {\n\t\t\turi = new URL(await response.text());\n\t\t} catch {\n\t\t\turi = new URL(response.url);\n\t\t}\n\n\t\tconst shortAppId = uri.searchParams.get('short_app_id');\n\t\tconst sessionId = uri.searchParams.get('session_id');\n\t\tconst language = uri.searchParams.get('language') || navigator.language;\n\n\t\tif (!shortAppId) {\n\t\t\tconst error = new Error('\"short_app_id\" is missing from the response');\n\t\t\tthis.logging?.error('Entry response error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!sessionId) {\n\t\t\tconst error = new Error('\"session_id\" is missing from the response');\n\t\t\tthis.logging?.error('Entry response error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn { session_id: sessionId, short_app_id: shortAppId, language: language };\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t *\n\t * @throws {Error} Throws an error if callback handler is not defined.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["EmbeddedFlow","BaseFlow","options","storage","httpClient","logging","redirectUrlHandler","redirectCallbackHandler","params","EmbeddedFlowHandler","url","entryUrl","response","data","message","error","uri","shortAppId","sessionId","language"],"mappings":"yeAKO,MAAMA,UAAqBC,EAAAA,QAAuC,CACxE,YAAYC,EAAqBC,EAAqBC,EAA2BC,EAAsB,CACjGH,EAAQ,aACZA,EAAQ,WAAaI,EAAAA,oBAEjBJ,EAAQ,kBACZA,EAAQ,gBAAkBK,EAAAA,yBAG3B,MAAML,EAASC,EAASC,EAAYC,CAAO,EAEtC,WAAW,MACf,WAAW,IAAM,CAAA,GAIlB,WAAW,IAAI,YAAc,IAC9B,CAOS,MAAMG,EAA2B,GAAyB,CAClE,YAAK,cAAc,iBAAkB,EAAE,EAEhC,IAAIC,EAAAA,oBAAoB,KAAMD,CAAM,CAC5C,CAES,SAASA,EAA2B,GAAI,CAChD,OAAAA,EAAO,OAAS,SAET,KAAK,MAAMA,CAAM,CACzB,CAEA,MAAe,MAAME,EAAc,CAC7BA,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAMC,EAAW,IAAI,IAAID,CAAG,EAC5BC,EAAS,aAAa,OAAO,MAAO,cAAc,EAClDA,EAAS,aAAa,OAAO,YAAa,KAAK,QAAQ,QAAQ,EAC/DA,EAAS,aAAa,OAAO,eAAgB,KAAK,QAAQ,WAAW,EAErE,MAAMC,EAAW,MAAM,KAAK,WAAW,QACtC,GAAG,KAAK,QAAQ,MAAM,wBAAwBD,EAAS,aAAa,UAAU,GAC9E,CACC,QAAS,CACR,kBAAmB,GAAA,CACpB,CACD,EAGD,GAAI,CAACC,EAAS,GAAI,CACjB,GAAIA,EAAS,SAAW,IAAK,CAC5B,MAAMC,EAAO,MAAMD,EAAS,KAAA,EAC5B,IAAIE,EAAU,uCAEV,OAAOD,GAAS,WACfA,EAAK,MACRC,EAAU,GAAGD,EAAK,KAAK,KAAKA,EAAK,iBAAiB,GACxCA,EAAK,WACfC,EAAUD,EAAK,WAIjB,MAAME,EAAQ,IAAI,MAAMD,CAAO,EAC/B,WAAK,SAAS,MAAM,sBAAuBC,CAAK,EAC1CA,CACP,CAEA,MAAMA,EAAQ,IAAI,MAAM,oCAAoCH,EAAS,MAAM,EAAE,EAC7E,WAAK,SAAS,MAAM,sBAAuBG,CAAK,EAC1CA,CACP,CAEA,IAAIC,EAEJ,GAAI,CACHA,EAAM,IAAI,IAAI,MAAMJ,EAAS,MAAM,CACpC,MAAQ,CACPI,EAAM,IAAI,IAAIJ,EAAS,GAAG,CAC3B,CAEA,MAAMK,EAAaD,EAAI,aAAa,IAAI,cAAc,EAChDE,EAAYF,EAAI,aAAa,IAAI,YAAY,EAC7CG,EAAWH,EAAI,aAAa,IAAI,UAAU,GAAK,UAAU,SAE/D,GAAI,CAACC,EAAY,CAChB,MAAMF,EAAQ,IAAI,MAAM,6CAA6C,EACrE,WAAK,SAAS,MAAM,uBAAwBA,CAAK,EAC3CA,CACP,CACA,GAAI,CAACG,EAAW,CACf,MAAMH,EAAQ,IAAI,MAAM,2CAA2C,EACnE,WAAK,SAAS,MAAM,uBAAwBA,CAAK,EAC3CA,CACP,CAEA,MAAO,CAAE,WAAYG,EAAW,aAAcD,EAAY,SAAAE,CAAA,CAC3D,CASA,MAAM,eAAeT,EAA6B,CACjD,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAAY,CACvD,MAAMK,EAAQ,IAAI,MAAM,iCAAiC,EACzD,WAAK,SAAS,MAAM,0BAA2BA,CAAK,EAC9CA,CACP,CAEKL,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAM,KAAK,cAAe,MAAM,KAAK,QAAQ,gBAAgBA,EAAK,KAAK,QAAQ,cAAgB,UAAU,CAA4B,CACtI,CACD"}
1
+ {"version":3,"file":"EmbeddedFlow.cjs","sources":["../../src/flows/EmbeddedFlow.ts"],"sourcesContent":["import type { SDKOptions, SDKStorage, SDKHttpClient, SDKLogging, ExtraRequestArgs } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { EmbeddedFlowHandler } from '../handlers/EmbeddedFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class EmbeddedFlow extends BaseFlow<SDKOptions, ExtraRequestArgs> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient, logging?: SDKLogging) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient, logging);\n\n\t\tif (!globalThis.sty) {\n\t\t\tglobalThis.sty = {};\n\t\t}\n\n\t\t// NOTE: Register the OIDC service instance globally for use in the login component\n\t\tglobalThis.sty.oidcService = this;\n\t}\n\n\t/**\n\t * Initiates the login process via embedded UI.\n\t * @param {ExtraRequestArgs} [params={}] Optional parameters for the login request.\n\t * @returns {EmbeddedFlowHandler} Returns with an embedded login handler.\n\t */\n\toverride login(params: ExtraRequestArgs = {}): EmbeddedFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new EmbeddedFlowHandler(this, params);\n\t}\n\n\toverride register(params: ExtraRequestArgs = {}) {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\toverride async entry(url?: string) {\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tconst entryUrl = new URL(url);\n\t\tentryUrl.searchParams.append('sdk', 'web-embedded');\n\t\tentryUrl.searchParams.append('client_id', this.options.clientId);\n\t\tentryUrl.searchParams.append('redirect_uri', this.options.redirectUri);\n\n\t\tconst response = await this.httpClient.request<string | Record<string, string>>(\n\t\t\t`${this.options.issuer}/provider/flow/entry?${entryUrl.searchParams.toString()}`,\n\t\t);\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 400) {\n\t\t\t\tconst data = await response.json();\n\t\t\t\tlet message = 'Entry request failed with status 400';\n\n\t\t\t\tif (typeof data === 'object') {\n\t\t\t\t\tif (data.error) {\n\t\t\t\t\t\tmessage = `${data.error}: ${data.error_description}`;\n\t\t\t\t\t} else if (data.errorKey) {\n\t\t\t\t\t\tmessage = data.errorKey;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst error = new Error(message);\n\t\t\t\tthis.logging?.error('Entry request error', error);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tconst error = new Error(`Entry request failed with status ${response.status}`);\n\t\t\tthis.logging?.error('Entry request error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tlet uri: URL;\n\n\t\ttry {\n\t\t\turi = new URL(await response.text());\n\t\t} catch {\n\t\t\turi = new URL(response.url);\n\t\t}\n\n\t\tconst shortAppId = uri.searchParams.get('short_app_id');\n\t\tconst sessionId = uri.searchParams.get('session_id');\n\t\tconst language = uri.searchParams.get('language') || navigator.language;\n\n\t\tif (!shortAppId) {\n\t\t\tconst error = new Error('\"short_app_id\" is missing from the response');\n\t\t\tthis.logging?.error('Entry response error', error);\n\t\t\tthrow error;\n\t\t}\n\t\tif (!sessionId) {\n\t\t\tconst error = new Error('\"session_id\" is missing from the response');\n\t\t\tthis.logging?.error('Entry response error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn { session_id: sessionId, short_app_id: shortAppId, language: language };\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t *\n\t * @throws {Error} Throws an error if callback handler is not defined.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tconst error = new Error('Missing option: callbackHandler');\n\t\t\tthis.logging?.error('Required option missing', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["EmbeddedFlow","BaseFlow","options","storage","httpClient","logging","redirectUrlHandler","redirectCallbackHandler","params","EmbeddedFlowHandler","url","entryUrl","response","data","message","error","uri","shortAppId","sessionId","language"],"mappings":"yeAKO,MAAMA,UAAqBC,EAAAA,QAAuC,CACxE,YAAYC,EAAqBC,EAAqBC,EAA2BC,EAAsB,CACjGH,EAAQ,aACZA,EAAQ,WAAaI,EAAAA,oBAEjBJ,EAAQ,kBACZA,EAAQ,gBAAkBK,EAAAA,yBAG3B,MAAML,EAASC,EAASC,EAAYC,CAAO,EAEtC,WAAW,MACf,WAAW,IAAM,CAAA,GAIlB,WAAW,IAAI,YAAc,IAC9B,CAOS,MAAMG,EAA2B,GAAyB,CAClE,YAAK,cAAc,iBAAkB,EAAE,EAEhC,IAAIC,EAAAA,oBAAoB,KAAMD,CAAM,CAC5C,CAES,SAASA,EAA2B,GAAI,CAChD,OAAAA,EAAO,OAAS,SAET,KAAK,MAAMA,CAAM,CACzB,CAEA,MAAe,MAAME,EAAc,CAC7BA,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAMC,EAAW,IAAI,IAAID,CAAG,EAC5BC,EAAS,aAAa,OAAO,MAAO,cAAc,EAClDA,EAAS,aAAa,OAAO,YAAa,KAAK,QAAQ,QAAQ,EAC/DA,EAAS,aAAa,OAAO,eAAgB,KAAK,QAAQ,WAAW,EAErE,MAAMC,EAAW,MAAM,KAAK,WAAW,QACtC,GAAG,KAAK,QAAQ,MAAM,wBAAwBD,EAAS,aAAa,UAAU,EAAA,EAG/E,GAAI,CAACC,EAAS,GAAI,CACjB,GAAIA,EAAS,SAAW,IAAK,CAC5B,MAAMC,EAAO,MAAMD,EAAS,KAAA,EAC5B,IAAIE,EAAU,uCAEV,OAAOD,GAAS,WACfA,EAAK,MACRC,EAAU,GAAGD,EAAK,KAAK,KAAKA,EAAK,iBAAiB,GACxCA,EAAK,WACfC,EAAUD,EAAK,WAIjB,MAAME,EAAQ,IAAI,MAAMD,CAAO,EAC/B,WAAK,SAAS,MAAM,sBAAuBC,CAAK,EAC1CA,CACP,CAEA,MAAMA,EAAQ,IAAI,MAAM,oCAAoCH,EAAS,MAAM,EAAE,EAC7E,WAAK,SAAS,MAAM,sBAAuBG,CAAK,EAC1CA,CACP,CAEA,IAAIC,EAEJ,GAAI,CACHA,EAAM,IAAI,IAAI,MAAMJ,EAAS,MAAM,CACpC,MAAQ,CACPI,EAAM,IAAI,IAAIJ,EAAS,GAAG,CAC3B,CAEA,MAAMK,EAAaD,EAAI,aAAa,IAAI,cAAc,EAChDE,EAAYF,EAAI,aAAa,IAAI,YAAY,EAC7CG,EAAWH,EAAI,aAAa,IAAI,UAAU,GAAK,UAAU,SAE/D,GAAI,CAACC,EAAY,CAChB,MAAMF,EAAQ,IAAI,MAAM,6CAA6C,EACrE,WAAK,SAAS,MAAM,uBAAwBA,CAAK,EAC3CA,CACP,CACA,GAAI,CAACG,EAAW,CACf,MAAMH,EAAQ,IAAI,MAAM,2CAA2C,EACnE,WAAK,SAAS,MAAM,uBAAwBA,CAAK,EAC3CA,CACP,CAEA,MAAO,CAAE,WAAYG,EAAW,aAAcD,EAAY,SAAAE,CAAA,CAC3D,CASA,MAAM,eAAeT,EAA6B,CACjD,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAAY,CACvD,MAAMK,EAAQ,IAAI,MAAM,iCAAiC,EACzD,WAAK,SAAS,MAAM,0BAA2BA,CAAK,EAC9CA,CACP,CAEKL,IACJA,EAAM,WAAW,QAAQ,SAAS,MAGnC,MAAM,KAAK,cAAe,MAAM,KAAK,QAAQ,gBAAgBA,EAAK,KAAK,QAAQ,cAAgB,UAAU,CAA4B,CACtI,CACD"}
@@ -1,2 +1,2 @@
1
- import{redirectUrlHandler as h,redirectCallbackHandler as p}from"../utils/handlers.mjs";import{EmbeddedFlowHandler as g}from"../handlers/EmbeddedFlowHandler.mjs";import{BaseFlow as m}from"./BaseFlow.mjs";import"../utils/errors.mjs";import"../handlers/BaseFlowHandler.mjs";import"../utils/State.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class $ extends m{constructor(r,e,t,o){r.urlHandler||(r.urlHandler=h),r.callbackHandler||(r.callbackHandler=p),super(r,e,t,o),globalThis.sty||(globalThis.sty={}),globalThis.sty.oidcService=this}login(r={}){return this.dispatchEvent("loginInitiated",[]),new g(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){r||(r=globalThis.window?.location.href);const e=new URL(r);e.searchParams.append("sdk","web-embedded"),e.searchParams.append("client_id",this.options.clientId),e.searchParams.append("redirect_uri",this.options.redirectUri);const t=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${e.searchParams.toString()}`,{headers:{"Accept-Language":"*"}});if(!t.ok){if(t.status===400){const i=await t.json();let n="Entry request failed with status 400";typeof i=="object"&&(i.error?n=`${i.error}: ${i.error_description}`:i.errorKey&&(n=i.errorKey));const c=new Error(n);throw this.logging?.error("Entry request error",c),c}const s=new Error(`Entry request failed with status ${t.status}`);throw this.logging?.error("Entry request error",s),s}let o;try{o=new URL(await t.text())}catch{o=new URL(t.url)}const a=o.searchParams.get("short_app_id"),l=o.searchParams.get("session_id"),d=o.searchParams.get("language")||navigator.language;if(!a){const s=new Error('"short_app_id" is missing from the response');throw this.logging?.error("Entry response error",s),s}if(!l){const s=new Error('"session_id" is missing from the response');throw this.logging?.error("Entry response error",s),s}return{session_id:l,short_app_id:a,language:d}}async handleCallback(r){if(typeof this.options.callbackHandler!="function"){const e=new Error("Missing option: callbackHandler");throw this.logging?.error("Required option missing",e),e}r||(r=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}export{$ as EmbeddedFlow};
1
+ import{redirectUrlHandler as h,redirectCallbackHandler as p}from"../utils/handlers.mjs";import{EmbeddedFlowHandler as g}from"../handlers/EmbeddedFlowHandler.mjs";import{BaseFlow as m}from"./BaseFlow.mjs";import"../utils/errors.mjs";import"../handlers/BaseFlowHandler.mjs";import"../utils/State.mjs";import"../utils/crypto.mjs";import"../utils/base64Url.mjs";import"../utils/date.mjs";import"../utils/jwt.mjs";import"../utils/Metadata.mjs";import"../utils/Session.mjs";class $ extends m{constructor(r,e,t,o){r.urlHandler||(r.urlHandler=h),r.callbackHandler||(r.callbackHandler=p),super(r,e,t,o),globalThis.sty||(globalThis.sty={}),globalThis.sty.oidcService=this}login(r={}){return this.dispatchEvent("loginInitiated",[]),new g(this,r)}register(r={}){return r.prompt="create",this.login(r)}async entry(r){r||(r=globalThis.window?.location.href);const e=new URL(r);e.searchParams.append("sdk","web-embedded"),e.searchParams.append("client_id",this.options.clientId),e.searchParams.append("redirect_uri",this.options.redirectUri);const t=await this.httpClient.request(`${this.options.issuer}/provider/flow/entry?${e.searchParams.toString()}`);if(!t.ok){if(t.status===400){const i=await t.json();let n="Entry request failed with status 400";typeof i=="object"&&(i.error?n=`${i.error}: ${i.error_description}`:i.errorKey&&(n=i.errorKey));const c=new Error(n);throw this.logging?.error("Entry request error",c),c}const s=new Error(`Entry request failed with status ${t.status}`);throw this.logging?.error("Entry request error",s),s}let o;try{o=new URL(await t.text())}catch{o=new URL(t.url)}const a=o.searchParams.get("short_app_id"),l=o.searchParams.get("session_id"),d=o.searchParams.get("language")||navigator.language;if(!a){const s=new Error('"short_app_id" is missing from the response');throw this.logging?.error("Entry response error",s),s}if(!l){const s=new Error('"session_id" is missing from the response');throw this.logging?.error("Entry response error",s),s}return{session_id:l,short_app_id:a,language:d}}async handleCallback(r){if(typeof this.options.callbackHandler!="function"){const e=new Error("Missing option: callbackHandler");throw this.logging?.error("Required option missing",e),e}r||(r=globalThis.window?.location.href),await this.tokenExchange(await this.options.callbackHandler(r,this.options.responseMode||"fragment"))}}export{$ as EmbeddedFlow};
2
2
  //# sourceMappingURL=EmbeddedFlow.mjs.map