@strivacity/sdk-core 4.0.0-beta.0 → 4.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +228 -86
- package/dist/assets/oidc.cjs +1 -1
- package/dist/assets/oidc.cjs.map +1 -1
- package/dist/assets/oidc.mjs +1 -1
- package/dist/assets/oidc.mjs.map +1 -1
- package/dist/assets/server.cjs +1 -1
- package/dist/assets/server.cjs.map +1 -1
- package/dist/assets/server.mjs +1 -1
- package/dist/assets/server.mjs.map +1 -1
- package/dist/flows/base.cjs +1 -1
- package/dist/flows/base.cjs.map +1 -1
- package/dist/flows/base.d.ts +4 -2
- package/dist/flows/base.mjs +1 -1
- package/dist/flows/base.mjs.map +1 -1
- package/dist/flows/popup.cjs +1 -1
- package/dist/flows/popup.cjs.map +1 -1
- package/dist/flows/popup.mjs +1 -1
- package/dist/flows/popup.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/server/base.cjs +1 -1
- package/dist/server/base.cjs.map +1 -1
- package/dist/server/base.d.ts +2 -4
- package/dist/server/base.mjs +1 -1
- package/dist/server/base.mjs.map +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.mjs +1 -1
- package/dist/storages/cache.cjs.map +1 -1
- package/dist/storages/cache.d.ts +1 -1
- package/dist/storages/cache.mjs.map +1 -1
- package/dist/storages/index.cjs +1 -1
- package/dist/storages/index.mjs +1 -1
- package/dist/storages/server.cjs +1 -1
- package/dist/storages/server.d.ts +29 -1
- package/dist/storages/server.mjs +1 -1
- package/dist/storages/worker.cjs.map +1 -1
- package/dist/storages/worker.d.ts +1 -1
- package/dist/storages/worker.mjs.map +1 -1
- package/dist/types/native.d.ts +67 -2
- package/dist/types/oidc.cjs.map +1 -1
- package/dist/types/oidc.d.ts +47 -6
- package/dist/types/oidc.mjs.map +1 -1
- package/dist/types/popup.d.ts +1 -1
- package/dist/types/server.d.ts +21 -9
- package/dist/utils/index.cjs +1 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.mjs +1 -1
- package/dist/utils/native-login.cjs +2 -0
- package/dist/utils/native-login.cjs.map +1 -0
- package/dist/utils/native-login.d.ts +13 -0
- package/dist/utils/native-login.mjs +2 -0
- package/dist/utils/native-login.mjs.map +1 -0
- package/dist/utils/oidc.d.ts +3 -4
- package/dist/utils/path.cjs +2 -0
- package/dist/utils/path.cjs.map +1 -0
- package/dist/utils/path.d.ts +16 -0
- package/dist/utils/path.mjs +2 -0
- package/dist/utils/path.mjs.map +1 -0
- package/dist/utils/server.d.ts +5 -4
- package/dist/utils/session.cjs +1 -1
- package/dist/utils/session.cjs.map +1 -1
- package/dist/utils/session.d.ts +10 -1
- package/dist/utils/session.mjs +1 -1
- package/dist/utils/session.mjs.map +1 -1
- package/package.json +1 -1
- package/testing/tests/flows/base.spec.ts +0 -1030
- package/testing/tests/flows/embedded.spec.ts +0 -443
- package/testing/tests/flows/index.spec.ts +0 -8
- package/testing/tests/flows/native.spec.ts +0 -487
- package/testing/tests/flows/popup.spec.ts +0 -400
- package/testing/tests/flows/redirect.spec.ts +0 -369
- package/testing/tests/handlers/embedded.spec.ts +0 -199
- package/testing/tests/handlers/index.spec.ts +0 -8
- package/testing/tests/handlers/native.spec.ts +0 -283
- package/testing/tests/handlers/popup.spec.ts +0 -206
- package/testing/tests/handlers/redirect.spec.ts +0 -70
- package/testing/tests/index.spec.ts +0 -78
- package/testing/tests/server/base.spec.ts +0 -846
- package/testing/tests/server/index.spec.ts +0 -15
- package/testing/tests/storages/cache.spec.ts +0 -107
- package/testing/tests/storages/index.spec.ts +0 -22
- package/testing/tests/storages/indexeddb.spec.ts +0 -113
- package/testing/tests/storages/local.spec.ts +0 -46
- package/testing/tests/storages/memory.spec.ts +0 -51
- package/testing/tests/storages/server.spec.ts +0 -435
- package/testing/tests/storages/session.spec.ts +0 -46
- package/testing/tests/storages/worker.spec.ts +0 -106
- package/testing/tests/utils/common.spec.ts +0 -77
- package/testing/tests/utils/credentials.spec.ts +0 -195
- package/testing/tests/utils/dom.spec.ts +0 -37
- package/testing/tests/utils/index.spec.ts +0 -71
- package/testing/tests/utils/logging.spec.ts +0 -82
- package/testing/tests/utils/oidc.spec.ts +0 -744
- package/testing/tests/utils/server.spec.ts +0 -235
package/dist/types/oidc.d.ts
CHANGED
|
@@ -330,6 +330,12 @@ export type LogoutParams = {
|
|
|
330
330
|
postLogoutRedirectUri?: string;
|
|
331
331
|
};
|
|
332
332
|
export type ExtraRequestArgs = {
|
|
333
|
+
/**
|
|
334
|
+
* Where to send the user after the login completes: a same-origin path or URL (e.g. the page a route guard protected).
|
|
335
|
+
* In `redirect` mode the SDK keeps it with the login state and `handleCallback()` returns it. With `serverSessionUri` it is
|
|
336
|
+
* forwarded to the Server SDK login route, which redirects there after its callback. The other modes ignore it.
|
|
337
|
+
*/
|
|
338
|
+
returnTo?: string;
|
|
333
339
|
/**
|
|
334
340
|
* Specifies the type of prompt to display to the user during authentication or authorization.
|
|
335
341
|
*
|
|
@@ -465,19 +471,43 @@ export type SDKOptions<Storage extends SDKStorage = SDKStorage, StateStorage ext
|
|
|
465
471
|
*/
|
|
466
472
|
lazyLoad: boolean;
|
|
467
473
|
/**
|
|
468
|
-
*
|
|
474
|
+
* Refreshes an expired (or about to expire, see `refreshSkew`) access token automatically.
|
|
475
|
+
* - Client SDK: refreshes when the authentication state is checked. Ignored when `serverSessionUri` is set.
|
|
476
|
+
* - Server SDK: refreshes when the session is read. With `false` an expired session is not refreshed.
|
|
469
477
|
*
|
|
470
478
|
* @default true
|
|
471
479
|
*/
|
|
472
480
|
autoRefresh: boolean;
|
|
481
|
+
/**
|
|
482
|
+
* The amount of time (in seconds) before the access token's expiration that the SDK should attempt to refresh it.
|
|
483
|
+
*
|
|
484
|
+
* @default 60
|
|
485
|
+
*/
|
|
486
|
+
refreshSkew: number;
|
|
487
|
+
/**
|
|
488
|
+
* The amount of time (in seconds) tolerated as clock difference between the device and the authorization server when validating token expiration.
|
|
489
|
+
*
|
|
490
|
+
* @default 60
|
|
491
|
+
*/
|
|
492
|
+
clockSkew: number;
|
|
473
493
|
/**
|
|
474
494
|
* The URL of your backend-for-frontend (BFF) endpoint that the SDK will route login/registration/start-session requests to instead of building the authorization URL itself.
|
|
475
495
|
* Setting this also switches the SDK into server-managed session mode: tokens are never read from or written to client-side storage, and successful authorization responses redirect the browser instead of being exchanged for tokens client-side.
|
|
476
|
-
* If not set, the SDK talks to the IDP directly and manages the session client-side.
|
|
496
|
+
* If not set (or set to `false` / `null`), the SDK talks to the IDP directly and manages the session client-side.
|
|
497
|
+
* Setting it to `true` enables server-managed session mode without routing through a BFF endpoint (the SDK builds the authorization URL itself).
|
|
477
498
|
*
|
|
478
|
-
* @default
|
|
499
|
+
* @default null (client SDK) / `${authUrlPrefix}/login` (server SDK)
|
|
479
500
|
*/
|
|
480
501
|
serverSessionUri?: boolean | string | null;
|
|
502
|
+
/**
|
|
503
|
+
* URL prefix of the Server SDK auth routes (`/login`, `/callback`, `/refresh`, `/logout`, ...).
|
|
504
|
+
* With server-managed sessions (`serverSessionUri`) the browser never refreshes tokens itself: `refresh()` and the route guards
|
|
505
|
+
* (`withAuthGuard`) send the browser to `${authUrlPrefix}/refresh` with `returnTo` set to the current URL, so the server
|
|
506
|
+
* refreshes the session, writes the rotated cookie and redirects back.
|
|
507
|
+
*
|
|
508
|
+
* @default '/auth'
|
|
509
|
+
*/
|
|
510
|
+
authUrlPrefix: string;
|
|
481
511
|
/**
|
|
482
512
|
* Discovery document metadata is cached for this amount of time (in seconds) before being refreshed from the authorization server.
|
|
483
513
|
*
|
|
@@ -714,17 +744,21 @@ export type SDK<URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs, En
|
|
|
714
744
|
* Handles the authentication callback by parsing the response from the given URL.
|
|
715
745
|
*
|
|
716
746
|
* @param {string | URL} [url] - The callback URL to process. Defaults to the current page URL if omitted.
|
|
717
|
-
* @returns {Promise<
|
|
747
|
+
* @returns {Promise<CallbackResult>} The `returnTo` given to `login()` / `register()`, if any.
|
|
718
748
|
* @throws {Error} Throws an error if the callback handling fails or if the URL is invalid.
|
|
719
749
|
*/
|
|
720
|
-
handleCallback(url?: string | URL): Promise<
|
|
750
|
+
handleCallback(url?: string | URL): Promise<CallbackResult>;
|
|
721
751
|
/**
|
|
722
752
|
* Refreshes the current access token using the refresh token.
|
|
753
|
+
* With server-managed sessions, navigates the browser to the server's refresh route (`${authUrlPrefix}/refresh`) instead.
|
|
723
754
|
*
|
|
755
|
+
* @param {{ returnTo?: string }} [params] - Server-managed only: where the refresh route should return to (defaults to the current URL).
|
|
724
756
|
* @returns {Promise<void>}
|
|
725
757
|
* @throws {Error} Throws an error if the refresh process fails or if no refresh token is available.
|
|
726
758
|
*/
|
|
727
|
-
refresh(
|
|
759
|
+
refresh(params?: {
|
|
760
|
+
returnTo?: string;
|
|
761
|
+
}): Promise<void>;
|
|
728
762
|
/**
|
|
729
763
|
* Revokes the current tokens.
|
|
730
764
|
*
|
|
@@ -766,3 +800,10 @@ export type SDK<URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs, En
|
|
|
766
800
|
*/
|
|
767
801
|
entry(url?: string | URL, params?: RedirectOptions): EntryReturnType;
|
|
768
802
|
};
|
|
803
|
+
/**
|
|
804
|
+
* The result of `handleCallback()`.
|
|
805
|
+
*/
|
|
806
|
+
export type CallbackResult = {
|
|
807
|
+
/** The same-origin path given to `login({ returnTo })` / `register({ returnTo })`, to navigate to after the login. */
|
|
808
|
+
returnTo?: string;
|
|
809
|
+
};
|
package/dist/types/oidc.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oidc.mjs","names":[],"sources":["../../src/types/oidc.ts"],"sourcesContent":["import type { SDKHttpClient, SDKLogging, SDKStorage } from './common';\nimport type { RedirectOptions } from './redirect';\nimport type { BACKCHANNEL_LOGOUT_EVENT } from '../utils/server';\n\nexport const ResponseTypeList = ['code'] as const;\nexport type ResponseType = (typeof ResponseTypeList)[number];\n\nexport const ResponseModeList = ['query', 'fragment'] as const;\nexport type ResponseMode = (typeof ResponseModeList)[number];\n\nexport const TokenEndpointAuthMethodList = ['none'] as const;\nexport type TokenEndpointAuthMethod = (typeof TokenEndpointAuthMethodList)[number];\n\nexport const GrantTypeList = ['authorization_code', 'refresh_token'] as const;\nexport type GrantType = (typeof GrantTypeList)[number];\n\nexport const AlgorithmTypeList = ['RS256'] as const;\nexport type AlgorithmType = (typeof AlgorithmTypeList)[number];\n\nexport const SubjectTypeList = ['public'] as const;\nexport type SubjectType = (typeof SubjectTypeList)[number];\n\nexport type SigningKey = {\n\t/**\n\t * The intended use of the key. Common values include \"sig\" for signature and \"enc\" for encryption.\n\t */\n\tuse: string;\n\n\t/**\n\t * The key type. For example, \"RSA\" for RSA keys or \"EC\" for Elliptic Curve keys.\n\t */\n\tkty: string;\n\n\t/**\n\t * A unique identifier for the key. This is used to distinguish the key from others.\n\t */\n\tkid: string;\n\n\t/**\n\t * The algorithm used with the key. For example, \"RS256\" for RSA SHA-256.\n\t */\n\talg: AlgorithmType;\n\n\t/**\n\t * The modulus of the RSA key, encoded in base64url format. For RSA keys, this is a required property.\n\t */\n\tn: string;\n\n\t/**\n\t * The exponent of the RSA key, encoded in base64url format. For RSA keys, this is a required property.\n\t */\n\te: string;\n};\n\nexport type DiscoveryDocument = {\n\t/**\n\t * The issuer of the tokens. This is the authorization server or entity that issues the tokens.\n\t */\n\tissuer: string;\n\n\t/**\n\t * The URL of the authorization endpoint where authentication requests are sent.\n\t */\n\tauthorization_endpoint: string;\n\n\t/**\n\t * The URL of the token endpoint where tokens are exchanged.\n\t */\n\ttoken_endpoint: string;\n\n\t/**\n\t * The URL of the JSON Web Key Set (JWKS) endpoint where public keys are available.\n\t */\n\tjwks_uri: string;\n\n\t/**\n\t * The types of subjects that are supported by the authorization server.\n\t */\n\tsubject_types_supported: Array<SubjectType>;\n\n\t/**\n\t * The types of responses supported by the authorization server.\n\t */\n\tresponse_types_supported: Array<string>;\n\n\t/**\n\t * The claims supported by the authorization server.\n\t */\n\tclaims_supported: Array<string>;\n\n\t/**\n\t * The grant types supported by the authorization server.\n\t */\n\tgrant_types_supported: Array<GrantType>;\n\n\t/**\n\t * The response modes supported by the authorization server.\n\t */\n\tresponse_modes_supported: Array<ResponseMode>;\n\n\t/**\n\t * The URL of the user info endpoint where user information can be retrieved.\n\t */\n\tuserinfo_endpoint: string;\n\n\t/**\n\t * The scopes supported by the authorization server.\n\t */\n\tscopes_supported: Array<string>;\n\n\t/**\n\t * The authentication methods supported for token endpoint authentication.\n\t */\n\ttoken_endpoint_auth_methods_supported: Array<TokenEndpointAuthMethod>;\n\n\t/**\n\t * The algorithms supported for signing tokens used in the user info endpoint.\n\t */\n\tuserinfo_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms supported for signing ID tokens.\n\t */\n\tid_token_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms used to sign ID tokens in response.\n\t */\n\tid_token_signed_response_alg: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms used to sign responses from the user info endpoint.\n\t */\n\tuserinfo_signed_response_alg: Array<AlgorithmType>;\n\n\t/**\n\t * Indicates whether the request parameter is supported in requests.\n\t */\n\trequest_parameter_supported: boolean;\n\n\t/**\n\t * Indicates whether the request URI parameter is supported in requests.\n\t */\n\trequest_uri_parameter_supported: boolean;\n\n\t/**\n\t * Indicates whether request URI registration is required.\n\t */\n\trequire_request_uri_registration: boolean;\n\n\t/**\n\t * Indicates whether the claims parameter is supported.\n\t */\n\tclaims_parameter_supported: boolean;\n\n\t/**\n\t * The URL of the revocation endpoint for revoking tokens.\n\t */\n\trevocation_endpoint: string;\n\n\t/**\n\t * Indicates whether backchannel logout is supported.\n\t */\n\tbackchannel_logout_supported: boolean;\n\n\t/**\n\t * Indicates whether backchannel logout session support is provided.\n\t */\n\tbackchannel_logout_session_supported: boolean;\n\n\t/**\n\t * Indicates whether frontchannel logout is supported.\n\t */\n\tfrontchannel_logout_supported: boolean;\n\n\t/**\n\t * Indicates whether frontchannel logout session support is provided.\n\t */\n\tfrontchannel_logout_session_supported: boolean;\n\n\t/**\n\t * The URL of the endpoint where end-session requests can be sent.\n\t */\n\tend_session_endpoint: string;\n\n\t/**\n\t * The algorithms supported for signing request objects.\n\t */\n\trequest_object_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The code challenge methods supported by the authorization server.\n\t */\n\tcode_challenge_methods_supported: Array<'S256'>;\n};\n\nexport type JwtClaims = {\n\t/**\n\t * The issuer of the token. This typically represents the authorization server or entity that issued the JWT.\n\t */\n\tiss?: string;\n\n\t/**\n\t * The subject of the token. This is the identifier for the entity the token represents, such as a user ID.\n\t */\n\tsub?: string;\n\n\t/**\n\t * The audience for which the token is intended. This can be a single identifier or an array of identifiers.\n\t */\n\taud?: string | Array<string>;\n\n\t/**\n\t * The expiration time of the token, expressed as a Unix timestamp (number of seconds since January 1, 1970).\n\t */\n\texp?: number;\n\n\t/**\n\t * The not-before time of the token, expressed as a Unix timestamp. The token must not be accepted before this time.\n\t */\n\tnbf?: number;\n\n\t/**\n\t * The issued-at time of the token, expressed as a Unix timestamp (number of seconds since January 1, 1970).\n\t */\n\tiat?: number;\n\n\t/**\n\t * A unique identifier for the token. This can be used to prevent token replay attacks.\n\t */\n\tjti?: string;\n};\n\nexport type IdTokenClaims = Required<Pick<JwtClaims, 'iss' | 'sub' | 'aud' | 'exp' | 'iat' | 'jti'>> & {\n\t/**\n\t * The authentication time, indicating when the user was authenticated.\n\t */\n\tauth_time?: number;\n\n\t/**\n\t * A nonce value used to associate a client session with an ID token, preventing replay attacks.\n\t */\n\tnonce?: string;\n\n\t/**\n\t * The Authentication Context Class Reference, indicating the authentication methods used.\n\t */\n\tacr?: string;\n\n\t/**\n\t * The Authentication Methods References, providing information about the authentication methods used.\n\t */\n\tamr?: unknown;\n\n\t/**\n\t * Authorized party, the client that the ID token is intended for.\n\t */\n\tazp?: string;\n\n\t/**\n\t * Session ID for the user, which can be used to manage user sessions.\n\t */\n\tsid?: string;\n\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t[key: string]: any;\n};\n\nexport type LogoutTokenClaims = Pick<JwtClaims, 'iss' | 'sub' | 'aud' | 'iat' | 'jti'> & {\n\t/**\n\t * Session ID for the user, which can be used to clear a specific session.\n\t */\n\tsid?: string;\n\n\t/**\n\t * Spec-compliant event signal for OpenID Connect Back-Channel Logout.\n\t */\n\tevents: Record<typeof BACKCHANNEL_LOGOUT_EVENT, Record<string, never>>;\n\n\t/**\n\t * MUST NOT contain a nonce claim according to the OIDC Back-Channel Logout spec.\n\t */\n\tnonce?: never;\n\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t[key: string]: any;\n};\n\nexport type SessionData = {\n\t/**\n\t * The state parameter used in the authentication request.\n\t */\n\tstate?: string | null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t */\n\tcode?: string | null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t */\n\terror?: string | null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t */\n\terror_description?: string | null;\n\n\t/**\n\t * A URI identifying a human-readable web page with information about the error (RFC 6749).\n\t */\n\terror_uri?: string | null;\n\n\t/**\n\t * Opaque value representing the session state at the authorization server (OIDC Session Management).\n\t */\n\tsession_state?: string | null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t */\n\tid_token?: string | null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t */\n\taccess_token?: string | null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t */\n\trefresh_token?: string | null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t */\n\ttoken_type?: string;\n\n\t/**\n\t * The scope of the issued token.\n\t */\n\tscope?: string | null;\n\n\t/**\n\t * The lifetime of the access token in seconds, as returned by the token endpoint.\n\t */\n\texpires_in?: number | null;\n\n\t/**\n\t * The absolute expiration time of the access token, represented as a Unix timestamp (seconds since epoch).\n\t */\n\texpires_at?: number | null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t */\n\tclaims?: IdTokenClaims | null;\n};\n\nexport type LoginSessionParams = {\n\t/**\n\t * The unique identifier of the login session.\n\t */\n\tsession_id?: string;\n\n\t/**\n\t * The short application identifier associated with the login session.\n\t */\n\tshort_app_id?: string;\n\n\t/**\n\t * BCP 47 language tag representing the language preference for the login session.\n\t */\n\tlanguage?: string;\n};\n\nexport type StateData = {\n\t/**\n\t * A unique identifier for the state.\n\t */\n\tid: string;\n\n\t/**\n\t * The timestamp when the state was created, represented as a Unix timestamp (seconds since epoch).\n\t */\n\tcreatedAt: number;\n\n\t/**\n\t * The code verifier used in the PKCE flow.\n\t */\n\tcodeVerifier: string;\n\n\t/**\n\t * The code challenge derived from the code verifier, used in the PKCE flow.\n\t */\n\tcodeChallenge: string;\n\n\t/**\n\t * A unique nonce value used to associate a client session with an ID token, preventing replay attacks.\n\t */\n\tnonce: string;\n\n\t/**\n\t * Optional metadata associated with the state, which can be used to store additional information relevant to the authentication flow.\n\t */\n\tmetadata?: Record<string, unknown>;\n};\n\nexport type LogoutParams = {\n\t/**\n\t * The URL to which the user should be redirected after logging out.\n\t */\n\tpostLogoutRedirectUri?: string;\n};\n\nexport type ExtraRequestArgs = {\n\t/**\n\t * Specifies the type of prompt to display to the user during authentication or authorization.\n\t *\n\t * @example 'none' | 'login' | 'create'\n\t */\n\tprompt?: string | null;\n\n\t/**\n\t * Specifies the display mode for the authentication or authorization request.\n\t *\n\t * @example 'page' | 'popup'\n\t */\n\tdisplay?: string | null;\n\n\t/**\n\t * Provides a hint to the authorization server about the user's email or username.\n\t *\n\t * @example 'user@example.com'\n\t */\n\tloginHint?: string | null;\n\n\t/**\n\t * A list of values used to request specific authentication contexts or levels of assurance.\n\t * This parameter allows requesting specific authentication contexts (e.g., multi-factor authentication)\n\t * or other criteria that the authorization server should consider when authenticating the user.\n\t *\n\t * @example ['urn:mace:incommon:iap:bronze', 'urn:mace:incommon:iap:silver']\n\t */\n\tacrValues?: Array<string> | null;\n\n\t/**\n\t * A list of BCP 47 language tags specifying the preferred display language for the customer-facing UI.\n\t * We uses this as a fallback when determining the display language.\n\t * It is only applied if no higher-priority signal is present.\n\t *\n\t * @see https://docs.strivacity.com/docs/translations\n\t * @example ['en-US', 'fr-FR', 'de-DE']\n\t */\n\tuiLocales?: Array<string> | null;\n\n\t/**\n\t * A list of audience values to specify the intended recipients of the token.\n\t * This parameter allows requesting that the issued token is intended for specific audiences.\n\t *\n\t * @example ['https://api.example.com', 'https://service.example.com']\n\t */\n\taudiences?: Array<string> | null;\n};\n\nexport type EntryResponse = {\n\t/**\n\t * The session ID associated with the entry flow. This is a unique identifier for the session and can be used to track or manage the session.\n\t */\n\tsession_id: string;\n\n\t/**\n\t * The short application ID associated with the entry flow. This is a unique identifier for the application and can be used to identify the application in various contexts.\n\t */\n\tshort_app_id: string;\n\n\t/**\n\t * The language code associated with the entry flow. This indicates the preferred language for the user interface and can be used to provide localized content.\n\t */\n\tlanguage: string;\n\n\t[key: string]: string;\n};\n\nexport type SDKOptions<Storage extends SDKStorage = SDKStorage, StateStorage extends SDKStorage = SDKStorage> = {\n\t/**\n\t * A factory function that creates an instance of the SDK based on the provided initialization options.\n\t *\n\t * @param options - The initialization options for the SDK.\n\t * @returns The instance created by the factory function.\n\t */\n\tfactory?: (options: SDKInitConfig) => unknown;\n\n\t/**\n\t * The mode of operation for the SDK, which determines how authentication flows are handled.\n\t *\n\t * @default 'redirect'\n\t */\n\tmode: 'popup' | 'redirect' | 'native' | 'embedded';\n\n\t/**\n\t * The issuer of the tokens, typically the URL of the authorization server.\n\t */\n\tissuer: string;\n\n\t/**\n\t * The client ID issued by the authorization server, used to identify the application.\n\t */\n\tclientId: string;\n\n\t/**\n\t * The URI to which the user will be redirected after authentication or authorization.\n\t */\n\tredirectUri: string;\n\n\t/**\n\t * A list of scopes requested by the application, defining the access levels for the tokens.\n\t *\n\t * @default ['openid']\n\t */\n\tscopes: Array<string>;\n\n\t/**\n\t * The type of response expected from the authorization server.\n\t *\n\t * @default 'code'\n\t */\n\tresponseType: ResponseType;\n\n\t/**\n\t * The mode in which the response is returned from the authorization server.\n\t *\n\t * @default 'query'\n\t */\n\tresponseMode: ResponseMode;\n\n\t/**\n\t * The storage mechanism used to save and retrieve authentication information.\n\t *\n\t * @default Storage\n\t */\n\tstorage: Storage;\n\n\t/**\n\t * The storage mechanism used to save and retrieve state information, such as the state parameter in OAuth flows.\n\t *\n\t * @default StateStorage\n\t */\n\tstateStorage: StateStorage;\n\n\t/**\n\t * The name of the storage token used to store session data.\n\t *\n\t * @default 'sty.session'\n\t */\n\tstorageTokenName: string;\n\n\t/**\n\t * The HTTP client used for making requests to the authorization server and other endpoints.\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The logging mechanism used for logging messages and errors.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Indicates whether the SDK should be lazily loaded, meaning that it will be initialized only when needed.\n\t *\n\t * @default false\n\t */\n\tlazyLoad: boolean;\n\n\t/**\n\t * Indicates whether the SDK should automatically refresh tokens when they are about to expire.\n\t *\n\t * @default true\n\t */\n\tautoRefresh: boolean;\n\n\t/**\n\t * The URL of your backend-for-frontend (BFF) endpoint that the SDK will route login/registration/start-session requests to instead of building the authorization URL itself.\n\t * Setting this also switches the SDK into server-managed session mode: tokens are never read from or written to client-side storage, and successful authorization responses redirect the browser instead of being exchanged for tokens client-side.\n\t * If not set, the SDK talks to the IDP directly and manages the session client-side.\n\t *\n\t * @default '/auth/login'\n\t */\n\tserverSessionUri?: boolean | string | null;\n\n\t/**\n\t * Discovery document metadata is cached for this amount of time (in seconds) before being refreshed from the authorization server.\n\t *\n\t * @default 3600 (1 hour)\n\t */\n\tdiscoveryDocumentCacheTTL: number;\n\n\t/**\n\t * JWKS (JSON Web Key Set) is cached for this amount of time (in seconds) before being refreshed from the authorization server.\n\t *\n\t * @default 600 (10 minutes)\n\t */\n\tjwksCacheTTL: number;\n\n\t/**\n\t * Handles the URL redirection to the specified target.\n\t * You can use this method to implement custom URL handling logic, such as opening a new window or navigating to a different page.\n\t *\n\t * @param {string | URL} url - The URL to handle.\n\t * @param {Record<string, unknown>} params - Optional parameters for redirection.\n\t * @returns - A promise that resolves when the redirection is handled.\n\t */\n\turlHandler: (url: string | URL, params?: Record<string, unknown>) => Promise<unknown>;\n\n\t/**\n\t * Handles the callback from the authorization server after a successful authentication or authorization.\n\t * You can use this method to implement custom logic for processing the response from the authorization server.\n\t *\n\t * @param {string | URL} url - The URL containing the response from the authorization server.\n\t * @param {ResponseMode} [responseMode] - Optional parameter specifying the response mode (query or fragment).\n\t * @returns - A promise that resolves when the callback is handled.\n\t */\n\tcallbackHandler: (url: string | URL, responseMode?: ResponseMode) => Promise<unknown>;\n};\n\nexport type SDKInitConfig = Partial<SDKOptions> & Required<Pick<SDKOptions, 'mode' | 'issuer' | 'clientId' | 'redirectUri'>>;\n\nexport type FlowState = {\n\t/**\n\t * Indicates whether the SDK has been initialized and is ready for use.\n\t */\n\tinitialized: boolean;\n\n\t/**\n\t * The current session data, which may include tokens and related information.\n\t */\n\tsession: SessionData | null;\n\n\t/**\n\t * The unique identifier for the current session, which may be used for tracking and correlation.\n\t */\n\tsessionId: string | null;\n\n\t/**\n\t * The short application identifier, which may be used for tracking and correlation.\n\t */\n\tshortAppId: string | null;\n\n\t/**\n\t * The language preference for the authentication flow, which may be used for localization.\n\t *\n\t * @default navigator.language\n\t */\n\tlanguage: string;\n};\n\nexport type EventFunctions = {\n\taccessTokenExpired: (params?: { accessToken?: string | null; refreshToken?: string | null }) => Promise<void> | void;\n\tinit: () => Promise<void> | void;\n\tloggedIn: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\tsessionUpdated: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\tsessionCleared: () => Promise<void> | void;\n\tloginInitiated: () => Promise<void> | void;\n\tflowInitiated: () => Promise<void> | void;\n\tlogoutInitiated: (params?: { idToken?: string | null; claims?: IdTokenClaims | null }) => Promise<void> | void;\n\tsessionLoaded: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\ttokenRefreshed: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\ttokenRefreshFailed: (params?: { refreshToken?: string | null }) => Promise<void> | void;\n\ttokenRevoked: (params?: { token?: string | null; tokenTypeHint?: 'refresh_token' | 'access_token' }) => Promise<void> | void;\n\ttokenRevokeFailed: (params?: { token?: string | null; tokenTypeHint?: 'refresh_token' | 'access_token' }) => Promise<void> | void;\n};\n\nexport type SDK<URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs, EntryReturnType = Promise<void>> = {\n\t/**\n\t * The resolved SDK configuration options in use.\n\t */\n\treadonly options: SDKOptions;\n\n\t/**\n\t * Whether the SDK has been fully initialized.\n\t */\n\treadonly initialized: boolean;\n\n\t/**\n\t * The storage adapter used to persist session and state data.\n\t */\n\treadonly storage: SDKStorage;\n\n\t/**\n\t * The HTTP client adapter used for making requests.\n\t */\n\treadonly httpClient: SDKHttpClient;\n\n\t/**\n\t * The optional logging adapter for SDK diagnostic output.\n\t */\n\treadonly logging?: SDKLogging;\n\n\t/**\n\t * The current session data, or `null` if no session is active.\n\t */\n\tsession: SessionData | null;\n\n\t/**\n\t * The short application ID associated with the current session, or `null` if not yet available.\n\t */\n\tshortAppId: string | null;\n\n\t/**\n\t * The unique identifier for the current session, or `null` if no session is active.\n\t */\n\tsessionId: string | null;\n\n\t/**\n\t * The language code used for the authentication UI.\n\t */\n\tlanguage: string;\n\n\t/**\n\t * A promise that resolves to `true` if the user is currently authenticated, `false` otherwise.\n\t */\n\treadonly isAuthenticated: Promise<boolean>;\n\n\t/**\n\t * A synchronous boolean indicating whether the user is currently authenticated.\n\t * This value may not reflect the most recent authentication state if the SDK has not been initialized or if a token refresh is pending.\n\t */\n\treadonly isAuthenticatedSync: boolean;\n\n\t/**\n\t * The current access token, or `null` if the user is not authenticated.\n\t */\n\treadonly accessToken: string | null;\n\n\t/**\n\t * Indicates whether the current access token has expired.\n\t */\n\treadonly accessTokenExpired: boolean;\n\n\t/**\n\t * The expiration time of the current access token, represented as a Unix timestamp (seconds since epoch), or `null` if no access token is present.\n\t */\n\treadonly accessTokenExpirationDate: number | null;\n\n\t/**\n\t * The current refresh token, or `null` if the user is not authenticated.\n\t */\n\treadonly refreshToken: string | null;\n\n\t/**\n\t * The current ID token, or `null` if the user is not authenticated.\n\t */\n\treadonly idToken: string | null;\n\n\t/**\n\t * The claims extracted from the current ID token, or `null` if no ID token is present.\n\t */\n\treadonly idTokenClaims: IdTokenClaims | null;\n\n\t/**\n\t * Subscribes to a specific SDK event by name.\n\t *\n\t * @template T - The name of the event to subscribe to.\n\t * @param {T} eventName - The name of the event.\n\t * @param {Function} callbackFn - The callback to invoke when the event fires.\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\n\t/**\n\t * Subscribes to all SDK events.\n\t *\n\t * @param {Function} callbackFn - The callback to invoke whenever any event fires.\n\t * @returns {{ dispose: () => void }} An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToAllEvents(callbackFn: (...params: Array<unknown>) => Promise<void> | void): { dispose: () => void };\n\n\t/**\n\t * Clears the current session data from storage.\n\t *\n\t * @returns {Promise<void>}\n\t */\n\tcleanupSession(): Promise<void>;\n\n\t/**\n\t * Replaces the current session data with the provided data.\n\t *\n\t * @param {SessionData} newData - The new session data to persist.\n\t * @returns {Promise<void>}\n\t */\n\tupdateSession(newData: SessionData): Promise<void>;\n\n\t/**\n\t * Checks whether the user is currently authenticated, optionally triggering a token refresh.\n\t *\n\t * @param {{ autoRefresh: boolean }} [params] - Options for the check.\n\t * @returns {Promise<boolean>} Resolves to `true` if authenticated, `false` otherwise.\n\t */\n\tcheckAuthentication(params?: { autoRefresh: boolean }): Promise<boolean>;\n\n\t/**\n\t * Initializes the SDK, loading metadata and restoring any persisted session.\n\t *\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the stored session cannot be loaded.\n\t */\n\tinit(): Promise<void>;\n\n\t/**\n\t * Performs a token exchange using the provided parameters.\n\t *\n\t * @param {Record<string, string>} [params] - Additional parameters for the token exchange request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the token exchange fails or if the provided parameters are invalid.\n\t */\n\ttokenExchange(params?: Record<string, string>): Promise<void>;\n\n\t/**\n\t * Handles the authentication callback by parsing the response from the given URL.\n\t *\n\t * @param {string | URL} [url] - The callback URL to process. Defaults to the current page URL if omitted.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the callback handling fails or if the URL is invalid.\n\t */\n\thandleCallback(url?: string | URL): Promise<void>;\n\n\t/**\n\t * Refreshes the current access token using the refresh token.\n\t *\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the refresh process fails or if no refresh token is available.\n\t */\n\trefresh(): Promise<void>;\n\n\t/**\n\t * Revokes the current tokens.\n\t *\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the revocation process fails or if no tokens are available to revoke.\n\t */\n\trevoke(): Promise<void>;\n\n\t/**\n\t * Logs the user out and optionally redirects to a post-logout URI.\n\t *\n\t * @param {LogoutParams} [params] - Optional logout and URL handler parameters.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the logout url handling fails or if the provided parameters are invalid.\n\t */\n\tlogout(params?: LogoutParams): Promise<void>;\n\n\t/**\n\t * Initiates the login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Optional parameters for the login request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the login process fails or if the provided parameters are invalid.\n\t */\n\tlogin(params?: URLHandlerParams): Promise<void>;\n\n\t/**\n\t * Initiates the registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Optional parameters for the registration request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the registration process fails or if the provided parameters are invalid.\n\t */\n\tregister(params?: URLHandlerParams): Promise<void>;\n\n\t/**\n\t * Handles the entry point URL of the authentication flow, typically used for embedded or native modes.\n\t *\n\t * @param {string | URL} [url] - The entry URL to process.\n\t * @param {RedirectOptions} [params] - Optional redirect options.\n\t * @returns {EntryReturnType}\n\t * @throws {Error} Throws an error if the entry URL is invalid or if the entry process fails.\n\t */\n\tentry(url?: string | URL, params?: RedirectOptions): EntryReturnType;\n};\n"],"mappings":"AAIA,IAAa,EAAmB,CAAC,MAAM,EAG1B,EAAmB,CAAC,QAAS,UAAU,EAGvC,EAA8B,CAAC,MAAM,EAGrC,EAAgB,CAAC,qBAAsB,eAAe,EAGtD,EAAoB,CAAC,OAAO,EAG5B,EAAkB,CAAC,QAAQ"}
|
|
1
|
+
{"version":3,"file":"oidc.mjs","names":[],"sources":["../../src/types/oidc.ts"],"sourcesContent":["import type { SDKHttpClient, SDKLogging, SDKStorage } from './common';\nimport type { RedirectOptions } from './redirect';\nimport type { BACKCHANNEL_LOGOUT_EVENT } from '../utils/server';\n\nexport const ResponseTypeList = ['code'] as const;\nexport type ResponseType = (typeof ResponseTypeList)[number];\n\nexport const ResponseModeList = ['query', 'fragment'] as const;\nexport type ResponseMode = (typeof ResponseModeList)[number];\n\nexport const TokenEndpointAuthMethodList = ['none'] as const;\nexport type TokenEndpointAuthMethod = (typeof TokenEndpointAuthMethodList)[number];\n\nexport const GrantTypeList = ['authorization_code', 'refresh_token'] as const;\nexport type GrantType = (typeof GrantTypeList)[number];\n\nexport const AlgorithmTypeList = ['RS256'] as const;\nexport type AlgorithmType = (typeof AlgorithmTypeList)[number];\n\nexport const SubjectTypeList = ['public'] as const;\nexport type SubjectType = (typeof SubjectTypeList)[number];\n\nexport type SigningKey = {\n\t/**\n\t * The intended use of the key. Common values include \"sig\" for signature and \"enc\" for encryption.\n\t */\n\tuse: string;\n\n\t/**\n\t * The key type. For example, \"RSA\" for RSA keys or \"EC\" for Elliptic Curve keys.\n\t */\n\tkty: string;\n\n\t/**\n\t * A unique identifier for the key. This is used to distinguish the key from others.\n\t */\n\tkid: string;\n\n\t/**\n\t * The algorithm used with the key. For example, \"RS256\" for RSA SHA-256.\n\t */\n\talg: AlgorithmType;\n\n\t/**\n\t * The modulus of the RSA key, encoded in base64url format. For RSA keys, this is a required property.\n\t */\n\tn: string;\n\n\t/**\n\t * The exponent of the RSA key, encoded in base64url format. For RSA keys, this is a required property.\n\t */\n\te: string;\n};\n\nexport type DiscoveryDocument = {\n\t/**\n\t * The issuer of the tokens. This is the authorization server or entity that issues the tokens.\n\t */\n\tissuer: string;\n\n\t/**\n\t * The URL of the authorization endpoint where authentication requests are sent.\n\t */\n\tauthorization_endpoint: string;\n\n\t/**\n\t * The URL of the token endpoint where tokens are exchanged.\n\t */\n\ttoken_endpoint: string;\n\n\t/**\n\t * The URL of the JSON Web Key Set (JWKS) endpoint where public keys are available.\n\t */\n\tjwks_uri: string;\n\n\t/**\n\t * The types of subjects that are supported by the authorization server.\n\t */\n\tsubject_types_supported: Array<SubjectType>;\n\n\t/**\n\t * The types of responses supported by the authorization server.\n\t */\n\tresponse_types_supported: Array<string>;\n\n\t/**\n\t * The claims supported by the authorization server.\n\t */\n\tclaims_supported: Array<string>;\n\n\t/**\n\t * The grant types supported by the authorization server.\n\t */\n\tgrant_types_supported: Array<GrantType>;\n\n\t/**\n\t * The response modes supported by the authorization server.\n\t */\n\tresponse_modes_supported: Array<ResponseMode>;\n\n\t/**\n\t * The URL of the user info endpoint where user information can be retrieved.\n\t */\n\tuserinfo_endpoint: string;\n\n\t/**\n\t * The scopes supported by the authorization server.\n\t */\n\tscopes_supported: Array<string>;\n\n\t/**\n\t * The authentication methods supported for token endpoint authentication.\n\t */\n\ttoken_endpoint_auth_methods_supported: Array<TokenEndpointAuthMethod>;\n\n\t/**\n\t * The algorithms supported for signing tokens used in the user info endpoint.\n\t */\n\tuserinfo_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms supported for signing ID tokens.\n\t */\n\tid_token_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms used to sign ID tokens in response.\n\t */\n\tid_token_signed_response_alg: Array<AlgorithmType>;\n\n\t/**\n\t * The algorithms used to sign responses from the user info endpoint.\n\t */\n\tuserinfo_signed_response_alg: Array<AlgorithmType>;\n\n\t/**\n\t * Indicates whether the request parameter is supported in requests.\n\t */\n\trequest_parameter_supported: boolean;\n\n\t/**\n\t * Indicates whether the request URI parameter is supported in requests.\n\t */\n\trequest_uri_parameter_supported: boolean;\n\n\t/**\n\t * Indicates whether request URI registration is required.\n\t */\n\trequire_request_uri_registration: boolean;\n\n\t/**\n\t * Indicates whether the claims parameter is supported.\n\t */\n\tclaims_parameter_supported: boolean;\n\n\t/**\n\t * The URL of the revocation endpoint for revoking tokens.\n\t */\n\trevocation_endpoint: string;\n\n\t/**\n\t * Indicates whether backchannel logout is supported.\n\t */\n\tbackchannel_logout_supported: boolean;\n\n\t/**\n\t * Indicates whether backchannel logout session support is provided.\n\t */\n\tbackchannel_logout_session_supported: boolean;\n\n\t/**\n\t * Indicates whether frontchannel logout is supported.\n\t */\n\tfrontchannel_logout_supported: boolean;\n\n\t/**\n\t * Indicates whether frontchannel logout session support is provided.\n\t */\n\tfrontchannel_logout_session_supported: boolean;\n\n\t/**\n\t * The URL of the endpoint where end-session requests can be sent.\n\t */\n\tend_session_endpoint: string;\n\n\t/**\n\t * The algorithms supported for signing request objects.\n\t */\n\trequest_object_signing_alg_values_supported: Array<AlgorithmType>;\n\n\t/**\n\t * The code challenge methods supported by the authorization server.\n\t */\n\tcode_challenge_methods_supported: Array<'S256'>;\n};\n\nexport type JwtClaims = {\n\t/**\n\t * The issuer of the token. This typically represents the authorization server or entity that issued the JWT.\n\t */\n\tiss?: string;\n\n\t/**\n\t * The subject of the token. This is the identifier for the entity the token represents, such as a user ID.\n\t */\n\tsub?: string;\n\n\t/**\n\t * The audience for which the token is intended. This can be a single identifier or an array of identifiers.\n\t */\n\taud?: string | Array<string>;\n\n\t/**\n\t * The expiration time of the token, expressed as a Unix timestamp (number of seconds since January 1, 1970).\n\t */\n\texp?: number;\n\n\t/**\n\t * The not-before time of the token, expressed as a Unix timestamp. The token must not be accepted before this time.\n\t */\n\tnbf?: number;\n\n\t/**\n\t * The issued-at time of the token, expressed as a Unix timestamp (number of seconds since January 1, 1970).\n\t */\n\tiat?: number;\n\n\t/**\n\t * A unique identifier for the token. This can be used to prevent token replay attacks.\n\t */\n\tjti?: string;\n};\n\nexport type IdTokenClaims = Required<Pick<JwtClaims, 'iss' | 'sub' | 'aud' | 'exp' | 'iat' | 'jti'>> & {\n\t/**\n\t * The authentication time, indicating when the user was authenticated.\n\t */\n\tauth_time?: number;\n\n\t/**\n\t * A nonce value used to associate a client session with an ID token, preventing replay attacks.\n\t */\n\tnonce?: string;\n\n\t/**\n\t * The Authentication Context Class Reference, indicating the authentication methods used.\n\t */\n\tacr?: string;\n\n\t/**\n\t * The Authentication Methods References, providing information about the authentication methods used.\n\t */\n\tamr?: unknown;\n\n\t/**\n\t * Authorized party, the client that the ID token is intended for.\n\t */\n\tazp?: string;\n\n\t/**\n\t * Session ID for the user, which can be used to manage user sessions.\n\t */\n\tsid?: string;\n\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t[key: string]: any;\n};\n\nexport type LogoutTokenClaims = Pick<JwtClaims, 'iss' | 'sub' | 'aud' | 'iat' | 'jti'> & {\n\t/**\n\t * Session ID for the user, which can be used to clear a specific session.\n\t */\n\tsid?: string;\n\n\t/**\n\t * Spec-compliant event signal for OpenID Connect Back-Channel Logout.\n\t */\n\tevents: Record<typeof BACKCHANNEL_LOGOUT_EVENT, Record<string, never>>;\n\n\t/**\n\t * MUST NOT contain a nonce claim according to the OIDC Back-Channel Logout spec.\n\t */\n\tnonce?: never;\n\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t[key: string]: any;\n};\n\nexport type SessionData = {\n\t/**\n\t * The state parameter used in the authentication request.\n\t */\n\tstate?: string | null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t */\n\tcode?: string | null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t */\n\terror?: string | null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t */\n\terror_description?: string | null;\n\n\t/**\n\t * A URI identifying a human-readable web page with information about the error (RFC 6749).\n\t */\n\terror_uri?: string | null;\n\n\t/**\n\t * Opaque value representing the session state at the authorization server (OIDC Session Management).\n\t */\n\tsession_state?: string | null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t */\n\tid_token?: string | null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t */\n\taccess_token?: string | null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t */\n\trefresh_token?: string | null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t */\n\ttoken_type?: string;\n\n\t/**\n\t * The scope of the issued token.\n\t */\n\tscope?: string | null;\n\n\t/**\n\t * The lifetime of the access token in seconds, as returned by the token endpoint.\n\t */\n\texpires_in?: number | null;\n\n\t/**\n\t * The absolute expiration time of the access token, represented as a Unix timestamp (seconds since epoch).\n\t */\n\texpires_at?: number | null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t */\n\tclaims?: IdTokenClaims | null;\n};\n\nexport type LoginSessionParams = {\n\t/**\n\t * The unique identifier of the login session.\n\t */\n\tsession_id?: string;\n\n\t/**\n\t * The short application identifier associated with the login session.\n\t */\n\tshort_app_id?: string;\n\n\t/**\n\t * BCP 47 language tag representing the language preference for the login session.\n\t */\n\tlanguage?: string;\n};\n\nexport type StateData = {\n\t/**\n\t * A unique identifier for the state.\n\t */\n\tid: string;\n\n\t/**\n\t * The timestamp when the state was created, represented as a Unix timestamp (seconds since epoch).\n\t */\n\tcreatedAt: number;\n\n\t/**\n\t * The code verifier used in the PKCE flow.\n\t */\n\tcodeVerifier: string;\n\n\t/**\n\t * The code challenge derived from the code verifier, used in the PKCE flow.\n\t */\n\tcodeChallenge: string;\n\n\t/**\n\t * A unique nonce value used to associate a client session with an ID token, preventing replay attacks.\n\t */\n\tnonce: string;\n\n\t/**\n\t * Optional metadata associated with the state, which can be used to store additional information relevant to the authentication flow.\n\t */\n\tmetadata?: Record<string, unknown>;\n};\n\nexport type LogoutParams = {\n\t/**\n\t * The URL to which the user should be redirected after logging out.\n\t */\n\tpostLogoutRedirectUri?: string;\n};\n\nexport type ExtraRequestArgs = {\n\t/**\n\t * Where to send the user after the login completes: a same-origin path or URL (e.g. the page a route guard protected).\n\t * In `redirect` mode the SDK keeps it with the login state and `handleCallback()` returns it. With `serverSessionUri` it is\n\t * forwarded to the Server SDK login route, which redirects there after its callback. The other modes ignore it.\n\t */\n\treturnTo?: string;\n\n\t/**\n\t * Specifies the type of prompt to display to the user during authentication or authorization.\n\t *\n\t * @example 'none' | 'login' | 'create'\n\t */\n\tprompt?: string | null;\n\n\t/**\n\t * Specifies the display mode for the authentication or authorization request.\n\t *\n\t * @example 'page' | 'popup'\n\t */\n\tdisplay?: string | null;\n\n\t/**\n\t * Provides a hint to the authorization server about the user's email or username.\n\t *\n\t * @example 'user@example.com'\n\t */\n\tloginHint?: string | null;\n\n\t/**\n\t * A list of values used to request specific authentication contexts or levels of assurance.\n\t * This parameter allows requesting specific authentication contexts (e.g., multi-factor authentication)\n\t * or other criteria that the authorization server should consider when authenticating the user.\n\t *\n\t * @example ['urn:mace:incommon:iap:bronze', 'urn:mace:incommon:iap:silver']\n\t */\n\tacrValues?: Array<string> | null;\n\n\t/**\n\t * A list of BCP 47 language tags specifying the preferred display language for the customer-facing UI.\n\t * We uses this as a fallback when determining the display language.\n\t * It is only applied if no higher-priority signal is present.\n\t *\n\t * @see https://docs.strivacity.com/docs/translations\n\t * @example ['en-US', 'fr-FR', 'de-DE']\n\t */\n\tuiLocales?: Array<string> | null;\n\n\t/**\n\t * A list of audience values to specify the intended recipients of the token.\n\t * This parameter allows requesting that the issued token is intended for specific audiences.\n\t *\n\t * @example ['https://api.example.com', 'https://service.example.com']\n\t */\n\taudiences?: Array<string> | null;\n};\n\nexport type EntryResponse = {\n\t/**\n\t * The session ID associated with the entry flow. This is a unique identifier for the session and can be used to track or manage the session.\n\t */\n\tsession_id: string;\n\n\t/**\n\t * The short application ID associated with the entry flow. This is a unique identifier for the application and can be used to identify the application in various contexts.\n\t */\n\tshort_app_id: string;\n\n\t/**\n\t * The language code associated with the entry flow. This indicates the preferred language for the user interface and can be used to provide localized content.\n\t */\n\tlanguage: string;\n\n\t[key: string]: string;\n};\n\nexport type SDKOptions<Storage extends SDKStorage = SDKStorage, StateStorage extends SDKStorage = SDKStorage> = {\n\t/**\n\t * A factory function that creates an instance of the SDK based on the provided initialization options.\n\t *\n\t * @param options - The initialization options for the SDK.\n\t * @returns The instance created by the factory function.\n\t */\n\tfactory?: (options: SDKInitConfig) => unknown;\n\n\t/**\n\t * The mode of operation for the SDK, which determines how authentication flows are handled.\n\t *\n\t * @default 'redirect'\n\t */\n\tmode: 'popup' | 'redirect' | 'native' | 'embedded';\n\n\t/**\n\t * The issuer of the tokens, typically the URL of the authorization server.\n\t */\n\tissuer: string;\n\n\t/**\n\t * The client ID issued by the authorization server, used to identify the application.\n\t */\n\tclientId: string;\n\n\t/**\n\t * The URI to which the user will be redirected after authentication or authorization.\n\t */\n\tredirectUri: string;\n\n\t/**\n\t * A list of scopes requested by the application, defining the access levels for the tokens.\n\t *\n\t * @default ['openid']\n\t */\n\tscopes: Array<string>;\n\n\t/**\n\t * The type of response expected from the authorization server.\n\t *\n\t * @default 'code'\n\t */\n\tresponseType: ResponseType;\n\n\t/**\n\t * The mode in which the response is returned from the authorization server.\n\t *\n\t * @default 'query'\n\t */\n\tresponseMode: ResponseMode;\n\n\t/**\n\t * The storage mechanism used to save and retrieve authentication information.\n\t *\n\t * @default Storage\n\t */\n\tstorage: Storage;\n\n\t/**\n\t * The storage mechanism used to save and retrieve state information, such as the state parameter in OAuth flows.\n\t *\n\t * @default StateStorage\n\t */\n\tstateStorage: StateStorage;\n\n\t/**\n\t * The name of the storage token used to store session data.\n\t *\n\t * @default 'sty.session'\n\t */\n\tstorageTokenName: string;\n\n\t/**\n\t * The HTTP client used for making requests to the authorization server and other endpoints.\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The logging mechanism used for logging messages and errors.\n\t */\n\tlogging?: SDKLogging;\n\n\t/**\n\t * Indicates whether the SDK should be lazily loaded, meaning that it will be initialized only when needed.\n\t *\n\t * @default false\n\t */\n\tlazyLoad: boolean;\n\n\t/**\n\t * Refreshes an expired (or about to expire, see `refreshSkew`) access token automatically.\n\t * - Client SDK: refreshes when the authentication state is checked. Ignored when `serverSessionUri` is set.\n\t * - Server SDK: refreshes when the session is read. With `false` an expired session is not refreshed.\n\t *\n\t * @default true\n\t */\n\tautoRefresh: boolean;\n\n\t/**\n\t * The amount of time (in seconds) before the access token's expiration that the SDK should attempt to refresh it.\n\t *\n\t * @default 60\n\t */\n\trefreshSkew: number;\n\n\t/**\n\t * The amount of time (in seconds) tolerated as clock difference between the device and the authorization server when validating token expiration.\n\t *\n\t * @default 60\n\t */\n\tclockSkew: number;\n\n\t/**\n\t * The URL of your backend-for-frontend (BFF) endpoint that the SDK will route login/registration/start-session requests to instead of building the authorization URL itself.\n\t * Setting this also switches the SDK into server-managed session mode: tokens are never read from or written to client-side storage, and successful authorization responses redirect the browser instead of being exchanged for tokens client-side.\n\t * If not set (or set to `false` / `null`), the SDK talks to the IDP directly and manages the session client-side.\n\t * Setting it to `true` enables server-managed session mode without routing through a BFF endpoint (the SDK builds the authorization URL itself).\n\t *\n\t * @default null (client SDK) / `${authUrlPrefix}/login` (server SDK)\n\t */\n\tserverSessionUri?: boolean | string | null;\n\n\t/**\n\t * URL prefix of the Server SDK auth routes (`/login`, `/callback`, `/refresh`, `/logout`, ...).\n\t * With server-managed sessions (`serverSessionUri`) the browser never refreshes tokens itself: `refresh()` and the route guards\n\t * (`withAuthGuard`) send the browser to `${authUrlPrefix}/refresh` with `returnTo` set to the current URL, so the server\n\t * refreshes the session, writes the rotated cookie and redirects back.\n\t *\n\t * @default '/auth'\n\t */\n\tauthUrlPrefix: string;\n\n\t/**\n\t * Discovery document metadata is cached for this amount of time (in seconds) before being refreshed from the authorization server.\n\t *\n\t * @default 3600 (1 hour)\n\t */\n\tdiscoveryDocumentCacheTTL: number;\n\n\t/**\n\t * JWKS (JSON Web Key Set) is cached for this amount of time (in seconds) before being refreshed from the authorization server.\n\t *\n\t * @default 600 (10 minutes)\n\t */\n\tjwksCacheTTL: number;\n\n\t/**\n\t * Handles the URL redirection to the specified target.\n\t * You can use this method to implement custom URL handling logic, such as opening a new window or navigating to a different page.\n\t *\n\t * @param {string | URL} url - The URL to handle.\n\t * @param {Record<string, unknown>} params - Optional parameters for redirection.\n\t * @returns - A promise that resolves when the redirection is handled.\n\t */\n\turlHandler: (url: string | URL, params?: Record<string, unknown>) => Promise<unknown>;\n\n\t/**\n\t * Handles the callback from the authorization server after a successful authentication or authorization.\n\t * You can use this method to implement custom logic for processing the response from the authorization server.\n\t *\n\t * @param {string | URL} url - The URL containing the response from the authorization server.\n\t * @param {ResponseMode} [responseMode] - Optional parameter specifying the response mode (query or fragment).\n\t * @returns - A promise that resolves when the callback is handled.\n\t */\n\tcallbackHandler: (url: string | URL, responseMode?: ResponseMode) => Promise<unknown>;\n};\n\nexport type SDKInitConfig = Partial<SDKOptions> & Required<Pick<SDKOptions, 'mode' | 'issuer' | 'clientId' | 'redirectUri'>>;\n\nexport type FlowState = {\n\t/**\n\t * Indicates whether the SDK has been initialized and is ready for use.\n\t */\n\tinitialized: boolean;\n\n\t/**\n\t * The current session data, which may include tokens and related information.\n\t */\n\tsession: SessionData | null;\n\n\t/**\n\t * The unique identifier for the current session, which may be used for tracking and correlation.\n\t */\n\tsessionId: string | null;\n\n\t/**\n\t * The short application identifier, which may be used for tracking and correlation.\n\t */\n\tshortAppId: string | null;\n\n\t/**\n\t * The language preference for the authentication flow, which may be used for localization.\n\t *\n\t * @default navigator.language\n\t */\n\tlanguage: string;\n};\n\nexport type EventFunctions = {\n\taccessTokenExpired: (params?: { accessToken?: string | null; refreshToken?: string | null }) => Promise<void> | void;\n\tinit: () => Promise<void> | void;\n\tloggedIn: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\tsessionUpdated: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\tsessionCleared: () => Promise<void> | void;\n\tloginInitiated: () => Promise<void> | void;\n\tflowInitiated: () => Promise<void> | void;\n\tlogoutInitiated: (params?: { idToken?: string | null; claims?: IdTokenClaims | null }) => Promise<void> | void;\n\tsessionLoaded: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\ttokenRefreshed: (params?: {\n\t\tidToken?: string | null;\n\t\taccessToken?: string | null;\n\t\trefreshToken?: string | null;\n\t\tclaims?: IdTokenClaims | null;\n\t}) => Promise<void> | void;\n\ttokenRefreshFailed: (params?: { refreshToken?: string | null }) => Promise<void> | void;\n\ttokenRevoked: (params?: { token?: string | null; tokenTypeHint?: 'refresh_token' | 'access_token' }) => Promise<void> | void;\n\ttokenRevokeFailed: (params?: { token?: string | null; tokenTypeHint?: 'refresh_token' | 'access_token' }) => Promise<void> | void;\n};\n\nexport type SDK<URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs, EntryReturnType = Promise<void>> = {\n\t/**\n\t * The resolved SDK configuration options in use.\n\t */\n\treadonly options: SDKOptions;\n\n\t/**\n\t * Whether the SDK has been fully initialized.\n\t */\n\treadonly initialized: boolean;\n\n\t/**\n\t * The storage adapter used to persist session and state data.\n\t */\n\treadonly storage: SDKStorage;\n\n\t/**\n\t * The HTTP client adapter used for making requests.\n\t */\n\treadonly httpClient: SDKHttpClient;\n\n\t/**\n\t * The optional logging adapter for SDK diagnostic output.\n\t */\n\treadonly logging?: SDKLogging;\n\n\t/**\n\t * The current session data, or `null` if no session is active.\n\t */\n\tsession: SessionData | null;\n\n\t/**\n\t * The short application ID associated with the current session, or `null` if not yet available.\n\t */\n\tshortAppId: string | null;\n\n\t/**\n\t * The unique identifier for the current session, or `null` if no session is active.\n\t */\n\tsessionId: string | null;\n\n\t/**\n\t * The language code used for the authentication UI.\n\t */\n\tlanguage: string;\n\n\t/**\n\t * A promise that resolves to `true` if the user is currently authenticated, `false` otherwise.\n\t */\n\treadonly isAuthenticated: Promise<boolean>;\n\n\t/**\n\t * A synchronous boolean indicating whether the user is currently authenticated.\n\t * This value may not reflect the most recent authentication state if the SDK has not been initialized or if a token refresh is pending.\n\t */\n\treadonly isAuthenticatedSync: boolean;\n\n\t/**\n\t * The current access token, or `null` if the user is not authenticated.\n\t */\n\treadonly accessToken: string | null;\n\n\t/**\n\t * Indicates whether the current access token has expired.\n\t */\n\treadonly accessTokenExpired: boolean;\n\n\t/**\n\t * The expiration time of the current access token, represented as a Unix timestamp (seconds since epoch), or `null` if no access token is present.\n\t */\n\treadonly accessTokenExpirationDate: number | null;\n\n\t/**\n\t * The current refresh token, or `null` if the user is not authenticated.\n\t */\n\treadonly refreshToken: string | null;\n\n\t/**\n\t * The current ID token, or `null` if the user is not authenticated.\n\t */\n\treadonly idToken: string | null;\n\n\t/**\n\t * The claims extracted from the current ID token, or `null` if no ID token is present.\n\t */\n\treadonly idTokenClaims: IdTokenClaims | null;\n\n\t/**\n\t * Subscribes to a specific SDK event by name.\n\t *\n\t * @template T - The name of the event to subscribe to.\n\t * @param {T} eventName - The name of the event.\n\t * @param {Function} callbackFn - The callback to invoke when the event fires.\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\n\t/**\n\t * Subscribes to all SDK events.\n\t *\n\t * @param {Function} callbackFn - The callback to invoke whenever any event fires.\n\t * @returns {{ dispose: () => void }} An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToAllEvents(callbackFn: (...params: Array<unknown>) => Promise<void> | void): { dispose: () => void };\n\n\t/**\n\t * Clears the current session data from storage.\n\t *\n\t * @returns {Promise<void>}\n\t */\n\tcleanupSession(): Promise<void>;\n\n\t/**\n\t * Replaces the current session data with the provided data.\n\t *\n\t * @param {SessionData} newData - The new session data to persist.\n\t * @returns {Promise<void>}\n\t */\n\tupdateSession(newData: SessionData): Promise<void>;\n\n\t/**\n\t * Checks whether the user is currently authenticated, optionally triggering a token refresh.\n\t *\n\t * @param {{ autoRefresh: boolean }} [params] - Options for the check.\n\t * @returns {Promise<boolean>} Resolves to `true` if authenticated, `false` otherwise.\n\t */\n\tcheckAuthentication(params?: { autoRefresh: boolean }): Promise<boolean>;\n\n\t/**\n\t * Initializes the SDK, loading metadata and restoring any persisted session.\n\t *\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the stored session cannot be loaded.\n\t */\n\tinit(): Promise<void>;\n\n\t/**\n\t * Performs a token exchange using the provided parameters.\n\t *\n\t * @param {Record<string, string>} [params] - Additional parameters for the token exchange request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the token exchange fails or if the provided parameters are invalid.\n\t */\n\ttokenExchange(params?: Record<string, string>): Promise<void>;\n\n\t/**\n\t * Handles the authentication callback by parsing the response from the given URL.\n\t *\n\t * @param {string | URL} [url] - The callback URL to process. Defaults to the current page URL if omitted.\n\t * @returns {Promise<CallbackResult>} The `returnTo` given to `login()` / `register()`, if any.\n\t * @throws {Error} Throws an error if the callback handling fails or if the URL is invalid.\n\t */\n\thandleCallback(url?: string | URL): Promise<CallbackResult>;\n\n\t/**\n\t * Refreshes the current access token using the refresh token.\n\t * With server-managed sessions, navigates the browser to the server's refresh route (`${authUrlPrefix}/refresh`) instead.\n\t *\n\t * @param {{ returnTo?: string }} [params] - Server-managed only: where the refresh route should return to (defaults to the current URL).\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the refresh process fails or if no refresh token is available.\n\t */\n\trefresh(params?: { returnTo?: string }): Promise<void>;\n\n\t/**\n\t * Revokes the current tokens.\n\t *\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the revocation process fails or if no tokens are available to revoke.\n\t */\n\trevoke(): Promise<void>;\n\n\t/**\n\t * Logs the user out and optionally redirects to a post-logout URI.\n\t *\n\t * @param {LogoutParams} [params] - Optional logout and URL handler parameters.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the logout url handling fails or if the provided parameters are invalid.\n\t */\n\tlogout(params?: LogoutParams): Promise<void>;\n\n\t/**\n\t * Initiates the login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Optional parameters for the login request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the login process fails or if the provided parameters are invalid.\n\t */\n\tlogin(params?: URLHandlerParams): Promise<void>;\n\n\t/**\n\t * Initiates the registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Optional parameters for the registration request.\n\t * @returns {Promise<void>}\n\t * @throws {Error} Throws an error if the registration process fails or if the provided parameters are invalid.\n\t */\n\tregister(params?: URLHandlerParams): Promise<void>;\n\n\t/**\n\t * Handles the entry point URL of the authentication flow, typically used for embedded or native modes.\n\t *\n\t * @param {string | URL} [url] - The entry URL to process.\n\t * @param {RedirectOptions} [params] - Optional redirect options.\n\t * @returns {EntryReturnType}\n\t * @throws {Error} Throws an error if the entry URL is invalid or if the entry process fails.\n\t */\n\tentry(url?: string | URL, params?: RedirectOptions): EntryReturnType;\n};\n\n/**\n * The result of `handleCallback()`.\n */\nexport type CallbackResult = {\n\t/** The same-origin path given to `login({ returnTo })` / `register({ returnTo })`, to navigate to after the login. */\n\treturnTo?: string;\n};\n"],"mappings":"AAIA,IAAa,EAAmB,CAAC,MAAM,EAG1B,EAAmB,CAAC,QAAS,UAAU,EAGvC,EAA8B,CAAC,MAAM,EAGrC,EAAgB,CAAC,qBAAsB,eAAe,EAGtD,EAAoB,CAAC,OAAO,EAG5B,EAAkB,CAAC,QAAQ"}
|
package/dist/types/popup.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export type PopupParams = ExtraRequestArgs & {
|
|
|
62
62
|
* If set to `true`, the SDK will verify that messages received from the popup window originate from the expected domain.
|
|
63
63
|
* This is a security measure to prevent malicious scripts from sending unauthorized messages to the application.
|
|
64
64
|
*
|
|
65
|
-
* @default
|
|
65
|
+
* @default false
|
|
66
66
|
*/
|
|
67
67
|
checkOrigin?: boolean;
|
|
68
68
|
};
|
package/dist/types/server.d.ts
CHANGED
|
@@ -24,6 +24,15 @@ export type SessionIdCookieStorageOptions = {
|
|
|
24
24
|
*/
|
|
25
25
|
uuidGenerator?: () => string;
|
|
26
26
|
};
|
|
27
|
+
/**
|
|
28
|
+
* Minimal cookie access used by the encrypted cookie helpers (`readEncryptedCookie`, `writeEncryptedCookie`, `deleteEncryptedCookie`).
|
|
29
|
+
* `get` reads the incoming request's cookies; `set` and `delete` write to the outgoing response.
|
|
30
|
+
*/
|
|
31
|
+
export type CookieJar<TOptions = ServerCookieOptions> = {
|
|
32
|
+
get(name: string): string | null | undefined | Promise<string | null | undefined>;
|
|
33
|
+
set(name: string, value: string, options: TOptions): void | Promise<void>;
|
|
34
|
+
delete(name: string, options: TOptions): void | Promise<void>;
|
|
35
|
+
};
|
|
27
36
|
export type EncryptedCookieStorageOptions = {
|
|
28
37
|
/**
|
|
29
38
|
* Default cookie options for the encrypted cookie.
|
|
@@ -92,23 +101,26 @@ export type ServerSDKOptions<TEvent = unknown, Storage extends ServerStorage<TEv
|
|
|
92
101
|
* Encrypted cookie storage secret. Required when no custom `storage` is provided.
|
|
93
102
|
*/
|
|
94
103
|
secret?: string;
|
|
95
|
-
/**
|
|
96
|
-
* URL prefix for auth routes (login, logout, callback, etc.) matched by `dispatch`.
|
|
97
|
-
*
|
|
98
|
-
* @default '/auth'
|
|
99
|
-
*/
|
|
100
|
-
authUrlPrefix: string;
|
|
101
104
|
};
|
|
102
105
|
export type ServerSDKInitConfig<TEvent = unknown, Storage extends ServerStorage<TEvent> = ServerStorage<TEvent>, StateStorage extends SDKStorage = SDKStorage> = SDKInitConfig & Partial<ServerSDKOptions<TEvent, Storage, StateStorage>>;
|
|
103
106
|
export type BaseServerSDK<TEvent = unknown> = {
|
|
104
107
|
options: ServerSDKOptions<TEvent>;
|
|
105
108
|
/**
|
|
106
|
-
* Retrieves the current session
|
|
109
|
+
* Retrieves the current session. With `autoRefresh` (the default) it refreshes the session first when the access token is
|
|
110
|
+
* expired or within `refreshSkew` of expiry and a refresh token exists, like the client SDK does. The refresh happens at most
|
|
111
|
+
* once per request event: concurrent and later calls with the same event share its result. The rotated session is queued as
|
|
112
|
+
* `Set-Cookie` on the event, so the caller (or the framework integration) must write the queued cookies to the response
|
|
113
|
+
* (`flushSetCookies`), otherwise the rotated refresh token is lost. A failed refresh resolves to `null`.
|
|
114
|
+
* With `autoRefresh: false` (the option, or `params.autoRefresh` for this call) the session is returned as stored, for example
|
|
115
|
+
* where the response cookies cannot be written.
|
|
107
116
|
*
|
|
108
117
|
* @param {TEvent} [event] - The framework-native request event.
|
|
109
|
-
* @
|
|
118
|
+
* @param {{ autoRefresh?: boolean }} [params] - Overrides the `autoRefresh` option for this call.
|
|
119
|
+
* @returns {Promise<SessionData | null>} The current (possibly refreshed) session, or `null`.
|
|
110
120
|
*/
|
|
111
|
-
getSession(event?: TEvent
|
|
121
|
+
getSession(event?: TEvent, params?: {
|
|
122
|
+
autoRefresh?: boolean;
|
|
123
|
+
}): Promise<SessionData | null>;
|
|
112
124
|
/**
|
|
113
125
|
* Updates the session data for the currently authenticated user.
|
|
114
126
|
*
|
package/dist/utils/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./base64url.cjs"),n=require("./httpClient.cjs"),r=require("./common.cjs"),i=require("./session.cjs"),a=require("../assets/oidc.cjs"),o=require("./credentials.cjs"),s=require("./crypto.cjs"),c=require("./dom.cjs"),l=require("./logging.cjs"),u=require("../assets/server.cjs");exports.BACKCHANNEL_LOGOUT_EVENT=
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./base64url.cjs"),n=require("./httpClient.cjs"),r=require("./common.cjs"),i=require("./session.cjs"),a=require("../assets/oidc.cjs"),o=require("./credentials.cjs"),s=require("./crypto.cjs"),c=require("./dom.cjs"),l=require("./logging.cjs"),u=require("./native-login.cjs"),d=require("../assets/server.cjs");exports.BACKCHANNEL_LOGOUT_EVENT=d.t,exports.ConfigurationError=e.ConfigurationError,exports.DEFAULT_COOKIE_MAX_AGE=d.n,exports.DISALLOWED_PROXY_HEADERS=d.r,exports.FallbackError=e.FallbackError,exports.InternalError=e.InternalError,exports.NetworkError=e.NetworkError,exports.OidcError=e.OidcError,exports.PopupBlockedError=e.PopupBlockedError,exports.PopupClosedError=e.PopupClosedError,exports.ProtocolError=e.ProtocolError,exports.RETURN_TO_COOKIE=d.i,exports.ServerError=e.ServerError,exports.SessionExpiredError=e.SessionExpiredError,exports.UnsupportedFlowError=e.UnsupportedFlowError,exports.assertWebAuthnCredential=o.assertWebAuthnCredential,exports.buildAuthorizationUrl=a.t,exports.buildCookieString=r.buildCookieString,exports.buildEndSessionUrl=a.n,exports.createDefaultLogging=l.createDefaultLogging,exports.createHttpClient=n.createHttpClient,exports.createNativeLoginController=u.createNativeLoginController,exports.createSession=i.createSession,exports.createState=a.b,exports.createWebAuthnCredential=o.createWebAuthnCredential,exports.decodeBase64URL=t.decodeBase64URL,exports.decodeJwt=a.r,exports.decryptString=s.decryptString,exports.defaultOptions=a.i,exports.encodeBase64URL=t.encodeBase64URL,exports.encryptString=s.encryptString,exports.exchangeCode=a.a,exports.fetchFlowEntry=a.o,exports.finalizeLoginSession=a.s,exports.flushSetCookies=d.a,exports.generateCodeChallenge=a.c,exports.generateCodeVerifier=a.l,exports.generateJwt=a.u,exports.generateRandomHex=a.d,exports.getDefaultFlowState=a.f,exports.getDiscoveryDocument=a.p,exports.getSDKOptions=a.m,exports.getServerSDKOptions=d.o,exports.injectScript=c.injectScript,exports.isSessionExpired=i.isSessionExpired,exports.loadSession=i.loadSession,exports.parseCookieHeader=d.s,exports.parseState=a.x,exports.proxyResponse=d.c,exports.pushSetCookie=d.l,exports.refreshToken=a.h,exports.revokeToken=a.g,exports.serializeCookie=d.u,exports.serializeSession=i.serializeSession,exports.serializeState=a.S,exports.submitLoginForm=a._,exports.throwHttpError=e.throwHttpError,exports.throwTokenEndpointError=e.throwTokenEndpointError,exports.timestamp=r.timestamp,exports.toClientSession=i.toClientSession,exports.toSafeRedirect=d.d,exports.unflattenObject=r.unflattenObject,exports.verifyIdToken=a.v,exports.verifyJwt=a.y;
|
package/dist/utils/index.d.ts
CHANGED
package/dist/utils/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConfigurationError as e,FallbackError as t,InternalError as n,NetworkError as r,OidcError as i,PopupBlockedError as a,PopupClosedError as o,ProtocolError as s,ServerError as c,SessionExpiredError as l,UnsupportedFlowError as u,throwHttpError as d,throwTokenEndpointError as f}from"./errors.mjs";import{decodeBase64URL as p,encodeBase64URL as m}from"./base64url.mjs";import{createHttpClient as h}from"./httpClient.mjs";import{buildCookieString as g,timestamp as _,unflattenObject as v}from"./common.mjs";import{createSession as y,isSessionExpired as b,loadSession as x,serializeSession as S}from"./session.mjs";import{S as
|
|
1
|
+
import{ConfigurationError as e,FallbackError as t,InternalError as n,NetworkError as r,OidcError as i,PopupBlockedError as a,PopupClosedError as o,ProtocolError as s,ServerError as c,SessionExpiredError as l,UnsupportedFlowError as u,throwHttpError as d,throwTokenEndpointError as f}from"./errors.mjs";import{decodeBase64URL as p,encodeBase64URL as m}from"./base64url.mjs";import{createHttpClient as h}from"./httpClient.mjs";import{buildCookieString as g,timestamp as _,unflattenObject as v}from"./common.mjs";import{createSession as y,isSessionExpired as b,loadSession as x,serializeSession as S,toClientSession as C}from"./session.mjs";import{S as w,_ as T,a as E,b as D,c as O,d as k,f as A,g as j,h as M,i as N,l as P,m as F,n as I,o as L,p as R,r as z,s as B,t as V,u as H,v as U,x as W,y as G}from"../assets/oidc.mjs";import{assertWebAuthnCredential as K,createWebAuthnCredential as q}from"./credentials.mjs";import{decryptString as J,encryptString as Y}from"./crypto.mjs";import{injectScript as X}from"./dom.mjs";import{createDefaultLogging as Z}from"./logging.mjs";import{createNativeLoginController as Q}from"./native-login.mjs";import{a as $,c as ee,d as te,i as ne,l as re,n as ie,o as ae,r as oe,s as se,t as ce,u as le}from"../assets/server.mjs";export{ce as BACKCHANNEL_LOGOUT_EVENT,e as ConfigurationError,ie as DEFAULT_COOKIE_MAX_AGE,oe as DISALLOWED_PROXY_HEADERS,t as FallbackError,n as InternalError,r as NetworkError,i as OidcError,a as PopupBlockedError,o as PopupClosedError,s as ProtocolError,ne as RETURN_TO_COOKIE,c as ServerError,l as SessionExpiredError,u as UnsupportedFlowError,K as assertWebAuthnCredential,V as buildAuthorizationUrl,g as buildCookieString,I as buildEndSessionUrl,Z as createDefaultLogging,h as createHttpClient,Q as createNativeLoginController,y as createSession,D as createState,q as createWebAuthnCredential,p as decodeBase64URL,z as decodeJwt,J as decryptString,N as defaultOptions,m as encodeBase64URL,Y as encryptString,E as exchangeCode,L as fetchFlowEntry,B as finalizeLoginSession,$ as flushSetCookies,O as generateCodeChallenge,P as generateCodeVerifier,H as generateJwt,k as generateRandomHex,A as getDefaultFlowState,R as getDiscoveryDocument,F as getSDKOptions,ae as getServerSDKOptions,X as injectScript,b as isSessionExpired,x as loadSession,se as parseCookieHeader,W as parseState,ee as proxyResponse,re as pushSetCookie,M as refreshToken,j as revokeToken,le as serializeCookie,S as serializeSession,w as serializeState,T as submitLoginForm,d as throwHttpError,f as throwTokenEndpointError,_ as timestamp,C as toClientSession,te as toSafeRedirect,v as unflattenObject,U as verifyIdToken,G as verifyJwt};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./common.cjs"),n=require("./session.cjs");function r(r,i={}){let a=new Set,o=i,s={loading:!0,forms:{},messages:{},state:{}},c=e=>{s={...s,...e};for(let e of a)e(s)},l=(t,n)=>{let i=r().logging;t instanceof e.FallbackError?(i?.error(`Fallback error occurred`,t),o.onFallback?.(t)):(i?.error(n,t),o.onError?.(t))},u=async e=>{let t=r();if(t.session&&!n.isSessionExpired(t.session))return await o.onLogin?.(t.session);let i=s.state,a={hostedUrl:e?.hostedUrl??i.hostedUrl,finalizeUrl:e?.finalizeUrl??i.finalizeUrl,screen:e?.screen??i.screen,forms:e?.forms??i.forms,layout:e?.layout??i.layout,messages:e?.messages??{},branding:e?.branding??i.branding},l=s.forms,u={...s.messages};if(a.screen!==i.screen){l={},u={};for(let e of a.forms??[])l[e.id]={},u[e.id]={}}else t.logging?.info(`Updating screen: ${a.screen}`);for(let e of Object.keys(a.messages??{}))e===`global`?o.onGlobalMessage?.(a.messages?.global):u[e]=a.messages[e]??{};c({forms:l,messages:u,state:a,loading:a.finalizeUrl?s.loading:!1})},d=async(e={})=>{try{c({loading:!0});let t=await r().startSession(e);t&&await u(t)}catch(e){l(e,`Error starting session`)}};return{getSnapshot:()=>s,subscribe:e=>(a.add(e),()=>a.delete(e)),setOptions:e=>{o=e},start:async()=>{try{await r().init()}catch(e){r().logging?.error(`Error initializing SDK`,e),o.onError?.(e),c({loading:!1});return}await d(o.params)},startSession:d,submitForm:async(e,n)=>{try{c({loading:!0});let i=await r().submitForm(e,n??t.unflattenObject(s.forms[e]??{}));i&&await u(i)}catch(e){l(e,`Error submitting form`)}},triggerFallback:t=>{let n=r().logging;if(n?.warn(t?`Triggering fallback due to: ${t}`:`Triggering fallback`),!s.state.hostedUrl){let e=Error(`No hosted URL provided`);throw n?.error(`Fallback error`,e),e}o.onFallback?.(new e.FallbackError(new URL(s.state.hostedUrl)))},triggerClose:()=>{r().logging?.debug(`Triggering close`),o.onClose?.()},setFormValue:(e,t,n)=>{c({forms:{...s.forms,[e]:{...s.forms[e],[t]:n===``?null:n}}})},setMessage:(e,t,n)=>{c({messages:{...s.messages,[e]:{...s.messages[e],[t]:n}}})}}}exports.createNativeLoginController=r;
|
|
2
|
+
//# sourceMappingURL=native-login.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"native-login.cjs","names":[],"sources":["../../src/utils/native-login.ts"],"sourcesContent":["import type {\n\tNativeFlow,\n\tNativeFlowMessage,\n\tNativeFlowState,\n\tNativeLoginController,\n\tNativeLoginControllerOptions,\n\tNativeLoginSnapshot,\n\tNativeParams,\n} from '../types';\nimport { unflattenObject } from './common';\nimport { FallbackError } from './errors';\nimport { isSessionExpired } from './session';\n\n/**\n * Creates the framework-agnostic state machine of a native login flow (`mode: 'native'`).\n *\n * The controller owns the flow state (loading flag, form values, messages, IdP state) and publishes it as immutable snapshots.\n * Framework integrations only bind `subscribe`/`getSnapshot` to their own reactivity and call `start()` when the login UI mounts.\n *\n * @param {() => NativeFlow} getSdk - Returns the native flow SDK instance. Called on every use, so the instance may be created or\n * replaced after the controller (e.g. by a provider that initializes the SDK later).\n * @param {NativeLoginControllerOptions} [options] - Callbacks and session parameters. Can be replaced later with `setOptions`.\n * @returns {NativeLoginController} The controller.\n */\nexport function createNativeLoginController(getSdk: () => NativeFlow, options: NativeLoginControllerOptions = {}): NativeLoginController {\n\tconst listeners = new Set<(snapshot: NativeLoginSnapshot) => void>();\n\tlet currentOptions = options;\n\tlet snapshot: NativeLoginSnapshot = { loading: true, forms: {}, messages: {}, state: {} };\n\n\tconst update = (patch: Partial<NativeLoginSnapshot>) => {\n\t\tsnapshot = { ...snapshot, ...patch };\n\n\t\tfor (const listener of listeners) {\n\t\t\tlistener(snapshot);\n\t\t}\n\t};\n\n\tconst handleError = (error: unknown, message: string) => {\n\t\tconst logging = getSdk().logging;\n\n\t\tif (error instanceof FallbackError) {\n\t\t\tlogging?.error('Fallback error occurred', error);\n\t\t\tvoid currentOptions.onFallback?.(error);\n\t\t} else {\n\t\t\tlogging?.error(message, error as Error);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n\t\t\tvoid currentOptions.onError?.(error as Error);\n\t\t}\n\t};\n\n\tconst handleResponse = async (nextState: Partial<NativeFlowState>) => {\n\t\tconst flow = getSdk();\n\n\t\tif (flow.session && !isSessionExpired(flow.session)) {\n\t\t\treturn await currentOptions.onLogin?.(flow.session);\n\t\t}\n\n\t\tconst state = snapshot.state;\n\t\tconst newState: NativeFlowState = {\n\t\t\thostedUrl: nextState?.hostedUrl ?? state.hostedUrl,\n\t\t\tfinalizeUrl: nextState?.finalizeUrl ?? state.finalizeUrl,\n\t\t\tscreen: nextState?.screen ?? state.screen,\n\t\t\tforms: nextState?.forms ?? state.forms,\n\t\t\tlayout: nextState?.layout ?? state.layout,\n\t\t\tmessages: nextState?.messages ?? {},\n\t\t\tbranding: nextState?.branding ?? state.branding,\n\t\t};\n\n\t\tlet forms = snapshot.forms;\n\t\tlet messages = { ...snapshot.messages };\n\n\t\tif (newState.screen !== state.screen) {\n\t\t\tforms = {};\n\t\t\tmessages = {};\n\n\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\tforms[form.id] = {};\n\t\t\t\tmessages[form.id] = {};\n\t\t\t}\n\t\t} else {\n\t\t\tflow.logging?.info(`Updating screen: ${newState.screen}`);\n\t\t}\n\n\t\tfor (const formId of Object.keys(newState.messages ?? {})) {\n\t\t\tif (formId === 'global') {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n\t\t\t\tvoid currentOptions.onGlobalMessage?.(newState.messages?.global!);\n\t\t\t} else {\n\t\t\t\tmessages[formId] = newState.messages![formId] ?? {};\n\t\t\t}\n\t\t}\n\n\t\tupdate({\n\t\t\tforms,\n\t\t\tmessages,\n\t\t\tstate: newState,\n\t\t\tloading: newState.finalizeUrl ? snapshot.loading : false,\n\t\t});\n\t};\n\n\tconst startSession = async (params: NativeParams = {}) => {\n\t\ttry {\n\t\t\tupdate({ loading: true });\n\n\t\t\tconst nextState = await getSdk().startSession(params);\n\n\t\t\tif (nextState) {\n\t\t\t\tawait handleResponse(nextState);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleError(error, 'Error starting session');\n\t\t}\n\t};\n\n\tconst submitForm = async (formId: string, customBody?: Record<string, unknown>) => {\n\t\ttry {\n\t\t\tupdate({ loading: true });\n\n\t\t\tconst nextState = await getSdk().submitForm(formId, customBody ?? unflattenObject(snapshot.forms[formId] ?? {}));\n\n\t\t\tif (nextState) {\n\t\t\t\tawait handleResponse(nextState);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleError(error, 'Error submitting form');\n\t\t}\n\t};\n\n\tconst start = async () => {\n\t\ttry {\n\t\t\tawait getSdk().init();\n\t\t} catch (error) {\n\t\t\tgetSdk().logging?.error('Error initializing SDK', error);\n\t\t\tvoid currentOptions.onError?.(error as Error);\n\t\t\tupdate({ loading: false });\n\t\t\treturn;\n\t\t}\n\n\t\tawait startSession(currentOptions.params);\n\t};\n\n\tconst triggerFallback = (message?: string) => {\n\t\tconst logging = getSdk().logging;\n\n\t\tlogging?.warn(message ? `Triggering fallback due to: ${message}` : 'Triggering fallback');\n\n\t\tif (!snapshot.state.hostedUrl) {\n\t\t\tconst error = new Error('No hosted URL provided');\n\t\t\tlogging?.error('Fallback error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tvoid currentOptions.onFallback?.(new FallbackError(new URL(snapshot.state.hostedUrl)));\n\t};\n\n\tconst triggerClose = () => {\n\t\tgetSdk().logging?.debug('Triggering close');\n\t\tvoid currentOptions.onClose?.();\n\t};\n\n\tconst setFormValue = (formId: string, widgetId: string, value: unknown) => {\n\t\tupdate({ forms: { ...snapshot.forms, [formId]: { ...snapshot.forms[formId], [widgetId]: value === '' ? null : value } } });\n\t};\n\n\tconst setMessage = (formId: string, widgetId: string, value: NativeFlowMessage) => {\n\t\tupdate({ messages: { ...snapshot.messages, [formId]: { ...snapshot.messages[formId], [widgetId]: value } } });\n\t};\n\n\treturn {\n\t\tgetSnapshot: () => snapshot,\n\t\tsubscribe: (listener) => {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => listeners.delete(listener);\n\t\t},\n\t\tsetOptions: (nextOptions) => {\n\t\t\tcurrentOptions = nextOptions;\n\t\t},\n\t\tstart,\n\t\tstartSession,\n\t\tsubmitForm,\n\t\ttriggerFallback,\n\t\ttriggerClose,\n\t\tsetFormValue,\n\t\tsetMessage,\n\t};\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { NativeFlow, NativeLoginController, NativeLoginControllerOptions } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Creates the framework-agnostic state machine of a native login flow (`mode: 'native'`).
|
|
4
|
+
*
|
|
5
|
+
* The controller owns the flow state (loading flag, form values, messages, IdP state) and publishes it as immutable snapshots.
|
|
6
|
+
* Framework integrations only bind `subscribe`/`getSnapshot` to their own reactivity and call `start()` when the login UI mounts.
|
|
7
|
+
*
|
|
8
|
+
* @param {() => NativeFlow} getSdk - Returns the native flow SDK instance. Called on every use, so the instance may be created or
|
|
9
|
+
* replaced after the controller (e.g. by a provider that initializes the SDK later).
|
|
10
|
+
* @param {NativeLoginControllerOptions} [options] - Callbacks and session parameters. Can be replaced later with `setOptions`.
|
|
11
|
+
* @returns {NativeLoginController} The controller.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createNativeLoginController(getSdk: () => NativeFlow, options?: NativeLoginControllerOptions): NativeLoginController;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{FallbackError as e}from"./errors.mjs";import{unflattenObject as t}from"./common.mjs";import{isSessionExpired as n}from"./session.mjs";function r(r,i={}){let a=new Set,o=i,s={loading:!0,forms:{},messages:{},state:{}},c=e=>{s={...s,...e};for(let e of a)e(s)},l=(t,n)=>{let i=r().logging;t instanceof e?(i?.error(`Fallback error occurred`,t),o.onFallback?.(t)):(i?.error(n,t),o.onError?.(t))},u=async e=>{let t=r();if(t.session&&!n(t.session))return await o.onLogin?.(t.session);let i=s.state,a={hostedUrl:e?.hostedUrl??i.hostedUrl,finalizeUrl:e?.finalizeUrl??i.finalizeUrl,screen:e?.screen??i.screen,forms:e?.forms??i.forms,layout:e?.layout??i.layout,messages:e?.messages??{},branding:e?.branding??i.branding},l=s.forms,u={...s.messages};if(a.screen!==i.screen){l={},u={};for(let e of a.forms??[])l[e.id]={},u[e.id]={}}else t.logging?.info(`Updating screen: ${a.screen}`);for(let e of Object.keys(a.messages??{}))e===`global`?o.onGlobalMessage?.(a.messages?.global):u[e]=a.messages[e]??{};c({forms:l,messages:u,state:a,loading:a.finalizeUrl?s.loading:!1})},d=async(e={})=>{try{c({loading:!0});let t=await r().startSession(e);t&&await u(t)}catch(e){l(e,`Error starting session`)}};return{getSnapshot:()=>s,subscribe:e=>(a.add(e),()=>a.delete(e)),setOptions:e=>{o=e},start:async()=>{try{await r().init()}catch(e){r().logging?.error(`Error initializing SDK`,e),o.onError?.(e),c({loading:!1});return}await d(o.params)},startSession:d,submitForm:async(e,n)=>{try{c({loading:!0});let i=await r().submitForm(e,n??t(s.forms[e]??{}));i&&await u(i)}catch(e){l(e,`Error submitting form`)}},triggerFallback:t=>{let n=r().logging;if(n?.warn(t?`Triggering fallback due to: ${t}`:`Triggering fallback`),!s.state.hostedUrl){let e=Error(`No hosted URL provided`);throw n?.error(`Fallback error`,e),e}o.onFallback?.(new e(new URL(s.state.hostedUrl)))},triggerClose:()=>{r().logging?.debug(`Triggering close`),o.onClose?.()},setFormValue:(e,t,n)=>{c({forms:{...s.forms,[e]:{...s.forms[e],[t]:n===``?null:n}}})},setMessage:(e,t,n)=>{c({messages:{...s.messages,[e]:{...s.messages[e],[t]:n}}})}}}export{r as createNativeLoginController};
|
|
2
|
+
//# sourceMappingURL=native-login.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"native-login.mjs","names":[],"sources":["../../src/utils/native-login.ts"],"sourcesContent":["import type {\n\tNativeFlow,\n\tNativeFlowMessage,\n\tNativeFlowState,\n\tNativeLoginController,\n\tNativeLoginControllerOptions,\n\tNativeLoginSnapshot,\n\tNativeParams,\n} from '../types';\nimport { unflattenObject } from './common';\nimport { FallbackError } from './errors';\nimport { isSessionExpired } from './session';\n\n/**\n * Creates the framework-agnostic state machine of a native login flow (`mode: 'native'`).\n *\n * The controller owns the flow state (loading flag, form values, messages, IdP state) and publishes it as immutable snapshots.\n * Framework integrations only bind `subscribe`/`getSnapshot` to their own reactivity and call `start()` when the login UI mounts.\n *\n * @param {() => NativeFlow} getSdk - Returns the native flow SDK instance. Called on every use, so the instance may be created or\n * replaced after the controller (e.g. by a provider that initializes the SDK later).\n * @param {NativeLoginControllerOptions} [options] - Callbacks and session parameters. Can be replaced later with `setOptions`.\n * @returns {NativeLoginController} The controller.\n */\nexport function createNativeLoginController(getSdk: () => NativeFlow, options: NativeLoginControllerOptions = {}): NativeLoginController {\n\tconst listeners = new Set<(snapshot: NativeLoginSnapshot) => void>();\n\tlet currentOptions = options;\n\tlet snapshot: NativeLoginSnapshot = { loading: true, forms: {}, messages: {}, state: {} };\n\n\tconst update = (patch: Partial<NativeLoginSnapshot>) => {\n\t\tsnapshot = { ...snapshot, ...patch };\n\n\t\tfor (const listener of listeners) {\n\t\t\tlistener(snapshot);\n\t\t}\n\t};\n\n\tconst handleError = (error: unknown, message: string) => {\n\t\tconst logging = getSdk().logging;\n\n\t\tif (error instanceof FallbackError) {\n\t\t\tlogging?.error('Fallback error occurred', error);\n\t\t\tvoid currentOptions.onFallback?.(error);\n\t\t} else {\n\t\t\tlogging?.error(message, error as Error);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n\t\t\tvoid currentOptions.onError?.(error as Error);\n\t\t}\n\t};\n\n\tconst handleResponse = async (nextState: Partial<NativeFlowState>) => {\n\t\tconst flow = getSdk();\n\n\t\tif (flow.session && !isSessionExpired(flow.session)) {\n\t\t\treturn await currentOptions.onLogin?.(flow.session);\n\t\t}\n\n\t\tconst state = snapshot.state;\n\t\tconst newState: NativeFlowState = {\n\t\t\thostedUrl: nextState?.hostedUrl ?? state.hostedUrl,\n\t\t\tfinalizeUrl: nextState?.finalizeUrl ?? state.finalizeUrl,\n\t\t\tscreen: nextState?.screen ?? state.screen,\n\t\t\tforms: nextState?.forms ?? state.forms,\n\t\t\tlayout: nextState?.layout ?? state.layout,\n\t\t\tmessages: nextState?.messages ?? {},\n\t\t\tbranding: nextState?.branding ?? state.branding,\n\t\t};\n\n\t\tlet forms = snapshot.forms;\n\t\tlet messages = { ...snapshot.messages };\n\n\t\tif (newState.screen !== state.screen) {\n\t\t\tforms = {};\n\t\t\tmessages = {};\n\n\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\tforms[form.id] = {};\n\t\t\t\tmessages[form.id] = {};\n\t\t\t}\n\t\t} else {\n\t\t\tflow.logging?.info(`Updating screen: ${newState.screen}`);\n\t\t}\n\n\t\tfor (const formId of Object.keys(newState.messages ?? {})) {\n\t\t\tif (formId === 'global') {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n\t\t\t\tvoid currentOptions.onGlobalMessage?.(newState.messages?.global!);\n\t\t\t} else {\n\t\t\t\tmessages[formId] = newState.messages![formId] ?? {};\n\t\t\t}\n\t\t}\n\n\t\tupdate({\n\t\t\tforms,\n\t\t\tmessages,\n\t\t\tstate: newState,\n\t\t\tloading: newState.finalizeUrl ? snapshot.loading : false,\n\t\t});\n\t};\n\n\tconst startSession = async (params: NativeParams = {}) => {\n\t\ttry {\n\t\t\tupdate({ loading: true });\n\n\t\t\tconst nextState = await getSdk().startSession(params);\n\n\t\t\tif (nextState) {\n\t\t\t\tawait handleResponse(nextState);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleError(error, 'Error starting session');\n\t\t}\n\t};\n\n\tconst submitForm = async (formId: string, customBody?: Record<string, unknown>) => {\n\t\ttry {\n\t\t\tupdate({ loading: true });\n\n\t\t\tconst nextState = await getSdk().submitForm(formId, customBody ?? unflattenObject(snapshot.forms[formId] ?? {}));\n\n\t\t\tif (nextState) {\n\t\t\t\tawait handleResponse(nextState);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\thandleError(error, 'Error submitting form');\n\t\t}\n\t};\n\n\tconst start = async () => {\n\t\ttry {\n\t\t\tawait getSdk().init();\n\t\t} catch (error) {\n\t\t\tgetSdk().logging?.error('Error initializing SDK', error);\n\t\t\tvoid currentOptions.onError?.(error as Error);\n\t\t\tupdate({ loading: false });\n\t\t\treturn;\n\t\t}\n\n\t\tawait startSession(currentOptions.params);\n\t};\n\n\tconst triggerFallback = (message?: string) => {\n\t\tconst logging = getSdk().logging;\n\n\t\tlogging?.warn(message ? `Triggering fallback due to: ${message}` : 'Triggering fallback');\n\n\t\tif (!snapshot.state.hostedUrl) {\n\t\t\tconst error = new Error('No hosted URL provided');\n\t\t\tlogging?.error('Fallback error', error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tvoid currentOptions.onFallback?.(new FallbackError(new URL(snapshot.state.hostedUrl)));\n\t};\n\n\tconst triggerClose = () => {\n\t\tgetSdk().logging?.debug('Triggering close');\n\t\tvoid currentOptions.onClose?.();\n\t};\n\n\tconst setFormValue = (formId: string, widgetId: string, value: unknown) => {\n\t\tupdate({ forms: { ...snapshot.forms, [formId]: { ...snapshot.forms[formId], [widgetId]: value === '' ? null : value } } });\n\t};\n\n\tconst setMessage = (formId: string, widgetId: string, value: NativeFlowMessage) => {\n\t\tupdate({ messages: { ...snapshot.messages, [formId]: { ...snapshot.messages[formId], [widgetId]: value } } });\n\t};\n\n\treturn {\n\t\tgetSnapshot: () => snapshot,\n\t\tsubscribe: (listener) => {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => listeners.delete(listener);\n\t\t},\n\t\tsetOptions: (nextOptions) => {\n\t\t\tcurrentOptions = nextOptions;\n\t\t},\n\t\tstart,\n\t\tstartSession,\n\t\tsubmitForm,\n\t\ttriggerFallback,\n\t\ttriggerClose,\n\t\tsetFormValue,\n\t\tsetMessage,\n\t};\n}\n"],"mappings":"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"}
|
package/dist/utils/oidc.d.ts
CHANGED
|
@@ -23,12 +23,11 @@ export declare function getDiscoveryDocument(options: SDKOptions): Promise<Disco
|
|
|
23
23
|
/**
|
|
24
24
|
* Returns with the SDK options merged with the provided options.
|
|
25
25
|
*
|
|
26
|
-
* @param {SDKInitConfig}
|
|
27
|
-
* @template InitOptions - The type of the SDK initialization configuration.
|
|
26
|
+
* @param {SDKInitConfig} initOptions - The SDK initialization configuration.
|
|
28
27
|
* @template Options - The type of the SDK options.
|
|
29
28
|
* @returns {Options} The merged SDK options.
|
|
30
29
|
*/
|
|
31
|
-
export declare function getSDKOptions<Options extends SDKOptions = SDKOptions>(
|
|
30
|
+
export declare function getSDKOptions<Options extends SDKOptions = SDKOptions>(initOptions: any): Options;
|
|
32
31
|
/**
|
|
33
32
|
* Generates a code verifier for PKCE (Proof Key for Code Exchange).
|
|
34
33
|
*
|
|
@@ -93,7 +92,7 @@ export declare function generateJwt(header: object, payload: object, privateKey?
|
|
|
93
92
|
* @param {string} [options.expectedSub] - Optional expected subject (`sub`) claim to validate against the ID token
|
|
94
93
|
* @param {string} [options.expectedNonce] - Optional expected nonce claim to validate against the ID token
|
|
95
94
|
* @returns {Promise<IdTokenClaims>} The verified, validated claims.
|
|
96
|
-
* @throws {ProtocolError} If the signature, `iss`, `aud`, `exp
|
|
95
|
+
* @throws {ProtocolError} If the signature, `iss`, `aud`, `exp` (allowing `clockSkew` seconds of tolerance), or `sub` fail validation.
|
|
97
96
|
*/
|
|
98
97
|
export declare function verifyIdToken({ idToken, options, verifySignature, expectedSub, expectedNonce, }: {
|
|
99
98
|
idToken: string;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs");function t(e,t){if(/[?&]returnTo=/.test(e))return e;let n=globalThis.location,r=t??(n?`${n.pathname}${n.search}${n.hash}`:`/`);return`${e}${e.includes(`?`)?`&`:`?`}returnTo=${encodeURIComponent(r)}`}function n(t){if(!t)return;let n=globalThis.location?.origin??`http://localhost`,r;try{r=new URL(t,n)}catch{throw new e.ProtocolError(`Invalid returnTo: ${t}`)}if(r.origin!==n)throw new e.ProtocolError(`Invalid returnTo: ${t}. Expected a path or a URL on ${n}`);return`${r.pathname}${r.search}${r.hash}`}exports.appendReturnTo=t,exports.toSameOriginPath=n;
|
|
2
|
+
//# sourceMappingURL=path.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"path.cjs","names":[],"sources":["../../src/utils/path.ts"],"sourcesContent":["import { ProtocolError } from './errors';\n\n/**\n * Adds a `returnTo` query parameter to a URI (for example a login page or the Server SDK refresh route), unless it already has one.\n *\n * @param {string} uri - The URI to extend.\n * @param {string} [returnTo] - Where to return to. Defaults to the current path, query and hash.\n * @returns {string} The URI with `returnTo`.\n */\nexport function appendReturnTo(uri: string, returnTo?: string): string {\n\tif (/[?&]returnTo=/.test(uri)) {\n\t\treturn uri;\n\t}\n\n\tconst location = globalThis.location;\n\tconst value = returnTo ?? (location ? `${location.pathname}${location.search}${location.hash}` : '/');\n\n\treturn `${uri}${uri.includes('?') ? '&' : '?'}returnTo=${encodeURIComponent(value)}`;\n}\n\n/**\n * Validates a `returnTo` value and turns it into a same-origin path (path, query and hash).\n *\n * @param {string | undefined} returnTo - A path, or an absolute URL on the current origin.\n * @returns {string | undefined} The path, or `undefined` when no value was given.\n * @throws {ProtocolError} If the value points to another origin.\n */\nexport function toSameOriginPath(returnTo: string | undefined): string | undefined {\n\tif (!returnTo) {\n\t\treturn undefined;\n\t}\n\n\tconst origin = globalThis.location?.origin ?? 'http://localhost';\n\tlet url: URL;\n\n\ttry {\n\t\turl = new URL(returnTo, origin);\n\t} catch {\n\t\tthrow new ProtocolError(`Invalid returnTo: ${returnTo}`);\n\t}\n\n\tif (url.origin !== origin) {\n\t\tthrow new ProtocolError(`Invalid returnTo: ${returnTo}. Expected a path or a URL on ${origin}`);\n\t}\n\n\treturn `${url.pathname}${url.search}${url.hash}`;\n}\n"],"mappings":"mGASA,SAAgB,EAAe,EAAa,EAA2B,CACtE,GAAI,gBAAgB,KAAK,CAAG,EAC3B,OAAO,EAGR,IAAM,EAAW,WAAW,SACtB,EAAQ,IAAa,EAAW,GAAG,EAAS,WAAW,EAAS,SAAS,EAAS,OAAS,KAEjG,MAAO,GAAG,IAAM,EAAI,SAAS,GAAG,EAAI,IAAM,IAAI,WAAW,mBAAmB,CAAK,GAClF,CASA,SAAgB,EAAiB,EAAkD,CAClF,GAAI,CAAC,EACJ,OAGD,IAAM,EAAS,WAAW,UAAU,QAAU,mBAC1C,EAEJ,GAAI,CACH,EAAM,IAAI,IAAI,EAAU,CAAM,CAC/B,MAAQ,CACP,MAAM,IAAI,EAAA,cAAc,qBAAqB,GAAU,CACxD,CAEA,GAAI,EAAI,SAAW,EAClB,MAAM,IAAI,EAAA,cAAc,qBAAqB,EAAS,gCAAgC,GAAQ,EAG/F,MAAO,GAAG,EAAI,WAAW,EAAI,SAAS,EAAI,MAC3C"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds a `returnTo` query parameter to a URI (for example a login page or the Server SDK refresh route), unless it already has one.
|
|
3
|
+
*
|
|
4
|
+
* @param {string} uri - The URI to extend.
|
|
5
|
+
* @param {string} [returnTo] - Where to return to. Defaults to the current path, query and hash.
|
|
6
|
+
* @returns {string} The URI with `returnTo`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function appendReturnTo(uri: string, returnTo?: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Validates a `returnTo` value and turns it into a same-origin path (path, query and hash).
|
|
11
|
+
*
|
|
12
|
+
* @param {string | undefined} returnTo - A path, or an absolute URL on the current origin.
|
|
13
|
+
* @returns {string | undefined} The path, or `undefined` when no value was given.
|
|
14
|
+
* @throws {ProtocolError} If the value points to another origin.
|
|
15
|
+
*/
|
|
16
|
+
export declare function toSameOriginPath(returnTo: string | undefined): string | undefined;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ProtocolError as e}from"./errors.mjs";function t(e,t){if(/[?&]returnTo=/.test(e))return e;let n=globalThis.location,r=t??(n?`${n.pathname}${n.search}${n.hash}`:`/`);return`${e}${e.includes(`?`)?`&`:`?`}returnTo=${encodeURIComponent(r)}`}function n(t){if(!t)return;let n=globalThis.location?.origin??`http://localhost`,r;try{r=new URL(t,n)}catch{throw new e(`Invalid returnTo: ${t}`)}if(r.origin!==n)throw new e(`Invalid returnTo: ${t}. Expected a path or a URL on ${n}`);return`${r.pathname}${r.search}${r.hash}`}export{t as appendReturnTo,n as toSameOriginPath};
|
|
2
|
+
//# sourceMappingURL=path.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"path.mjs","names":[],"sources":["../../src/utils/path.ts"],"sourcesContent":["import { ProtocolError } from './errors';\n\n/**\n * Adds a `returnTo` query parameter to a URI (for example a login page or the Server SDK refresh route), unless it already has one.\n *\n * @param {string} uri - The URI to extend.\n * @param {string} [returnTo] - Where to return to. Defaults to the current path, query and hash.\n * @returns {string} The URI with `returnTo`.\n */\nexport function appendReturnTo(uri: string, returnTo?: string): string {\n\tif (/[?&]returnTo=/.test(uri)) {\n\t\treturn uri;\n\t}\n\n\tconst location = globalThis.location;\n\tconst value = returnTo ?? (location ? `${location.pathname}${location.search}${location.hash}` : '/');\n\n\treturn `${uri}${uri.includes('?') ? '&' : '?'}returnTo=${encodeURIComponent(value)}`;\n}\n\n/**\n * Validates a `returnTo` value and turns it into a same-origin path (path, query and hash).\n *\n * @param {string | undefined} returnTo - A path, or an absolute URL on the current origin.\n * @returns {string | undefined} The path, or `undefined` when no value was given.\n * @throws {ProtocolError} If the value points to another origin.\n */\nexport function toSameOriginPath(returnTo: string | undefined): string | undefined {\n\tif (!returnTo) {\n\t\treturn undefined;\n\t}\n\n\tconst origin = globalThis.location?.origin ?? 'http://localhost';\n\tlet url: URL;\n\n\ttry {\n\t\turl = new URL(returnTo, origin);\n\t} catch {\n\t\tthrow new ProtocolError(`Invalid returnTo: ${returnTo}`);\n\t}\n\n\tif (url.origin !== origin) {\n\t\tthrow new ProtocolError(`Invalid returnTo: ${returnTo}. Expected a path or a URL on ${origin}`);\n\t}\n\n\treturn `${url.pathname}${url.search}${url.hash}`;\n}\n"],"mappings":"6CASA,SAAgB,EAAe,EAAa,EAA2B,CACtE,GAAI,gBAAgB,KAAK,CAAG,EAC3B,OAAO,EAGR,IAAM,EAAW,WAAW,SACtB,EAAQ,IAAa,EAAW,GAAG,EAAS,WAAW,EAAS,SAAS,EAAS,OAAS,KAEjG,MAAO,GAAG,IAAM,EAAI,SAAS,GAAG,EAAI,IAAM,IAAI,WAAW,mBAAmB,CAAK,GAClF,CASA,SAAgB,EAAiB,EAAkD,CAClF,GAAI,CAAC,EACJ,OAGD,IAAM,EAAS,WAAW,UAAU,QAAU,mBAC1C,EAEJ,GAAI,CACH,EAAM,IAAI,IAAI,EAAU,CAAM,CAC/B,MAAQ,CACP,MAAM,IAAI,EAAc,qBAAqB,GAAU,CACxD,CAEA,GAAI,EAAI,SAAW,EAClB,MAAM,IAAI,EAAc,qBAAqB,EAAS,gCAAgC,GAAQ,EAG/F,MAAO,GAAG,EAAI,WAAW,EAAI,SAAS,EAAI,MAC3C"}
|
package/dist/utils/server.d.ts
CHANGED
|
@@ -18,12 +18,13 @@ export declare const DEFAULT_COOKIE_MAX_AGE: number;
|
|
|
18
18
|
/**
|
|
19
19
|
* Returns with the server SDK options merged with the provided options.
|
|
20
20
|
*
|
|
21
|
-
* @param {SDKInitConfig}
|
|
22
|
-
* @template
|
|
23
|
-
* @template
|
|
21
|
+
* @param {SDKInitConfig} initOptions - The SDK initialization configuration.
|
|
22
|
+
* @template TEvent - The type of the server request event.
|
|
23
|
+
* @template Storage - The type of the server storage.
|
|
24
|
+
* @template StateStorage - The type of the state storage.
|
|
24
25
|
* @returns {Options} The merged SDK options.
|
|
25
26
|
*/
|
|
26
|
-
export declare function getServerSDKOptions<TEvent = unknown, Storage extends ServerStorage<TEvent> = ServerStorage<TEvent>, StateStorage extends SDKStorage = SDKStorage>(adapter: ServerAdapter<TEvent>,
|
|
27
|
+
export declare function getServerSDKOptions<TEvent = unknown, Storage extends ServerStorage<TEvent> = ServerStorage<TEvent>, StateStorage extends SDKStorage = SDKStorage>(adapter: ServerAdapter<TEvent>, initOptions: any): ServerSDKOptions<TEvent, Storage, StateStorage>;
|
|
27
28
|
/**
|
|
28
29
|
* Parses a `Cookie` request header into a plain name/value map.
|
|
29
30
|
*
|
package/dist/utils/session.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./common.cjs");function n(n={}){let r={state:null,code:null,error:null,error_description:null,id_token:null,access_token:null,refresh_token:null,token_type:`bearer`,scope:null,expires_in:null,expires_at:null,claims:null};if(typeof n.expires_in==`number`&&!isNaN(n.expires_in)&&(r.expires_at=Math.floor(n.expires_in)+t.timestamp()),Object.assign(r,n),r.access_token&&r.token_type?.toLowerCase()!==`bearer`)throw new e.ProtocolError(`Unsupported token_type: ${r.token_type}`);return r}function r(e){if(!e)return null;let t=n();try{Object.assign(t,JSON.parse(e))}catch{t=null}return t}function i(e){return JSON.stringify(e)}function a(e){return!e?.access_token||!e.expires_at||e.expires_at<=t.timestamp()}exports.createSession=n,exports.isSessionExpired=a,exports.loadSession=r,exports.serializeSession=i;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./common.cjs");function n(n={}){let r={state:null,code:null,error:null,error_description:null,id_token:null,access_token:null,refresh_token:null,token_type:`bearer`,scope:null,expires_in:null,expires_at:null,claims:null};if(typeof n.expires_in==`number`&&!isNaN(n.expires_in)&&(r.expires_at=Math.floor(n.expires_in)+t.timestamp()),Object.assign(r,n),r.access_token&&r.token_type?.toLowerCase()!==`bearer`)throw new e.ProtocolError(`Unsupported token_type: ${r.token_type}`);return r}function r(e){if(!e)return null;let t=n();try{Object.assign(t,JSON.parse(e))}catch{t=null}return t}function i(e){return JSON.stringify(e)}function a(e,n=0){let r=typeof e?.expires_in==`number`&&e.expires_in>0?e.expires_in:null,i=r===null?n:Math.min(n,Math.floor(r/2));return!e?.access_token||!e.expires_at||e.expires_at<=t.timestamp()+i}function o(e){if(!e)return null;let t={...e};return delete t.refresh_token,delete t.id_token,t}exports.createSession=n,exports.isSessionExpired=a,exports.loadSession=r,exports.serializeSession=i,exports.toClientSession=o;
|
|
2
2
|
//# sourceMappingURL=session.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","names":[],"sources":["../../src/utils/session.ts"],"sourcesContent":["import type { SessionData } from '../types/oidc';\nimport { ProtocolError } from './errors';\nimport { timestamp } from './common';\n\n/**\n * Creates a new session object with default values and merges it with provided parameters.\n *\n * @param {Record<string, unknown>} params - Optional parameters to merge into the new session object.\n * @returns {SessionData} The newly created session object.\n */\nexport function createSession(params: Record<string, unknown> = {}): SessionData {\n\tconst session: SessionData = {\n\t\tstate: null,\n\t\tcode: null,\n\t\terror: null,\n\t\terror_description: null,\n\t\tid_token: null,\n\t\taccess_token: null,\n\t\trefresh_token: null,\n\t\ttoken_type: 'bearer',\n\t\tscope: null,\n\t\texpires_in: null,\n\t\texpires_at: null,\n\t\tclaims: null,\n\t};\n\n\tif (typeof params.expires_in === 'number' && !isNaN(params.expires_in)) {\n\t\tsession.expires_at = Math.floor(params.expires_in) + timestamp();\n\t}\n\n\tObject.assign(session, params);\n\n\tif (session.access_token && session.token_type?.toLowerCase() !== 'bearer') {\n\t\tthrow new ProtocolError(`Unsupported token_type: ${session.token_type}`);\n\t}\n\n\treturn session;\n}\n\n/**\n * Loads a serialized session from a JSON string.\n *\n * @param {string | null} serialized - The serialized session string to parse.\n * @returns {SessionData | null} The parsed session object, or null if parsing fails.\n */\nexport function loadSession(serialized: string | null): SessionData | null {\n\tif (!serialized) {\n\t\treturn null;\n\t}\n\n\tlet session: SessionData | null = createSession();\n\n\ttry {\n\t\tObject.assign(session, JSON.parse(serialized));\n\t} catch {\n\t\tsession = null;\n\t}\n\n\treturn session;\n}\n\n/**\n * Serializes a session object into a JSON string.\n *\n * @param {SessionData} session - The session object to serialize.\n * @returns {string} The serialized session string.\n */\nexport function serializeSession(session: SessionData): string {\n\treturn JSON.stringify(session);\n}\n\n/**\n * Checks if a session is expired based on its access token and expiration timestamp.\n *\n * @param {Partial<SessionData> | null} session - The session object to check for expiration.\n * @returns {boolean} True if the session is expired or invalid, false otherwise.\n */\nexport function isSessionExpired(session?: Partial<SessionData> | null): boolean {\n\treturn !session?.access_token || !session.expires_at || session.expires_at <= timestamp();\n}\n"],"mappings":"6HAUA,SAAgB,EAAc,EAAkC,CAAC,EAAgB,CAChF,IAAM,EAAuB,CAC5B,MAAO,KACP,KAAM,KACN,MAAO,KACP,kBAAmB,KACnB,SAAU,KACV,aAAc,KACd,cAAe,KACf,WAAY,SACZ,MAAO,KACP,WAAY,KACZ,WAAY,KACZ,OAAQ,IACT,EAQA,GANI,OAAO,EAAO,YAAe,UAAY,CAAC,MAAM,EAAO,UAAU,IACpE,EAAQ,WAAa,KAAK,MAAM,EAAO,UAAU,EAAI,EAAA,UAAU,GAGhE,OAAO,OAAO,EAAS,CAAM,EAEzB,EAAQ,cAAgB,EAAQ,YAAY,YAAY,IAAM,SACjE,MAAM,IAAI,EAAA,cAAc,2BAA2B,EAAQ,YAAY,EAGxE,OAAO,CACR,CAQA,SAAgB,EAAY,EAA+C,CAC1E,GAAI,CAAC,EACJ,OAAO,KAGR,IAAI,EAA8B,EAAc,EAEhD,GAAI,CACH,OAAO,OAAO,EAAS,KAAK,MAAM,CAAU,CAAC,CAC9C,MAAQ,CACP,EAAU,IACX,CAEA,OAAO,CACR,CAQA,SAAgB,EAAiB,EAA8B,CAC9D,OAAO,KAAK,UAAU,CAAO,CAC9B,
|
|
1
|
+
{"version":3,"file":"session.cjs","names":[],"sources":["../../src/utils/session.ts"],"sourcesContent":["import type { SessionData } from '../types/oidc';\nimport { ProtocolError } from './errors';\nimport { timestamp } from './common';\n\n/**\n * Creates a new session object with default values and merges it with provided parameters.\n *\n * @param {Record<string, unknown>} params - Optional parameters to merge into the new session object.\n * @returns {SessionData} The newly created session object.\n */\nexport function createSession(params: Record<string, unknown> = {}): SessionData {\n\tconst session: SessionData = {\n\t\tstate: null,\n\t\tcode: null,\n\t\terror: null,\n\t\terror_description: null,\n\t\tid_token: null,\n\t\taccess_token: null,\n\t\trefresh_token: null,\n\t\ttoken_type: 'bearer',\n\t\tscope: null,\n\t\texpires_in: null,\n\t\texpires_at: null,\n\t\tclaims: null,\n\t};\n\n\tif (typeof params.expires_in === 'number' && !isNaN(params.expires_in)) {\n\t\tsession.expires_at = Math.floor(params.expires_in) + timestamp();\n\t}\n\n\tObject.assign(session, params);\n\n\tif (session.access_token && session.token_type?.toLowerCase() !== 'bearer') {\n\t\tthrow new ProtocolError(`Unsupported token_type: ${session.token_type}`);\n\t}\n\n\treturn session;\n}\n\n/**\n * Loads a serialized session from a JSON string.\n *\n * @param {string | null} serialized - The serialized session string to parse.\n * @returns {SessionData | null} The parsed session object, or null if parsing fails.\n */\nexport function loadSession(serialized: string | null): SessionData | null {\n\tif (!serialized) {\n\t\treturn null;\n\t}\n\n\tlet session: SessionData | null = createSession();\n\n\ttry {\n\t\tObject.assign(session, JSON.parse(serialized));\n\t} catch {\n\t\tsession = null;\n\t}\n\n\treturn session;\n}\n\n/**\n * Serializes a session object into a JSON string.\n *\n * @param {SessionData} session - The session object to serialize.\n * @returns {string} The serialized session string.\n */\nexport function serializeSession(session: SessionData): string {\n\treturn JSON.stringify(session);\n}\n\n/**\n * Checks if a session is expired based on its access token and expiration timestamp.\n *\n * @param {Partial<SessionData> | null} session - The session object to check for expiration.\n * @param {number} [skew=0] - The number of seconds before the actual expiration to already treat the session as expired. Capped at half of the token lifetime (`expires_in`), so a short-lived token is not treated as expired the moment it is issued.\n * @returns {boolean} True if the session is expired or invalid, false otherwise.\n */\nexport function isSessionExpired(session?: Partial<SessionData> | null, skew = 0): boolean {\n\tconst lifetime = typeof session?.expires_in === 'number' && session.expires_in > 0 ? session.expires_in : null;\n\tconst effectiveSkew = lifetime === null ? skew : Math.min(skew, Math.floor(lifetime / 2));\n\n\treturn !session?.access_token || !session.expires_at || session.expires_at <= timestamp() + effectiveSkew;\n}\n\n/**\n * Returns a copy of a server-managed session that is safe to hand to the browser (e.g. serialized into SSR page data):\n * without the refresh token and the ID token, which stay server-side in the session cookie.\n *\n * @param {SessionData | null | undefined} session - The full server-side session.\n * @returns {SessionData | null} The session without `refresh_token` and `id_token`, or `null`.\n */\nexport function toClientSession(session?: SessionData | null): SessionData | null {\n\tif (!session) {\n\t\treturn null;\n\t}\n\n\tconst clientSession = { ...session };\n\n\tdelete clientSession.refresh_token;\n\tdelete clientSession.id_token;\n\n\treturn clientSession;\n}\n"],"mappings":"6HAUA,SAAgB,EAAc,EAAkC,CAAC,EAAgB,CAChF,IAAM,EAAuB,CAC5B,MAAO,KACP,KAAM,KACN,MAAO,KACP,kBAAmB,KACnB,SAAU,KACV,aAAc,KACd,cAAe,KACf,WAAY,SACZ,MAAO,KACP,WAAY,KACZ,WAAY,KACZ,OAAQ,IACT,EAQA,GANI,OAAO,EAAO,YAAe,UAAY,CAAC,MAAM,EAAO,UAAU,IACpE,EAAQ,WAAa,KAAK,MAAM,EAAO,UAAU,EAAI,EAAA,UAAU,GAGhE,OAAO,OAAO,EAAS,CAAM,EAEzB,EAAQ,cAAgB,EAAQ,YAAY,YAAY,IAAM,SACjE,MAAM,IAAI,EAAA,cAAc,2BAA2B,EAAQ,YAAY,EAGxE,OAAO,CACR,CAQA,SAAgB,EAAY,EAA+C,CAC1E,GAAI,CAAC,EACJ,OAAO,KAGR,IAAI,EAA8B,EAAc,EAEhD,GAAI,CACH,OAAO,OAAO,EAAS,KAAK,MAAM,CAAU,CAAC,CAC9C,MAAQ,CACP,EAAU,IACX,CAEA,OAAO,CACR,CAQA,SAAgB,EAAiB,EAA8B,CAC9D,OAAO,KAAK,UAAU,CAAO,CAC9B,CASA,SAAgB,EAAiB,EAAuC,EAAO,EAAY,CAC1F,IAAM,EAAW,OAAO,GAAS,YAAe,UAAY,EAAQ,WAAa,EAAI,EAAQ,WAAa,KACpG,EAAgB,IAAa,KAAO,EAAO,KAAK,IAAI,EAAM,KAAK,MAAM,EAAW,CAAC,CAAC,EAExF,MAAO,CAAC,GAAS,cAAgB,CAAC,EAAQ,YAAc,EAAQ,YAAc,EAAA,UAAU,EAAI,CAC7F,CASA,SAAgB,EAAgB,EAAkD,CACjF,GAAI,CAAC,EACJ,OAAO,KAGR,IAAM,EAAgB,CAAE,GAAG,CAAQ,EAKnC,OAHA,OAAO,EAAc,cACrB,OAAO,EAAc,SAEd,CACR"}
|
package/dist/utils/session.d.ts
CHANGED
|
@@ -24,6 +24,15 @@ export declare function serializeSession(session: SessionData): string;
|
|
|
24
24
|
* Checks if a session is expired based on its access token and expiration timestamp.
|
|
25
25
|
*
|
|
26
26
|
* @param {Partial<SessionData> | null} session - The session object to check for expiration.
|
|
27
|
+
* @param {number} [skew=0] - The number of seconds before the actual expiration to already treat the session as expired. Capped at half of the token lifetime (`expires_in`), so a short-lived token is not treated as expired the moment it is issued.
|
|
27
28
|
* @returns {boolean} True if the session is expired or invalid, false otherwise.
|
|
28
29
|
*/
|
|
29
|
-
export declare function isSessionExpired(session?: Partial<SessionData> | null): boolean;
|
|
30
|
+
export declare function isSessionExpired(session?: Partial<SessionData> | null, skew?: number): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Returns a copy of a server-managed session that is safe to hand to the browser (e.g. serialized into SSR page data):
|
|
33
|
+
* without the refresh token and the ID token, which stay server-side in the session cookie.
|
|
34
|
+
*
|
|
35
|
+
* @param {SessionData | null | undefined} session - The full server-side session.
|
|
36
|
+
* @returns {SessionData | null} The session without `refresh_token` and `id_token`, or `null`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function toClientSession(session?: SessionData | null): SessionData | null;
|
package/dist/utils/session.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ProtocolError as e}from"./errors.mjs";import{timestamp as t}from"./common.mjs";function n(n={}){let r={state:null,code:null,error:null,error_description:null,id_token:null,access_token:null,refresh_token:null,token_type:`bearer`,scope:null,expires_in:null,expires_at:null,claims:null};if(typeof n.expires_in==`number`&&!isNaN(n.expires_in)&&(r.expires_at=Math.floor(n.expires_in)+t()),Object.assign(r,n),r.access_token&&r.token_type?.toLowerCase()!==`bearer`)throw new e(`Unsupported token_type: ${r.token_type}`);return r}function r(e){if(!e)return null;let t=n();try{Object.assign(t,JSON.parse(e))}catch{t=null}return t}function i(e){return JSON.stringify(e)}function a(e){return!e?.access_token||!e.expires_at||e.expires_at<=t()}export{n as createSession,a as isSessionExpired,r as loadSession,i as serializeSession};
|
|
1
|
+
import{ProtocolError as e}from"./errors.mjs";import{timestamp as t}from"./common.mjs";function n(n={}){let r={state:null,code:null,error:null,error_description:null,id_token:null,access_token:null,refresh_token:null,token_type:`bearer`,scope:null,expires_in:null,expires_at:null,claims:null};if(typeof n.expires_in==`number`&&!isNaN(n.expires_in)&&(r.expires_at=Math.floor(n.expires_in)+t()),Object.assign(r,n),r.access_token&&r.token_type?.toLowerCase()!==`bearer`)throw new e(`Unsupported token_type: ${r.token_type}`);return r}function r(e){if(!e)return null;let t=n();try{Object.assign(t,JSON.parse(e))}catch{t=null}return t}function i(e){return JSON.stringify(e)}function a(e,n=0){let r=typeof e?.expires_in==`number`&&e.expires_in>0?e.expires_in:null,i=r===null?n:Math.min(n,Math.floor(r/2));return!e?.access_token||!e.expires_at||e.expires_at<=t()+i}function o(e){if(!e)return null;let t={...e};return delete t.refresh_token,delete t.id_token,t}export{n as createSession,a as isSessionExpired,r as loadSession,i as serializeSession,o as toClientSession};
|
|
2
2
|
//# sourceMappingURL=session.mjs.map
|