@thunderid/nextjs 1.11.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ThunderIDNextClient.d.ts +8 -1
- package/dist/ThunderIDNextClient.d.ts.map +1 -1
- package/dist/ThunderIDNextClient.js +10 -0
- package/dist/ThunderIDNextClient.js.map +1 -1
- package/dist/cjs/ThunderIDNextClient.cjs +10 -0
- package/dist/cjs/ThunderIDNextClient.cjs.map +1 -1
- package/dist/cjs/client/components/account/UserProfile/UserProfile.cjs +11 -1
- package/dist/cjs/client/components/account/UserProfile/UserProfile.cjs.map +1 -1
- package/dist/cjs/client/components/account/VerifyAttribute/VerifyAttribute.cjs +80 -0
- package/dist/cjs/client/components/account/VerifyAttribute/VerifyAttribute.cjs.map +1 -0
- package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs +12 -0
- package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs.map +1 -1
- package/dist/cjs/client/index.cjs +1 -0
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/server/actions/auth/executeSelfFlowAction.cjs +47 -0
- package/dist/cjs/server/actions/auth/executeSelfFlowAction.cjs.map +1 -0
- package/dist/client/components/account/UserProfile/UserProfile.d.ts +7 -1
- package/dist/client/components/account/UserProfile/UserProfile.d.ts.map +1 -1
- package/dist/client/components/account/UserProfile/UserProfile.js +12 -2
- package/dist/client/components/account/UserProfile/UserProfile.js.map +1 -1
- package/dist/client/components/account/VerifyAttribute/VerifyAttribute.d.ts +41 -0
- package/dist/client/components/account/VerifyAttribute/VerifyAttribute.d.ts.map +1 -0
- package/dist/client/components/account/VerifyAttribute/VerifyAttribute.js +75 -0
- package/dist/client/components/account/VerifyAttribute/VerifyAttribute.js.map +1 -0
- package/dist/client/contexts/ThunderID/ThunderIDProvider.d.ts.map +1 -1
- package/dist/client/contexts/ThunderID/ThunderIDProvider.js +12 -0
- package/dist/client/contexts/ThunderID/ThunderIDProvider.js.map +1 -1
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -0
- package/dist/index.js +2 -1
- package/dist/server/actions/auth/executeSelfFlowAction.d.ts +20 -0
- package/dist/server/actions/auth/executeSelfFlowAction.d.ts.map +1 -0
- package/dist/server/actions/auth/executeSelfFlowAction.js +45 -0
- package/dist/server/actions/auth/executeSelfFlowAction.js.map +1 -0
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ThunderIDNodeClient, AttributeSchema, ExtendedAuthorizeRequestUrlParams, IdToken, SignInOptions, SignUpOptions, Storage, TokenExchangeRequestConfig, TokenResponse, User, ManagedFlowListResponse, ManagedUserListResponse, ManagedUserTypeListResponse, UserProfile } from '@thunderid/node';
|
|
1
|
+
import { ThunderIDNodeClient, AttributeSchema, EmbeddedSelfFlowRequest, EmbeddedSelfFlowResponse, ExtendedAuthorizeRequestUrlParams, IdToken, SignInOptions, SignUpOptions, Storage, TokenExchangeRequestConfig, TokenResponse, User, ManagedFlowListResponse, ManagedUserListResponse, ManagedUserTypeListResponse, UserProfile } from '@thunderid/node';
|
|
2
2
|
import { ThunderIDNextConfig } from './models/config';
|
|
3
3
|
declare class ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextConfig> extends ThunderIDNodeClient<T> {
|
|
4
4
|
isInitialized: boolean;
|
|
@@ -26,6 +26,13 @@ declare class ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextC
|
|
|
26
26
|
* boundary back to the client.
|
|
27
27
|
*/
|
|
28
28
|
updateUserCredentials(payload: Record<string, string>, userId?: string): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Executes one step of a `SELF` flow, such as self attribute verification, for the session
|
|
31
|
+
* identified by `userId`.
|
|
32
|
+
*
|
|
33
|
+
* Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.
|
|
34
|
+
*/
|
|
35
|
+
executeEmbeddedSelfFlow(payload: EmbeddedSelfFlowRequest, userId?: string): Promise<EmbeddedSelfFlowResponse>;
|
|
29
36
|
/**
|
|
30
37
|
* Retrieves one page of the user directory for the session identified by `userId`.
|
|
31
38
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThunderIDNextClient.d.ts","sourceRoot":"","sources":["../src/ThunderIDNextClient.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,mBAAmB,EAEnB,eAAe,
|
|
1
|
+
{"version":3,"file":"ThunderIDNextClient.d.ts","sourceRoot":"","sources":["../src/ThunderIDNextClient.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,mBAAmB,EAEnB,eAAe,EAEf,uBAAuB,EACvB,wBAAwB,EAExB,iCAAiC,EACjC,OAAO,EACP,aAAa,EACb,aAAa,EACb,OAAO,EACP,0BAA0B,EAC1B,aAAa,EACb,IAAI,EACJ,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,WAAW,EASZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAC,mBAAmB,EAAC,MAAM,iBAAiB,CAAC;AAKpD,cAAM,mBAAmB,CAAC,CAAC,SAAS,mBAAmB,GAAG,mBAAmB,CAAE,SAAQ,mBAAmB,CAAC,CAAC,CAAC;IACpG,aAAa,UAAS;;YAMf,iBAAiB;IAehB,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IA0C1D,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAclD,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBvC,cAAc,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IA2B9D,aAAa,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC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flow, such as self attribute verification, for the session
|
|
138
|
+
* identified by `userId`.
|
|
139
|
+
*
|
|
140
|
+
* Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.
|
|
141
|
+
*/
|
|
142
|
+
async executeEmbeddedSelfFlow(payload, userId) {
|
|
143
|
+
await this.ensureInitialized();
|
|
144
|
+
return super.executeEmbeddedSelfFlow(payload, userId);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
137
147
|
* Retrieves one page of the user directory for the session identified by `userId`.
|
|
138
148
|
*
|
|
139
149
|
* Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThunderIDNextClient.js","names":["decorateConfigWithNextEnv","origin: string","getClientOrigin","initialized: boolean","resolvedSessionId: string","getSessionId","configData: AuthClientConfig<T>","baseUrl: string | undefined","profile: User","token: string | undefined","arg1: any","arg2: any","arg3: any","arg4: any","configData: ThunderIDNextConfig","afterSignOutUrl: string","message: string"],"sources":["../src/ThunderIDNextClient.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n ThunderIDNodeClient,\n ThunderIDRuntimeError,\n AttributeSchema,\n AuthClientConfig,\n EmbeddedSignInFlowResponse,\n ExtendedAuthorizeRequestUrlParams,\n IdToken,\n SignInOptions,\n SignUpOptions,\n Storage,\n TokenExchangeRequestConfig,\n TokenResponse,\n User,\n ManagedFlowListResponse,\n ManagedUserListResponse,\n ManagedUserTypeListResponse,\n UserProfile,\n executeEmbeddedSignInFlow,\n extractUserClaimsFromIdToken,\n generateFlattenedUserProfile,\n getUsersMe,\n getUsersMeMeta,\n updateMeCredentials,\n updateMeProfile,\n resolveResourceEndpoint,\n} from '@thunderid/node';\nimport {ThunderIDNextConfig} from './models/config';\nimport getClientOrigin from './server/actions/getClientOrigin';\nimport getSessionId from './server/actions/getSessionId';\nimport decorateConfigWithNextEnv from './utils/decorateConfigWithNextEnv';\n\nclass ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextConfig> extends ThunderIDNodeClient<T> {\n public isInitialized = false;\n\n public constructor() {\n super();\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.isInitialized) {\n // Server actions may run in a module context that hasn't been through\n // ThunderIDServerProvider (e.g. a different worker). Try to initialize\n // from environment variables before giving up.\n await this.initialize({} as T);\n }\n\n if (!this.isInitialized) {\n throw new Error(\n '[ThunderIDNextClient] Client is not initialized. Make sure you have wrapped your app with ThunderIDProvider and provided the required configuration (baseUrl, clientId, etc.).',\n );\n }\n }\n\n override async initialize(config: T, storage?: Storage): Promise<boolean> {\n if (this.isInitialized) {\n return Promise.resolve(true);\n }\n\n const {\n baseUrl,\n organizationHandle,\n clientId,\n clientSecret,\n flowSecret,\n signInUrl,\n afterSignInUrl,\n afterSignOutUrl,\n signUpUrl,\n ...rest\n } = decorateConfigWithNextEnv(config);\n\n const origin: string = await getClientOrigin();\n\n const initialized: boolean = await super.initialize(\n {\n ...rest,\n afterSignInUrl: afterSignInUrl ?? origin,\n afterSignOutUrl: afterSignOutUrl ?? origin,\n baseUrl,\n clientId,\n clientSecret,\n enablePKCE: (rest as any).enablePKCE ?? true,\n flowSecret,\n organizationHandle,\n signInUrl,\n signUpUrl,\n } as any,\n storage,\n );\n\n this.isInitialized = initialized;\n\n return initialized;\n }\n\n override async reInitialize(config: Partial<T>): Promise<boolean> {\n try {\n await super.reInitialize(config);\n return true;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to re-initialize the client: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-reInitialize-RuntimeError-001',\n 'nextjs',\n 'An error occurred while re-initializing the client. Please check your configuration and network connection.',\n );\n }\n }\n\n override async getUser(userId?: string): Promise<User> {\n await this.ensureInitialized();\n const resolvedSessionId: string = userId || (await getSessionId())!;\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return profile;\n } catch (error) {\n return await super.getUser(resolvedSessionId);\n }\n }\n\n override async getUserProfile(userId?: string): Promise<UserProfile> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return {\n flattenedProfile: generateFlattenedUserProfile(profile),\n profile,\n };\n } catch (error) {\n return {\n flattenedProfile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n profile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n };\n }\n }\n\n async getUserSchema(userId?: string): Promise<Record<string, AttributeSchema> | null> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const {schema} = await getUsersMeMeta({\n baseUrl,\n url: resolveResourceEndpoint('usersMeMeta', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return schema ?? null;\n } catch (error) {\n return null;\n }\n }\n\n override async updateUserProfile(payload: any, userId?: string): Promise<User> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n return updateMeProfile({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload: payload?.payload ?? payload,\n });\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to update user profile: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-UpdateProfileError-001',\n 'react',\n 'An error occurred while updating the user profile. Please check your configuration and network connection.',\n );\n }\n }\n\n /**\n * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other\n * attribute the user type schema declares `credential: true`).\n *\n * Not part of {@link ThunderIDJavaScriptClient}'s base surface — unlike `updateUserProfile`,\n * no other SDK routes credential updates through a client method (React/Vue's\n * `ChangeCredential` call the core `updateMeCredentials` function directly), so this is a\n * Next.js-specific addition rather than an override. Kept here anyway so this SDK's own\n * server actions have one consistent way to reach every `/users/me/*` operation.\n *\n * Deliberately does not catch and rewrap errors the way `updateUserProfile` does: the caller\n * (`updateUserCredentialsAction`) needs the real `ThunderIDAPIError` instance, status code\n * included, to map a failure onto the right form field before it crosses the server action\n * boundary back to the client.\n */\n override async updateUserCredentials(payload: Record<string, string>, userId?: string): Promise<void> {\n await this.ensureInitialized();\n\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n await updateMeCredentials({\n baseUrl,\n url: resolveResourceEndpoint('usersMeCredentials', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload,\n });\n }\n\n /**\n * Retrieves one page of the user directory for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUsers(\n options: {filter?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserListResponse> {\n await this.ensureInitialized();\n\n return super.getUsers(options, userId);\n }\n\n /**\n * Retrieves one page of flows for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getFlows(\n options: {flowType?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedFlowListResponse> {\n await this.ensureInitialized();\n\n return super.getFlows(options, userId);\n }\n\n /**\n * Retrieves one page of user types for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUserTypes(\n options: {limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserTypeListResponse> {\n await this.ensureInitialized();\n\n return super.getUserTypes(options, userId);\n }\n\n override isLoading(): boolean {\n return false;\n }\n\n override isSignedIn(sessionId?: string): Promise<boolean> {\n return super.isSignedIn(sessionId);\n }\n\n override exchangeToken(config: TokenExchangeRequestConfig, sessionId?: string): Promise<TokenResponse | Response> {\n return super.exchangeToken(config, sessionId) as unknown as Promise<TokenResponse | Response>;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override async getAccessToken(_sessionId?: string): Promise<string> {\n const {default: getAccessToken} = await import('./server/actions/getAccessToken');\n const token: string | undefined = await getAccessToken();\n\n if (typeof token !== 'string' || !token) {\n throw new ThunderIDRuntimeError(\n 'Failed to get access token.',\n 'ThunderIDNextClient-getAccessToken-RuntimeError-003',\n 'nextjs',\n 'An error occurred while obtaining the access token. Please check your configuration and network connection.',\n );\n }\n\n return token;\n }\n\n override async getDecodedIdToken(sessionId?: string, idToken?: string): Promise<IdToken> {\n await this.ensureInitialized();\n return await super.getDecodedIdToken(sessionId, idToken);\n }\n\n override async signIn(...args: any[]): Promise<any> {\n const arg1: any = args[0];\n const arg2: any = args[1];\n const arg3: any = args[2];\n const arg4: any = args[3];\n\n // An embedded sign-in flow payload initiates or continues a `POST /flow/execute` step\n // (identified by `applicationId` for a new flow or `executionId` to continue one). This is\n // distinct from the OAuth authorization_code exchange handled by `super.signIn` below, which\n // is used once the embedded flow completes and returns an authorization code.\n const isEmbeddedFlowPayload: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n if (isEmbeddedFlowPayload) {\n await this.ensureInitialized();\n\n // Typed as the Next config rather than `AuthClientConfig<T>` because the server-only\n // `flowSecret` lives on `ThunderIDNodeConfig`, which the generic base config does not expose.\n const configData: ThunderIDNextConfig = (await this.getStorageManager().getConfigData()) as ThunderIDNextConfig;\n\n return executeEmbeddedSignInFlow({\n baseUrl: configData?.baseUrl,\n flowSecret: arg2?.flowSecret ?? configData?.flowSecret,\n payload: arg1,\n url: resolveResourceEndpoint('flowExecute', configData, arg2?.url),\n }) as unknown as Promise<EmbeddedSignInFlowResponse>;\n }\n\n return super.signIn(arg4, arg3, arg1?.code, arg1?.state, arg1) as unknown as Promise<User>;\n }\n\n override async signOut(...args: any[]): Promise<string> {\n if (args[1] && typeof args[1] !== 'string') {\n throw new Error('The second argument must be a string.');\n }\n\n const config: T = await this.getConfiguration();\n const afterSignOutUrl: string = config?.afterSignOutUrl || '/';\n\n const resolvedSessionId: string = args[1] || (await getSessionId())!;\n\n try {\n await (super.signOut as (...a: any[]) => Promise<string>)(resolvedSessionId);\n } catch (error) {\n const message: string = error instanceof Error ? error.message : String(error);\n\n if (\n !message.includes('end_session_endpoint') &&\n !message.includes('sign-out endpoint') &&\n !message.includes('Sign-out endpoint') &&\n !message.includes('Sign-out redirect URL')\n ) {\n throw error;\n }\n }\n\n return afterSignOutUrl;\n }\n\n override async signUp(_options?: SignUpOptions): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-ValidationError-002',\n 'nextjs',\n 'The signUp method is not implemented in the Next.js client.',\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override signInSilently(_options?: SignInOptions): Promise<User | boolean> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-signInSilently-NotImplementedError-001',\n 'nextjs',\n 'The signInSilently method is not implemented in the Next.js client.',\n );\n }\n\n public async getAuthorizeRequestUrl(\n customParams: ExtendedAuthorizeRequestUrlParams,\n userId?: string,\n ): Promise<string> {\n await this.ensureInitialized();\n return this.getSignInUrl(customParams, userId);\n }\n\n public override getStorageManager(): any {\n return super.getStorageManager();\n }\n\n public override async clearSession(): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-clearSession-NotImplementedError-001',\n 'nextjs',\n 'The clearSession method is not implemented in the Next.js client.',\n );\n }\n\n override async setSession(sessionData: Record<string, unknown>, sessionId?: string): Promise<void> {\n return this.getStorageManager().setSessionData(sessionData, sessionId);\n }\n\n override decodeJwtToken<R = Record<string, unknown>>(token: string): Promise<R> {\n return super.decodeJwtToken<R>(token);\n }\n}\n\nexport default ThunderIDNextClient;\n"],"mappings":";;;;;;AAmCA,IAAM,sBAAN,cAAuF,oBAAuB;CAC5G,AAAO,gBAAgB;CAEvB,AAAO,cAAc;AACnB,SAAO;;CAGT,MAAc,oBAAmC;AAC/C,MAAI,CAAC,KAAK,cAIR,OAAM,KAAK,WAAW,EAAE,CAAM;AAGhC,MAAI,CAAC,KAAK,cACR,OAAM,IAAI,MACR,iLACD;;CAIL,MAAe,WAAW,QAAW,SAAqC;AACxE,MAAI,KAAK,cACP,QAAO,QAAQ,QAAQ,KAAK;EAG9B,MAAM,EACJ,SACA,oBACA,UACA,cACA,YACA,WACA,gBACA,iBACA,UACA,GAAG,SACDA,kCAA0B,OAAO;EAErC,MAAMC,SAAiB,MAAMC,yBAAiB;EAE9C,MAAMC,cAAuB,MAAM,MAAM,WACvC;GACE,GAAG;GACH,gBAAgB,kBAAkB;GAClC,iBAAiB,mBAAmB;GACpC;GACA;GACA;GACA,YAAa,KAAa,cAAc;GACxC;GACA;GACA;GACA;GACD,EACD,QACD;AAED,OAAK,gBAAgB;AAErB,SAAO;;CAGT,MAAe,aAAa,QAAsC;AAChE,MAAI;AACF,SAAM,MAAM,aAAa,OAAO;AAChC,UAAO;WACA,OAAO;AACd,SAAM,IAAI,sBACR,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAC7F,qDACA,UACA,8GACD;;;CAIL,MAAe,QAAQ,QAAgC;AACrD,QAAM,KAAK,mB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AM,IAAI,sBACR,mBACA,2CACA,UACA,8DACD;;CAIH,AAAS,eAAe,UAAmD;AACzE,QAAM,IAAI,sBACR,mBACA,8DACA,UACA,sEACD;;CAGH,MAAa,uBACX,cACA,QACiB;AACjB,QAAM,KAAK,mBAAmB;AAC9B,SAAO,KAAK,aAAa,cAAc,OAAO;;CAGhD,AAAgB,oBAAyB;AACvC,SAAO,MAAM,mBAAmB;;CAGlC,MAAsB,eAA8B;AAClD,QAAM,IAAI,sBACR,mBACA,4DACA,UACA,oEACD;;CAGH,MAAe,WAAW,aAAsC,WAAmC;AACjG,SAAO,KAAK,mBAAmB,CAAC,eAAe,aAAa,UAAU;;CAGxE,AAAS,eAA4C,OAA2B;AAC9E,SAAO,MAAM,eAAkB,MAAM;;;AAIzC,kCAAe"}
|
|
1
|
+
{"version":3,"file":"ThunderIDNextClient.js","names":["decorateConfigWithNextEnv","origin: string","getClientOrigin","initialized: boolean","resolvedSessionId: string","getSessionId","configData: AuthClientConfig<T>","baseUrl: string | undefined","profile: User","token: string | undefined","arg1: any","arg2: any","arg3: any","arg4: any","configData: ThunderIDNextConfig","afterSignOutUrl: string","message: string"],"sources":["../src/ThunderIDNextClient.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n ThunderIDNodeClient,\n ThunderIDRuntimeError,\n AttributeSchema,\n AuthClientConfig,\n EmbeddedSelfFlowRequest,\n EmbeddedSelfFlowResponse,\n EmbeddedSignInFlowResponse,\n ExtendedAuthorizeRequestUrlParams,\n IdToken,\n SignInOptions,\n SignUpOptions,\n Storage,\n TokenExchangeRequestConfig,\n TokenResponse,\n User,\n ManagedFlowListResponse,\n ManagedUserListResponse,\n ManagedUserTypeListResponse,\n UserProfile,\n executeEmbeddedSignInFlow,\n extractUserClaimsFromIdToken,\n generateFlattenedUserProfile,\n getUsersMe,\n getUsersMeMeta,\n updateMeCredentials,\n updateMeProfile,\n resolveResourceEndpoint,\n} from '@thunderid/node';\nimport {ThunderIDNextConfig} from './models/config';\nimport getClientOrigin from './server/actions/getClientOrigin';\nimport getSessionId from './server/actions/getSessionId';\nimport decorateConfigWithNextEnv from './utils/decorateConfigWithNextEnv';\n\nclass ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextConfig> extends ThunderIDNodeClient<T> {\n public isInitialized = false;\n\n public constructor() {\n super();\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.isInitialized) {\n // Server actions may run in a module context that hasn't been through\n // ThunderIDServerProvider (e.g. a different worker). Try to initialize\n // from environment variables before giving up.\n await this.initialize({} as T);\n }\n\n if (!this.isInitialized) {\n throw new Error(\n '[ThunderIDNextClient] Client is not initialized. Make sure you have wrapped your app with ThunderIDProvider and provided the required configuration (baseUrl, clientId, etc.).',\n );\n }\n }\n\n override async initialize(config: T, storage?: Storage): Promise<boolean> {\n if (this.isInitialized) {\n return Promise.resolve(true);\n }\n\n const {\n baseUrl,\n organizationHandle,\n clientId,\n clientSecret,\n flowSecret,\n signInUrl,\n afterSignInUrl,\n afterSignOutUrl,\n signUpUrl,\n ...rest\n } = decorateConfigWithNextEnv(config);\n\n const origin: string = await getClientOrigin();\n\n const initialized: boolean = await super.initialize(\n {\n ...rest,\n afterSignInUrl: afterSignInUrl ?? origin,\n afterSignOutUrl: afterSignOutUrl ?? origin,\n baseUrl,\n clientId,\n clientSecret,\n enablePKCE: (rest as any).enablePKCE ?? true,\n flowSecret,\n organizationHandle,\n signInUrl,\n signUpUrl,\n } as any,\n storage,\n );\n\n this.isInitialized = initialized;\n\n return initialized;\n }\n\n override async reInitialize(config: Partial<T>): Promise<boolean> {\n try {\n await super.reInitialize(config);\n return true;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to re-initialize the client: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-reInitialize-RuntimeError-001',\n 'nextjs',\n 'An error occurred while re-initializing the client. Please check your configuration and network connection.',\n );\n }\n }\n\n override async getUser(userId?: string): Promise<User> {\n await this.ensureInitialized();\n const resolvedSessionId: string = userId || (await getSessionId())!;\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return profile;\n } catch (error) {\n return await super.getUser(resolvedSessionId);\n }\n }\n\n override async getUserProfile(userId?: string): Promise<UserProfile> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return {\n flattenedProfile: generateFlattenedUserProfile(profile),\n profile,\n };\n } catch (error) {\n return {\n flattenedProfile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n profile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n };\n }\n }\n\n async getUserSchema(userId?: string): Promise<Record<string, AttributeSchema> | null> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const {schema} = await getUsersMeMeta({\n baseUrl,\n url: resolveResourceEndpoint('usersMeMeta', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return schema ?? null;\n } catch (error) {\n return null;\n }\n }\n\n override async updateUserProfile(payload: any, userId?: string): Promise<User> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n return updateMeProfile({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload: payload?.payload ?? payload,\n });\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to update user profile: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-UpdateProfileError-001',\n 'react',\n 'An error occurred while updating the user profile. Please check your configuration and network connection.',\n );\n }\n }\n\n /**\n * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other\n * attribute the user type schema declares `credential: true`).\n *\n * Not part of {@link ThunderIDJavaScriptClient}'s base surface — unlike `updateUserProfile`,\n * no other SDK routes credential updates through a client method (React/Vue's\n * `ChangeCredential` call the core `updateMeCredentials` function directly), so this is a\n * Next.js-specific addition rather than an override. Kept here anyway so this SDK's own\n * server actions have one consistent way to reach every `/users/me/*` operation.\n *\n * Deliberately does not catch and rewrap errors the way `updateUserProfile` does: the caller\n * (`updateUserCredentialsAction`) needs the real `ThunderIDAPIError` instance, status code\n * included, to map a failure onto the right form field before it crosses the server action\n * boundary back to the client.\n */\n override async updateUserCredentials(payload: Record<string, string>, userId?: string): Promise<void> {\n await this.ensureInitialized();\n\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n await updateMeCredentials({\n baseUrl,\n url: resolveResourceEndpoint('usersMeCredentials', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload,\n });\n }\n\n /**\n * Executes one step of a `SELF` flow, such as self attribute verification, for the session\n * identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async executeEmbeddedSelfFlow(\n payload: EmbeddedSelfFlowRequest,\n userId?: string,\n ): Promise<EmbeddedSelfFlowResponse> {\n await this.ensureInitialized();\n\n return super.executeEmbeddedSelfFlow(payload, userId);\n }\n\n /**\n * Retrieves one page of the user directory for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUsers(\n options: {filter?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserListResponse> {\n await this.ensureInitialized();\n\n return super.getUsers(options, userId);\n }\n\n /**\n * Retrieves one page of flows for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getFlows(\n options: {flowType?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedFlowListResponse> {\n await this.ensureInitialized();\n\n return super.getFlows(options, userId);\n }\n\n /**\n * Retrieves one page of user types for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUserTypes(\n options: {limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserTypeListResponse> {\n await this.ensureInitialized();\n\n return super.getUserTypes(options, userId);\n }\n\n override isLoading(): boolean {\n return false;\n }\n\n override isSignedIn(sessionId?: string): Promise<boolean> {\n return super.isSignedIn(sessionId);\n }\n\n override exchangeToken(config: TokenExchangeRequestConfig, sessionId?: string): Promise<TokenResponse | Response> {\n return super.exchangeToken(config, sessionId) as unknown as Promise<TokenResponse | Response>;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override async getAccessToken(_sessionId?: string): Promise<string> {\n const {default: getAccessToken} = await import('./server/actions/getAccessToken');\n const token: string | undefined = await getAccessToken();\n\n if (typeof token !== 'string' || !token) {\n throw new ThunderIDRuntimeError(\n 'Failed to get access token.',\n 'ThunderIDNextClient-getAccessToken-RuntimeError-003',\n 'nextjs',\n 'An error occurred while obtaining the access token. Please check your configuration and network connection.',\n );\n }\n\n return token;\n }\n\n override async getDecodedIdToken(sessionId?: string, idToken?: string): Promise<IdToken> {\n await this.ensureInitialized();\n return await super.getDecodedIdToken(sessionId, idToken);\n }\n\n override async signIn(...args: any[]): Promise<any> {\n const arg1: any = args[0];\n const arg2: any = args[1];\n const arg3: any = args[2];\n const arg4: any = args[3];\n\n // An embedded sign-in flow payload initiates or continues a `POST /flow/execute` step\n // (identified by `applicationId` for a new flow or `executionId` to continue one). This is\n // distinct from the OAuth authorization_code exchange handled by `super.signIn` below, which\n // is used once the embedded flow completes and returns an authorization code.\n const isEmbeddedFlowPayload: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n if (isEmbeddedFlowPayload) {\n await this.ensureInitialized();\n\n // Typed as the Next config rather than `AuthClientConfig<T>` because the server-only\n // `flowSecret` lives on `ThunderIDNodeConfig`, which the generic base config does not expose.\n const configData: ThunderIDNextConfig = (await this.getStorageManager().getConfigData()) as ThunderIDNextConfig;\n\n return executeEmbeddedSignInFlow({\n baseUrl: configData?.baseUrl,\n flowSecret: arg2?.flowSecret ?? configData?.flowSecret,\n payload: arg1,\n url: resolveResourceEndpoint('flowExecute', configData, arg2?.url),\n }) as unknown as Promise<EmbeddedSignInFlowResponse>;\n }\n\n return super.signIn(arg4, arg3, arg1?.code, arg1?.state, arg1) as unknown as Promise<User>;\n }\n\n override async signOut(...args: any[]): Promise<string> {\n if (args[1] && typeof args[1] !== 'string') {\n throw new Error('The second argument must be a string.');\n }\n\n const config: T = await this.getConfiguration();\n const afterSignOutUrl: string = config?.afterSignOutUrl || '/';\n\n const resolvedSessionId: string = args[1] || (await getSessionId())!;\n\n try {\n await (super.signOut as (...a: any[]) => Promise<string>)(resolvedSessionId);\n } catch (error) {\n const message: string = error instanceof Error ? error.message : String(error);\n\n if (\n !message.includes('end_session_endpoint') &&\n !message.includes('sign-out endpoint') &&\n !message.includes('Sign-out endpoint') &&\n !message.includes('Sign-out redirect URL')\n ) {\n throw error;\n }\n }\n\n return afterSignOutUrl;\n }\n\n override async signUp(_options?: SignUpOptions): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-ValidationError-002',\n 'nextjs',\n 'The signUp method is not implemented in the Next.js client.',\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override signInSilently(_options?: SignInOptions): Promise<User | boolean> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-signInSilently-NotImplementedError-001',\n 'nextjs',\n 'The signInSilently method is not implemented in the Next.js client.',\n );\n }\n\n public async getAuthorizeRequestUrl(\n customParams: ExtendedAuthorizeRequestUrlParams,\n userId?: string,\n ): Promise<string> {\n await this.ensureInitialized();\n return this.getSignInUrl(customParams, userId);\n }\n\n public override getStorageManager(): any {\n return super.getStorageManager();\n }\n\n public override async clearSession(): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-clearSession-NotImplementedError-001',\n 'nextjs',\n 'The clearSession method is not implemented in the Next.js client.',\n );\n }\n\n override async setSession(sessionData: Record<string, unknown>, sessionId?: string): Promise<void> {\n return this.getStorageManager().setSessionData(sessionData, sessionId);\n }\n\n override decodeJwtToken<R = Record<string, unknown>>(token: string): Promise<R> {\n return super.decodeJwtToken<R>(token);\n }\n}\n\nexport default ThunderIDNextClient;\n"],"mappings":";;;;;;AAqCA,IAAM,sBAAN,cAAuF,oBAAuB;CAC5G,AAAO,gBAAgB;CAEvB,AAAO,cAAc;AACnB,SAAO;;CAGT,MAAc,oBAAmC;AAC/C,MAAI,CAAC,KAAK,cAIR,OAAM,KAAK,WAAW,EAAE,CAAM;AAGhC,MAAI,CAAC,KAAK,cACR,OAAM,IAAI,MACR,iLACD;;CAIL,MAAe,WAAW,QAAW,SAAqC;AACxE,MAAI,KAAK,cACP,QAAO,QAAQ,QAAQ,KAAK;EAG9B,MAAM,EACJ,SACA,oBACA,UACA,cACA,YACA,WACA,gBACA,iBACA,UACA,GAAG,SACDA,kCAA0B,OAAO;EAErC,MAAMC,SAAiB,MAAMC,yBAAiB;EAE9C,MAAMC,cAAuB,MAAM,MAAM,WACvC;GACE,GAAG;GACH,gBAAgB,kBAAkB;GAClC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OAAO,SAChC,OAAM,IAAI,MAAM,wCAAwC;EAI1D,MAAMC,mBADY,MAAM,KAAK,kBAAkB,GACP,mBAAmB;EAE3D,MAAMX,oBAA4B,KAAK,MAAO,MAAMC,sBAAc;AAElE,MAAI;AACF,SAAO,MAAM,QAA6C,kBAAkB;WACrE,OAAO;GACd,MAAMW,UAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AAE9E,OACE,CAAC,QAAQ,SAAS,uBAAuB,IACzC,CAAC,QAAQ,SAAS,oBAAoB,IACtC,CAAC,QAAQ,SAAS,oBAAoB,IACtC,CAAC,QAAQ,SAAS,wBAAwB,CAE1C,OAAM;;AAIV,SAAO;;CAGT,MAAe,OAAO,UAAyC;AAC7D,QAAM,IAAI,sBACR,mBACA,2CACA,UACA,8DACD;;CAIH,AAAS,eAAe,UAAmD;AACzE,QAAM,IAAI,sBACR,mBACA,8DACA,UACA,sEACD;;CAGH,MAAa,uBACX,cACA,QACiB;AACjB,QAAM,KAAK,mBAAmB;AAC9B,SAAO,KAAK,aAAa,cAAc,OAAO;;CAGhD,AAAgB,oBAAyB;AACvC,SAAO,MAAM,mBAAmB;;CAGlC,MAAsB,eAA8B;AAClD,QAAM,IAAI,sBACR,mBACA,4DACA,UACA,oEACD;;CAGH,MAAe,WAAW,aAAsC,WAAmC;AACjG,SAAO,KAAK,mBAAmB,CAAC,eAAe,aAAa,UAAU;;CAGxE,AAAS,eAA4C,OAA2B;AAC9E,SAAO,MAAM,eAAkB,MAAM;;;AAIzC,kCAAe"}
|
|
@@ -136,6 +136,16 @@ var ThunderIDNextClient = class extends __thunderid_node.ThunderIDNodeClient {
|
|
|
136
136
|
});
|
|
137
137
|
}
|
|
138
138
|
/**
|
|
139
|
+
* Executes one step of a `SELF` flow, such as self attribute verification, for the session
|
|
140
|
+
* identified by `userId`.
|
|
141
|
+
*
|
|
142
|
+
* Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.
|
|
143
|
+
*/
|
|
144
|
+
async executeEmbeddedSelfFlow(payload, userId) {
|
|
145
|
+
await this.ensureInitialized();
|
|
146
|
+
return super.executeEmbeddedSelfFlow(payload, userId);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
139
149
|
* Retrieves one page of the user directory for the session identified by `userId`.
|
|
140
150
|
*
|
|
141
151
|
* Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThunderIDNextClient.cjs","names":["ThunderIDNodeClient","decorateConfigWithNextEnv","origin: string","getClientOrigin","initialized: boolean","ThunderIDRuntimeError","resolvedSessionId: string","getSessionId","configData: AuthClientConfig<T>","baseUrl: string | undefined","profile: User","token: string | undefined","arg1: any","arg2: any","arg3: any","arg4: any","configData: ThunderIDNextConfig","afterSignOutUrl: string","message: string"],"sources":["../../src/ThunderIDNextClient.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n ThunderIDNodeClient,\n ThunderIDRuntimeError,\n AttributeSchema,\n AuthClientConfig,\n EmbeddedSignInFlowResponse,\n ExtendedAuthorizeRequestUrlParams,\n IdToken,\n SignInOptions,\n SignUpOptions,\n Storage,\n TokenExchangeRequestConfig,\n TokenResponse,\n User,\n ManagedFlowListResponse,\n ManagedUserListResponse,\n ManagedUserTypeListResponse,\n UserProfile,\n executeEmbeddedSignInFlow,\n extractUserClaimsFromIdToken,\n generateFlattenedUserProfile,\n getUsersMe,\n getUsersMeMeta,\n updateMeCredentials,\n updateMeProfile,\n resolveResourceEndpoint,\n} from '@thunderid/node';\nimport {ThunderIDNextConfig} from './models/config';\nimport getClientOrigin from './server/actions/getClientOrigin';\nimport getSessionId from './server/actions/getSessionId';\nimport decorateConfigWithNextEnv from './utils/decorateConfigWithNextEnv';\n\nclass ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextConfig> extends ThunderIDNodeClient<T> {\n public isInitialized = false;\n\n public constructor() {\n super();\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.isInitialized) {\n // Server actions may run in a module context that hasn't been through\n // ThunderIDServerProvider (e.g. a different worker). Try to initialize\n // from environment variables before giving up.\n await this.initialize({} as T);\n }\n\n if (!this.isInitialized) {\n throw new Error(\n '[ThunderIDNextClient] Client is not initialized. Make sure you have wrapped your app with ThunderIDProvider and provided the required configuration (baseUrl, clientId, etc.).',\n );\n }\n }\n\n override async initialize(config: T, storage?: Storage): Promise<boolean> {\n if (this.isInitialized) {\n return Promise.resolve(true);\n }\n\n const {\n baseUrl,\n organizationHandle,\n clientId,\n clientSecret,\n flowSecret,\n signInUrl,\n afterSignInUrl,\n afterSignOutUrl,\n signUpUrl,\n ...rest\n } = decorateConfigWithNextEnv(config);\n\n const origin: string = await getClientOrigin();\n\n const initialized: boolean = await super.initialize(\n {\n ...rest,\n afterSignInUrl: afterSignInUrl ?? origin,\n afterSignOutUrl: afterSignOutUrl ?? origin,\n baseUrl,\n clientId,\n clientSecret,\n enablePKCE: (rest as any).enablePKCE ?? true,\n flowSecret,\n organizationHandle,\n signInUrl,\n signUpUrl,\n } as any,\n storage,\n );\n\n this.isInitialized = initialized;\n\n return initialized;\n }\n\n override async reInitialize(config: Partial<T>): Promise<boolean> {\n try {\n await super.reInitialize(config);\n return true;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to re-initialize the client: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-reInitialize-RuntimeError-001',\n 'nextjs',\n 'An error occurred while re-initializing the client. Please check your configuration and network connection.',\n );\n }\n }\n\n override async getUser(userId?: string): Promise<User> {\n await this.ensureInitialized();\n const resolvedSessionId: string = userId || (await getSessionId())!;\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return profile;\n } catch (error) {\n return await super.getUser(resolvedSessionId);\n }\n }\n\n override async getUserProfile(userId?: string): Promise<UserProfile> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return {\n flattenedProfile: generateFlattenedUserProfile(profile),\n profile,\n };\n } catch (error) {\n return {\n flattenedProfile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n profile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n };\n }\n }\n\n async getUserSchema(userId?: string): Promise<Record<string, AttributeSchema> | null> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const {schema} = await getUsersMeMeta({\n baseUrl,\n url: resolveResourceEndpoint('usersMeMeta', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return schema ?? null;\n } catch (error) {\n return null;\n }\n }\n\n override async updateUserProfile(payload: any, userId?: string): Promise<User> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n return updateMeProfile({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload: payload?.payload ?? payload,\n });\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to update user profile: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-UpdateProfileError-001',\n 'react',\n 'An error occurred while updating the user profile. Please check your configuration and network connection.',\n );\n }\n }\n\n /**\n * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other\n * attribute the user type schema declares `credential: true`).\n *\n * Not part of {@link ThunderIDJavaScriptClient}'s base surface — unlike `updateUserProfile`,\n * no other SDK routes credential updates through a client method (React/Vue's\n * `ChangeCredential` call the core `updateMeCredentials` function directly), so this is a\n * Next.js-specific addition rather than an override. Kept here anyway so this SDK's own\n * server actions have one consistent way to reach every `/users/me/*` operation.\n *\n * Deliberately does not catch and rewrap errors the way `updateUserProfile` does: the caller\n * (`updateUserCredentialsAction`) needs the real `ThunderIDAPIError` instance, status code\n * included, to map a failure onto the right form field before it crosses the server action\n * boundary back to the client.\n */\n override async updateUserCredentials(payload: Record<string, string>, userId?: string): Promise<void> {\n await this.ensureInitialized();\n\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n await updateMeCredentials({\n baseUrl,\n url: resolveResourceEndpoint('usersMeCredentials', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload,\n });\n }\n\n /**\n * Retrieves one page of the user directory for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUsers(\n options: {filter?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserListResponse> {\n await this.ensureInitialized();\n\n return super.getUsers(options, userId);\n }\n\n /**\n * Retrieves one page of flows for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getFlows(\n options: {flowType?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedFlowListResponse> {\n await this.ensureInitialized();\n\n return super.getFlows(options, userId);\n }\n\n /**\n * Retrieves one page of user types for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUserTypes(\n options: {limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserTypeListResponse> {\n await this.ensureInitialized();\n\n return super.getUserTypes(options, userId);\n }\n\n override isLoading(): boolean {\n return false;\n }\n\n override isSignedIn(sessionId?: string): Promise<boolean> {\n return super.isSignedIn(sessionId);\n }\n\n override exchangeToken(config: TokenExchangeRequestConfig, sessionId?: string): Promise<TokenResponse | Response> {\n return super.exchangeToken(config, sessionId) as unknown as Promise<TokenResponse | Response>;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override async getAccessToken(_sessionId?: string): Promise<string> {\n const {default: getAccessToken} = await import('./server/actions/getAccessToken');\n const token: string | undefined = await getAccessToken();\n\n if (typeof token !== 'string' || !token) {\n throw new ThunderIDRuntimeError(\n 'Failed to get access token.',\n 'ThunderIDNextClient-getAccessToken-RuntimeError-003',\n 'nextjs',\n 'An error occurred while obtaining the access token. Please check your configuration and network connection.',\n );\n }\n\n return token;\n }\n\n override async getDecodedIdToken(sessionId?: string, idToken?: string): Promise<IdToken> {\n await this.ensureInitialized();\n return await super.getDecodedIdToken(sessionId, idToken);\n }\n\n override async signIn(...args: any[]): Promise<any> {\n const arg1: any = args[0];\n const arg2: any = args[1];\n const arg3: any = args[2];\n const arg4: any = args[3];\n\n // An embedded sign-in flow payload initiates or continues a `POST /flow/execute` step\n // (identified by `applicationId` for a new flow or `executionId` to continue one). This is\n // distinct from the OAuth authorization_code exchange handled by `super.signIn` below, which\n // is used once the embedded flow completes and returns an authorization code.\n const isEmbeddedFlowPayload: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n if (isEmbeddedFlowPayload) {\n await this.ensureInitialized();\n\n // Typed as the Next config rather than `AuthClientConfig<T>` because the server-only\n // `flowSecret` lives on `ThunderIDNodeConfig`, which the generic base config does not expose.\n const configData: ThunderIDNextConfig = (await this.getStorageManager().getConfigData()) as ThunderIDNextConfig;\n\n return executeEmbeddedSignInFlow({\n baseUrl: configData?.baseUrl,\n flowSecret: arg2?.flowSecret ?? configData?.flowSecret,\n payload: arg1,\n url: resolveResourceEndpoint('flowExecute', configData, arg2?.url),\n }) as unknown as Promise<EmbeddedSignInFlowResponse>;\n }\n\n return super.signIn(arg4, arg3, arg1?.code, arg1?.state, arg1) as unknown as Promise<User>;\n }\n\n override async signOut(...args: any[]): Promise<string> {\n if (args[1] && typeof args[1] !== 'string') {\n throw new Error('The second argument must be a string.');\n }\n\n const config: T = await this.getConfiguration();\n const afterSignOutUrl: string = config?.afterSignOutUrl || '/';\n\n const resolvedSessionId: string = args[1] || (await getSessionId())!;\n\n try {\n await (super.signOut as (...a: any[]) => Promise<string>)(resolvedSessionId);\n } catch (error) {\n const message: string = error instanceof Error ? error.message : String(error);\n\n if (\n !message.includes('end_session_endpoint') &&\n !message.includes('sign-out endpoint') &&\n !message.includes('Sign-out endpoint') &&\n !message.includes('Sign-out redirect URL')\n ) {\n throw error;\n }\n }\n\n return afterSignOutUrl;\n }\n\n override async signUp(_options?: SignUpOptions): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-ValidationError-002',\n 'nextjs',\n 'The signUp method is not implemented in the Next.js client.',\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override signInSilently(_options?: SignInOptions): Promise<User | boolean> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-signInSilently-NotImplementedError-001',\n 'nextjs',\n 'The signInSilently method is not implemented in the Next.js client.',\n );\n }\n\n public async getAuthorizeRequestUrl(\n customParams: ExtendedAuthorizeRequestUrlParams,\n userId?: string,\n ): Promise<string> {\n await this.ensureInitialized();\n return this.getSignInUrl(customParams, userId);\n }\n\n public override getStorageManager(): any {\n return super.getStorageManager();\n }\n\n public override async clearSession(): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-clearSession-NotImplementedError-001',\n 'nextjs',\n 'The clearSession method is not implemented in the Next.js client.',\n );\n }\n\n override async setSession(sessionData: Record<string, unknown>, sessionId?: string): Promise<void> {\n return this.getStorageManager().setSessionData(sessionData, sessionId);\n }\n\n override decodeJwtToken<R = Record<string, unknown>>(token: string): Promise<R> {\n return super.decodeJwtToken<R>(token);\n }\n}\n\nexport default ThunderIDNextClient;\n"],"mappings":";;;;;;;;AAmCA,IAAM,sBAAN,cAAuFA,qCAAuB;CAC5G,AAAO,gBAAgB;CAEvB,AAAO,cAAc;AACnB,SAAO;;CAGT,MAAc,oBAAmC;AAC/C,MAAI,CAAC,KAAK,cAIR,OAAM,KAAK,WAAW,EAAE,CAAM;AAGhC,MAAI,CAAC,KAAK,cACR,OAAM,IAAI,MACR,iLACD;;CAIL,MAAe,WAAW,QAAW,SAAqC;AACxE,MAAI,KAAK,cACP,QAAO,QAAQ,QAAQ,KAAK;EAG9B,MAAM,EACJ,SACA,oBACA,UACA,cACA,YACA,WACA,gBACA,iBACA,UACA,GAAG,SACDC,0CAA0B,OAAO;EAErC,MAAMC,SAAiB,MAAMC,iCAAiB;EAE9C,MAAMC,cAAuB,MAAM,MAAM,WACvC;GACE,GAAG;GACH,gBAAgB,kBAAkB;GAClC,iBAAiB,mBAAmB;GACpC;GACA;GACA;GACA,YAAa,KAAa,cAAc;GACxC;GACA;GACA;GACA;GACD,EACD,QACD;AAED,OAAK,gBAAgB;AAErB,SAAO;;CAGT,MAAe,aAAa,QAAsC;AAChE,MAAI;AACF,SAAM,MAAM,aAAa,OAAO;AAChC,UAAO;WACA,OAAO;AACd,SAAM,IAAIC,uCACR,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAC7F,qDACA,UACA,8GACD;;;CAIL,MAAe,QAAQ,QAAgC;AACrD,QAAM,KAAK,mBAAmB;EAC9B,MAAMC,oBAA4B,UAAW,MAAMC,8BAAc;AAEjE,MAAI;GACF,MAAMC,aAAkC,MAAM,KAAK,mBAAm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aAAa,cAAc,OAAO;;CAGhD,AAAgB,oBAAyB;AACvC,SAAO,MAAM,mBAAmB;;CAGlC,MAAsB,eAA8B;AAClD,QAAM,IAAIA,uCACR,mBACA,4DACA,UACA,oEACD;;CAGH,MAAe,WAAW,aAAsC,WAAmC;AACjG,SAAO,KAAK,mBAAmB,CAAC,eAAe,aAAa,UAAU;;CAGxE,AAAS,eAA4C,OAA2B;AAC9E,SAAO,MAAM,eAAkB,MAAM;;;AAIzC,kCAAe"}
|
|
1
|
+
{"version":3,"file":"ThunderIDNextClient.cjs","names":["ThunderIDNodeClient","decorateConfigWithNextEnv","origin: string","getClientOrigin","initialized: boolean","ThunderIDRuntimeError","resolvedSessionId: string","getSessionId","configData: AuthClientConfig<T>","baseUrl: string | undefined","profile: User","token: string | undefined","arg1: any","arg2: any","arg3: any","arg4: any","configData: ThunderIDNextConfig","afterSignOutUrl: string","message: string"],"sources":["../../src/ThunderIDNextClient.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n ThunderIDNodeClient,\n ThunderIDRuntimeError,\n AttributeSchema,\n AuthClientConfig,\n EmbeddedSelfFlowRequest,\n EmbeddedSelfFlowResponse,\n EmbeddedSignInFlowResponse,\n ExtendedAuthorizeRequestUrlParams,\n IdToken,\n SignInOptions,\n SignUpOptions,\n Storage,\n TokenExchangeRequestConfig,\n TokenResponse,\n User,\n ManagedFlowListResponse,\n ManagedUserListResponse,\n ManagedUserTypeListResponse,\n UserProfile,\n executeEmbeddedSignInFlow,\n extractUserClaimsFromIdToken,\n generateFlattenedUserProfile,\n getUsersMe,\n getUsersMeMeta,\n updateMeCredentials,\n updateMeProfile,\n resolveResourceEndpoint,\n} from '@thunderid/node';\nimport {ThunderIDNextConfig} from './models/config';\nimport getClientOrigin from './server/actions/getClientOrigin';\nimport getSessionId from './server/actions/getSessionId';\nimport decorateConfigWithNextEnv from './utils/decorateConfigWithNextEnv';\n\nclass ThunderIDNextClient<T extends ThunderIDNextConfig = ThunderIDNextConfig> extends ThunderIDNodeClient<T> {\n public isInitialized = false;\n\n public constructor() {\n super();\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.isInitialized) {\n // Server actions may run in a module context that hasn't been through\n // ThunderIDServerProvider (e.g. a different worker). Try to initialize\n // from environment variables before giving up.\n await this.initialize({} as T);\n }\n\n if (!this.isInitialized) {\n throw new Error(\n '[ThunderIDNextClient] Client is not initialized. Make sure you have wrapped your app with ThunderIDProvider and provided the required configuration (baseUrl, clientId, etc.).',\n );\n }\n }\n\n override async initialize(config: T, storage?: Storage): Promise<boolean> {\n if (this.isInitialized) {\n return Promise.resolve(true);\n }\n\n const {\n baseUrl,\n organizationHandle,\n clientId,\n clientSecret,\n flowSecret,\n signInUrl,\n afterSignInUrl,\n afterSignOutUrl,\n signUpUrl,\n ...rest\n } = decorateConfigWithNextEnv(config);\n\n const origin: string = await getClientOrigin();\n\n const initialized: boolean = await super.initialize(\n {\n ...rest,\n afterSignInUrl: afterSignInUrl ?? origin,\n afterSignOutUrl: afterSignOutUrl ?? origin,\n baseUrl,\n clientId,\n clientSecret,\n enablePKCE: (rest as any).enablePKCE ?? true,\n flowSecret,\n organizationHandle,\n signInUrl,\n signUpUrl,\n } as any,\n storage,\n );\n\n this.isInitialized = initialized;\n\n return initialized;\n }\n\n override async reInitialize(config: Partial<T>): Promise<boolean> {\n try {\n await super.reInitialize(config);\n return true;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to re-initialize the client: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-reInitialize-RuntimeError-001',\n 'nextjs',\n 'An error occurred while re-initializing the client. Please check your configuration and network connection.',\n );\n }\n }\n\n override async getUser(userId?: string): Promise<User> {\n await this.ensureInitialized();\n const resolvedSessionId: string = userId || (await getSessionId())!;\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return profile;\n } catch (error) {\n return await super.getUser(resolvedSessionId);\n }\n }\n\n override async getUserProfile(userId?: string): Promise<UserProfile> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const profile: User = await getUsersMe({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return {\n flattenedProfile: generateFlattenedUserProfile(profile),\n profile,\n };\n } catch (error) {\n return {\n flattenedProfile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n profile: extractUserClaimsFromIdToken(await super.getDecodedIdToken(userId)),\n };\n }\n }\n\n async getUserSchema(userId?: string): Promise<Record<string, AttributeSchema> | null> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n const {schema} = await getUsersMeMeta({\n baseUrl,\n url: resolveResourceEndpoint('usersMeMeta', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n });\n\n return schema ?? null;\n } catch (error) {\n return null;\n }\n }\n\n override async updateUserProfile(payload: any, userId?: string): Promise<User> {\n await this.ensureInitialized();\n\n try {\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n return updateMeProfile({\n baseUrl,\n url: resolveResourceEndpoint('usersMe', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload: payload?.payload ?? payload,\n });\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Failed to update user profile: ${error instanceof Error ? error.message : String(error)}`,\n 'ThunderIDNextClient-UpdateProfileError-001',\n 'react',\n 'An error occurred while updating the user profile. Please check your configuration and network connection.',\n );\n }\n }\n\n /**\n * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other\n * attribute the user type schema declares `credential: true`).\n *\n * Not part of {@link ThunderIDJavaScriptClient}'s base surface — unlike `updateUserProfile`,\n * no other SDK routes credential updates through a client method (React/Vue's\n * `ChangeCredential` call the core `updateMeCredentials` function directly), so this is a\n * Next.js-specific addition rather than an override. Kept here anyway so this SDK's own\n * server actions have one consistent way to reach every `/users/me/*` operation.\n *\n * Deliberately does not catch and rewrap errors the way `updateUserProfile` does: the caller\n * (`updateUserCredentialsAction`) needs the real `ThunderIDAPIError` instance, status code\n * included, to map a failure onto the right form field before it crosses the server action\n * boundary back to the client.\n */\n override async updateUserCredentials(payload: Record<string, string>, userId?: string): Promise<void> {\n await this.ensureInitialized();\n\n const configData: AuthClientConfig<T> = await this.getStorageManager().getConfigData();\n const baseUrl: string | undefined = configData?.baseUrl;\n\n await updateMeCredentials({\n baseUrl,\n url: resolveResourceEndpoint('usersMeCredentials', configData),\n headers: {\n Authorization: `Bearer ${await this.getAccessToken(userId)}`,\n },\n payload,\n });\n }\n\n /**\n * Executes one step of a `SELF` flow, such as self attribute verification, for the session\n * identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async executeEmbeddedSelfFlow(\n payload: EmbeddedSelfFlowRequest,\n userId?: string,\n ): Promise<EmbeddedSelfFlowResponse> {\n await this.ensureInitialized();\n\n return super.executeEmbeddedSelfFlow(payload, userId);\n }\n\n /**\n * Retrieves one page of the user directory for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `updateUserCredentials`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUsers(\n options: {filter?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserListResponse> {\n await this.ensureInitialized();\n\n return super.getUsers(options, userId);\n }\n\n /**\n * Retrieves one page of flows for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getFlows(\n options: {flowType?: string; limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedFlowListResponse> {\n await this.ensureInitialized();\n\n return super.getFlows(options, userId);\n }\n\n /**\n * Retrieves one page of user types for the session identified by `userId`.\n *\n * Ensures the client is initialized first, like `getUsers`. Errors are not caught so the calling server action can map the real `ThunderIDAPIError`.\n */\n override async getUserTypes(\n options: {limit?: number; offset?: number; signal?: AbortSignal} = {},\n userId?: string,\n ): Promise<ManagedUserTypeListResponse> {\n await this.ensureInitialized();\n\n return super.getUserTypes(options, userId);\n }\n\n override isLoading(): boolean {\n return false;\n }\n\n override isSignedIn(sessionId?: string): Promise<boolean> {\n return super.isSignedIn(sessionId);\n }\n\n override exchangeToken(config: TokenExchangeRequestConfig, sessionId?: string): Promise<TokenResponse | Response> {\n return super.exchangeToken(config, sessionId) as unknown as Promise<TokenResponse | Response>;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override async getAccessToken(_sessionId?: string): Promise<string> {\n const {default: getAccessToken} = await import('./server/actions/getAccessToken');\n const token: string | undefined = await getAccessToken();\n\n if (typeof token !== 'string' || !token) {\n throw new ThunderIDRuntimeError(\n 'Failed to get access token.',\n 'ThunderIDNextClient-getAccessToken-RuntimeError-003',\n 'nextjs',\n 'An error occurred while obtaining the access token. Please check your configuration and network connection.',\n );\n }\n\n return token;\n }\n\n override async getDecodedIdToken(sessionId?: string, idToken?: string): Promise<IdToken> {\n await this.ensureInitialized();\n return await super.getDecodedIdToken(sessionId, idToken);\n }\n\n override async signIn(...args: any[]): Promise<any> {\n const arg1: any = args[0];\n const arg2: any = args[1];\n const arg3: any = args[2];\n const arg4: any = args[3];\n\n // An embedded sign-in flow payload initiates or continues a `POST /flow/execute` step\n // (identified by `applicationId` for a new flow or `executionId` to continue one). This is\n // distinct from the OAuth authorization_code exchange handled by `super.signIn` below, which\n // is used once the embedded flow completes and returns an authorization code.\n const isEmbeddedFlowPayload: boolean =\n typeof arg1 === 'object' && arg1 !== null && ('executionId' in arg1 || 'applicationId' in arg1);\n\n if (isEmbeddedFlowPayload) {\n await this.ensureInitialized();\n\n // Typed as the Next config rather than `AuthClientConfig<T>` because the server-only\n // `flowSecret` lives on `ThunderIDNodeConfig`, which the generic base config does not expose.\n const configData: ThunderIDNextConfig = (await this.getStorageManager().getConfigData()) as ThunderIDNextConfig;\n\n return executeEmbeddedSignInFlow({\n baseUrl: configData?.baseUrl,\n flowSecret: arg2?.flowSecret ?? configData?.flowSecret,\n payload: arg1,\n url: resolveResourceEndpoint('flowExecute', configData, arg2?.url),\n }) as unknown as Promise<EmbeddedSignInFlowResponse>;\n }\n\n return super.signIn(arg4, arg3, arg1?.code, arg1?.state, arg1) as unknown as Promise<User>;\n }\n\n override async signOut(...args: any[]): Promise<string> {\n if (args[1] && typeof args[1] !== 'string') {\n throw new Error('The second argument must be a string.');\n }\n\n const config: T = await this.getConfiguration();\n const afterSignOutUrl: string = config?.afterSignOutUrl || '/';\n\n const resolvedSessionId: string = args[1] || (await getSessionId())!;\n\n try {\n await (super.signOut as (...a: any[]) => Promise<string>)(resolvedSessionId);\n } catch (error) {\n const message: string = error instanceof Error ? error.message : String(error);\n\n if (\n !message.includes('end_session_endpoint') &&\n !message.includes('sign-out endpoint') &&\n !message.includes('Sign-out endpoint') &&\n !message.includes('Sign-out redirect URL')\n ) {\n throw error;\n }\n }\n\n return afterSignOutUrl;\n }\n\n override async signUp(_options?: SignUpOptions): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-ValidationError-002',\n 'nextjs',\n 'The signUp method is not implemented in the Next.js client.',\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n override signInSilently(_options?: SignInOptions): Promise<User | boolean> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-signInSilently-NotImplementedError-001',\n 'nextjs',\n 'The signInSilently method is not implemented in the Next.js client.',\n );\n }\n\n public async getAuthorizeRequestUrl(\n customParams: ExtendedAuthorizeRequestUrlParams,\n userId?: string,\n ): Promise<string> {\n await this.ensureInitialized();\n return this.getSignInUrl(customParams, userId);\n }\n\n public override getStorageManager(): any {\n return super.getStorageManager();\n }\n\n public override async clearSession(): Promise<void> {\n throw new ThunderIDRuntimeError(\n 'Not implemented',\n 'ThunderIDNextClient-clearSession-NotImplementedError-001',\n 'nextjs',\n 'The clearSession method is not implemented in the Next.js client.',\n );\n }\n\n override async setSession(sessionData: Record<string, unknown>, sessionId?: string): Promise<void> {\n return this.getStorageManager().setSessionData(sessionData, sessionId);\n }\n\n override decodeJwtToken<R = Record<string, unknown>>(token: string): Promise<R> {\n return super.decodeJwtToken<R>(token);\n }\n}\n\nexport default ThunderIDNextClient;\n"],"mappings":";;;;;;;;AAqCA,IAAM,sBAAN,cAAuFA,qCAAuB;CAC5G,AAAO,gBAAgB;CAEvB,AAAO,cAAc;AACnB,SAAO;;CAGT,MAAc,oBAAmC;AAC/C,MAAI,CAAC,KAAK,cAIR,OAAM,KAAK,WAAW,EAAE,CAAM;AAGhC,MAAI,CAAC,KAAK,cACR,OAAM,IAAI,MACR,iLACD;;CAIL,MAAe,WAAW,QAAW,SAAqC;AACxE,MAAI,KAAK,cACP,QAAO,QAAQ,QAAQ,KAAK;EAG9B,MAAM,EACJ,SACA,oBACA,UACA,cACA,YACA,WACA,gBACA,iBACA,UACA,GAAG,SACDC,0CAA0B,OAAO;EAErC,MAAMC,SAAiB,MAAMC,iCAAiB;EAE9C,MAAMC,cAAuB,MAAM,MAAM,WACvC;GACE,GAAG;GACH,gBAAgB,kBAAkB;GAClC,iBAAiB,mBAAmB;GACpC;GACA;GACA;GACA,YAAa,KAAa,cAAc;GACxC;GACA;GACA;GACA;GACD,EACD,QACD;AAED,OAAK,gBAAgB;AAErB,SAAO;;CAGT,MAAe,aAAa,QAAsC;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,UAAU,OAAO,MAAM;AAE9E,OACE,CAAC,QAAQ,SAAS,uBAAuB,IACzC,CAAC,QAAQ,SAAS,oBAAoB,IACtC,CAAC,QAAQ,SAAS,oBAAoB,IACtC,CAAC,QAAQ,SAAS,wBAAwB,CAE1C,OAAM;;AAIV,SAAO;;CAGT,MAAe,OAAO,UAAyC;AAC7D,QAAM,IAAIb,uCACR,mBACA,2CACA,UACA,8DACD;;CAIH,AAAS,eAAe,UAAmD;AACzE,QAAM,IAAIA,uCACR,mBACA,8DACA,UACA,sEACD;;CAGH,MAAa,uBACX,cACA,QACiB;AACjB,QAAM,KAAK,mBAAmB;AAC9B,SAAO,KAAK,aAAa,cAAc,OAAO;;CAGhD,AAAgB,oBAAyB;AACvC,SAAO,MAAM,mBAAmB;;CAGlC,MAAsB,eAA8B;AAClD,QAAM,IAAIA,uCACR,mBACA,4DACA,UACA,oEACD;;CAGH,MAAe,WAAW,aAAsC,WAAmC;AACjG,SAAO,KAAK,mBAAmB,CAAC,eAAe,aAAa,UAAU;;CAGxE,AAAS,eAA4C,OAA2B;AAC9E,SAAO,MAAM,eAAkB,MAAM;;;AAIzC,kCAAe"}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
const require_rolldown_runtime = require('../../../../_virtual/rolldown_runtime.cjs');
|
|
5
5
|
const require_getSessionId = require('../../../../server/actions/getSessionId.cjs');
|
|
6
6
|
const require_useThunderID = require('../../../contexts/ThunderID/useThunderID.cjs');
|
|
7
|
+
const require_VerifyAttribute = require('../VerifyAttribute/VerifyAttribute.cjs');
|
|
7
8
|
let __thunderid_node = require("@thunderid/node");
|
|
8
9
|
__thunderid_node = require_rolldown_runtime.__toESM(__thunderid_node);
|
|
9
10
|
let __thunderid_react = require("@thunderid/react");
|
|
@@ -37,7 +38,7 @@ react_jsx_runtime = require_rolldown_runtime.__toESM(react_jsx_runtime);
|
|
|
37
38
|
* />
|
|
38
39
|
* ```
|
|
39
40
|
*/
|
|
40
|
-
const UserProfile = ({ preferences, editable = true,...rest }) => {
|
|
41
|
+
const UserProfile = ({ preferences, editable = true, verificationFlowHandle = __thunderid_node.AttributeVerificationConstants.DEFAULT_FLOW_HANDLE,...rest }) => {
|
|
41
42
|
const { preferences: contextPreferences } = require_useThunderID.default();
|
|
42
43
|
const { profile, flattenedProfile, onUpdateProfile, updateProfile, userSchema } = (0, __thunderid_react.useUser)();
|
|
43
44
|
const resolvedPreferences = {
|
|
@@ -61,7 +62,16 @@ const UserProfile = ({ preferences, editable = true,...rest }) => {
|
|
|
61
62
|
if (result.success) onUpdateProfile(result.data.user);
|
|
62
63
|
else setError(result.error || t("user.profile.update.generic.error"));
|
|
63
64
|
};
|
|
65
|
+
const renderVerification = ({ attribute, attributeDisplayName, onCancel }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_VerifyAttribute.default, {
|
|
66
|
+
attribute,
|
|
67
|
+
attributeDisplayName,
|
|
68
|
+
flowHandle: verificationFlowHandle,
|
|
69
|
+
preferences: resolvedPreferences,
|
|
70
|
+
onCancel,
|
|
71
|
+
onDone: onCancel
|
|
72
|
+
}, attribute);
|
|
64
73
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__thunderid_react.BaseUserProfile, {
|
|
74
|
+
renderVerification: isEditableProfile ? renderVerification : void 0,
|
|
65
75
|
profile,
|
|
66
76
|
flattenedProfile,
|
|
67
77
|
userSchema,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserProfile.cjs","names":["UserProfile: FC<UserProfileProps>","useThunderID","isEditableProfile: boolean","result: {data: {user: User}; error: string; success: boolean}","getSessionId","BaseUserProfile"],"sources":["../../../../../../src/client/components/account/UserProfile/UserProfile.tsx"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use client';\n\nimport {deepMerge, User} from '@thunderid/node';\nimport {BaseUserProfile
|
|
1
|
+
{"version":3,"file":"UserProfile.cjs","names":["UserProfile: FC<UserProfileProps>","AttributeVerificationConstants","useThunderID","isEditableProfile: boolean","result: {data: {user: User}; error: string; success: boolean}","getSessionId","VerifyAttribute","BaseUserProfile"],"sources":["../../../../../../src/client/components/account/UserProfile/UserProfile.tsx"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use client';\n\nimport {AttributeVerificationConstants, deepMerge, User} from '@thunderid/node';\nimport {\n BaseUserProfile,\n BaseUserProfileProps,\n BaseUserProfileVerificationRenderProps,\n useUser,\n useTranslation,\n} from '@thunderid/react';\nimport {FC, ReactElement, ReactNode, useState} from 'react';\nimport useThunderID from '../../../contexts/ThunderID/useThunderID';\nimport getSessionId from '../../../../server/actions/getSessionId';\nimport VerifyAttribute from '../VerifyAttribute/VerifyAttribute';\n\n/**\n * Props for the UserProfile component.\n * Extends BaseUserProfileProps but makes the user prop optional since it will be obtained from useThunderID\n */\nexport type UserProfileProps = Omit<BaseUserProfileProps, 'user' | 'profile' | 'flattenedProfile'> & {\n /**\n * Handle of the `SELF` flow that verifies an attribute. Defaults to the server's shipped\n * `default-self-attribute-verification-flow`.\n */\n verificationFlowHandle?: string;\n};\n\n/**\n * UserProfile component displays the authenticated user's profile information in a\n * structured and styled format. It shows user details such as display name, email,\n * username, and other available profile information from ThunderID.\n *\n * This component is the React-specific implementation that uses the BaseUserProfile\n * and automatically retrieves the user data from ThunderID context if not provided.\n *\n * @example\n * ```tsx\n * // Basic usage - will use user from ThunderID context\n * <UserProfile />\n *\n * // With explicit user data\n * <UserProfile user={specificUser} />\n *\n * // With card layout and custom fallback\n * <UserProfile\n * cardLayout={true}\n * fallback={<div>Please sign in to view your profile</div>}\n * />\n * ```\n */\nconst UserProfile: FC<UserProfileProps> = ({\n preferences,\n editable = true,\n verificationFlowHandle = AttributeVerificationConstants.DEFAULT_FLOW_HANDLE,\n ...rest\n}: UserProfileProps): ReactElement => {\n const {preferences: contextPreferences} = useThunderID();\n const {profile, flattenedProfile, onUpdateProfile, updateProfile, userSchema} = useUser();\n const resolvedPreferences = {\n ...contextPreferences,\n ...preferences,\n user: {\n ...contextPreferences?.user,\n ...preferences?.user,\n },\n };\n const {t} = useTranslation(resolvedPreferences?.i18n);\n const isEditableProfile: boolean = resolvedPreferences?.user?.fetchUserProfile === false ? false : editable;\n\n const [error, setError] = useState<string | null>(null);\n\n const handleProfileUpdate = async (payload: any): Promise<void> => {\n setError(null);\n\n const updatedAttributes = deepMerge((profile?.['attributes'] as Record<string, unknown>) ?? {}, payload);\n\n Object.keys(updatedAttributes).forEach((key) => {\n if (updatedAttributes[key] === undefined || updatedAttributes[key] === null) {\n delete updatedAttributes[key];\n }\n });\n\n const result: {data: {user: User}; error: string; success: boolean} = await updateProfile(\n {payload: updatedAttributes},\n await getSessionId(),\n );\n\n if (result.success) {\n onUpdateProfile(result.data.user);\n } else {\n setError(result.error || t('user.profile.update.generic.error'));\n }\n };\n\n const renderVerification = ({\n attribute,\n attributeDisplayName,\n onCancel,\n }: BaseUserProfileVerificationRenderProps): ReactNode => (\n <VerifyAttribute\n key={attribute}\n attribute={attribute}\n attributeDisplayName={attributeDisplayName}\n flowHandle={verificationFlowHandle}\n preferences={resolvedPreferences}\n onCancel={onCancel}\n onDone={onCancel}\n />\n );\n\n return (\n <BaseUserProfile\n renderVerification={isEditableProfile ? renderVerification : undefined}\n profile={profile!}\n flattenedProfile={flattenedProfile!}\n userSchema={userSchema}\n editable={isEditableProfile}\n onUpdate={isEditableProfile ? handleProfileUpdate : undefined}\n error={error}\n preferences={resolvedPreferences}\n {...rest}\n />\n );\n};\n\nexport default UserProfile;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAMA,eAAqC,EACzC,aACA,WAAW,MACX,yBAAyBC,gDAA+B,oBACxD,GAAG,WACiC;CACpC,MAAM,EAAC,aAAa,uBAAsBC,8BAAc;CACxD,MAAM,EAAC,SAAS,kBAAkB,iBAAiB,eAAe,+CAAuB;CACzF,MAAM,sBAAsB;EAC1B,GAAG;EACH,GAAG;EACH,MAAM;GACJ,GAAG,oBAAoB;GACvB,GAAG,aAAa;GACjB;EACF;CACD,MAAM,EAAC,4CAAoB,qBAAqB,KAAK;CACrD,MAAMC,oBAA6B,qBAAqB,MAAM,qBAAqB,QAAQ,QAAQ;CAEnG,MAAM,CAAC,OAAO,gCAAoC,KAAK;CAEvD,MAAM,sBAAsB,OAAO,YAAgC;AACjE,WAAS,KAAK;EAEd,MAAM,oDAA+B,UAAU,iBAA6C,EAAE,EAAE,QAAQ;AAExG,SAAO,KAAK,kBAAkB,CAAC,SAAS,QAAQ;AAC9C,OAAI,kBAAkB,SAAS,UAAa,kBAAkB,SAAS,KACrE,QAAO,kBAAkB;IAE3B;EAEF,MAAMC,SAAgE,MAAM,cAC1E,EAAC,SAAS,mBAAkB,EAC5B,MAAMC,8BAAc,CACrB;AAED,MAAI,OAAO,QACT,iBAAgB,OAAO,KAAK,KAAK;MAEjC,UAAS,OAAO,SAAS,EAAE,oCAAoC,CAAC;;CAIpE,MAAM,sBAAsB,EAC1B,WACA,sBACA,eAEA,2CAACC;EAEY;EACW;EACtB,YAAY;EACZ,aAAa;EACH;EACV,QAAQ;IANH,UAOL;AAGJ,QACE,2CAACC;EACC,oBAAoB,oBAAoB,qBAAqB;EACpD;EACS;EACN;EACZ,UAAU;EACV,UAAU,oBAAoB,sBAAsB;EAC7C;EACP,aAAa;EACb,GAAI;GACJ;;AAIN,0BAAe"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
const require_rolldown_runtime = require('../../../../_virtual/rolldown_runtime.cjs');
|
|
5
|
+
const require_useThunderID = require('../../../contexts/ThunderID/useThunderID.cjs');
|
|
6
|
+
const require_executeSelfFlowAction = require('../../../../server/actions/auth/executeSelfFlowAction.cjs');
|
|
7
|
+
let __thunderid_node = require("@thunderid/node");
|
|
8
|
+
__thunderid_node = require_rolldown_runtime.__toESM(__thunderid_node);
|
|
9
|
+
let __thunderid_react = require("@thunderid/react");
|
|
10
|
+
__thunderid_react = require_rolldown_runtime.__toESM(__thunderid_react);
|
|
11
|
+
let react = require("react");
|
|
12
|
+
react = require_rolldown_runtime.__toESM(react);
|
|
13
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
14
|
+
react_jsx_runtime = require_rolldown_runtime.__toESM(react_jsx_runtime);
|
|
15
|
+
|
|
16
|
+
//#region src/client/components/account/VerifyAttribute/VerifyAttribute.tsx
|
|
17
|
+
const execute = async (payload) => {
|
|
18
|
+
const result = await require_executeSelfFlowAction.default(payload);
|
|
19
|
+
if (!result.success) throw new __thunderid_node.ThunderIDAPIError("SELF flow request failed", "VerifyAttribute-execute-ResponseError-001", "nextjs", result.statusCode);
|
|
20
|
+
return result.data;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* VerifyAttribute verifies one of the signed-in user's attributes, such as their email address, by
|
|
24
|
+
* running a self attribute verification flow named by `flowHandle`.
|
|
25
|
+
*
|
|
26
|
+
* This is the Next.js-specific implementation: it renders `BaseVerifyAttribute` from
|
|
27
|
+
* `@thunderid/react`, but runs every step through `executeSelfFlowAction` (a server action that
|
|
28
|
+
* attaches the server-held session's access token) instead of calling the ThunderID server from the
|
|
29
|
+
* browser. Once the server records the verification, and when the user selects Done after a link is
|
|
30
|
+
* sent, it re-reads the user's profile.
|
|
31
|
+
*
|
|
32
|
+
* Mount it with a `key` per attribute: each mount starts a new verification and sends a new code or
|
|
33
|
+
* link.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```tsx
|
|
37
|
+
* <VerifyAttribute attribute="email" onComplete={() => setOpen(false)} onCancel={() => setOpen(false)} />
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
const VerifyAttribute = ({ attribute, attributeDisplayName, flowHandle = __thunderid_node.AttributeVerificationConstants.DEFAULT_FLOW_HANDLE, onComplete, onDone,...rest }) => {
|
|
41
|
+
const { isLoading } = require_useThunderID.default();
|
|
42
|
+
const { revalidateProfile, userSchema } = (0, __thunderid_react.useUser)();
|
|
43
|
+
const refreshProfile = (0, react.useCallback)(async () => {
|
|
44
|
+
try {
|
|
45
|
+
await revalidateProfile?.();
|
|
46
|
+
} catch {}
|
|
47
|
+
}, [revalidateProfile]);
|
|
48
|
+
const handleInitialize = (0, react.useCallback)(() => {
|
|
49
|
+
if (!(0, __thunderid_node.isVerifiableAttribute)(userSchema, attribute)) return Promise.reject(new __thunderid_node.ThunderIDRuntimeError(`Attribute "${attribute}" is not a verifiable email or mobile attribute.`, "VerifyAttribute-handleInitialize-RuntimeError-001", "nextjs", "Only a top-level, single-valued email or mobile attribute of the user schema can be verified."));
|
|
50
|
+
return execute({
|
|
51
|
+
flowType: __thunderid_node.EmbeddedFlowType.Self,
|
|
52
|
+
handle: flowHandle,
|
|
53
|
+
inputs: { [__thunderid_node.AttributeVerificationConstants.ATTRIBUTE_INPUT]: attribute }
|
|
54
|
+
});
|
|
55
|
+
}, [
|
|
56
|
+
attribute,
|
|
57
|
+
flowHandle,
|
|
58
|
+
userSchema
|
|
59
|
+
]);
|
|
60
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__thunderid_react.BaseVerifyAttribute, {
|
|
61
|
+
...rest,
|
|
62
|
+
attributeDisplayName: attributeDisplayName ?? userSchema?.[attribute]?.displayName ?? (0, __thunderid_node.startCase)(attribute),
|
|
63
|
+
isInitialized: !isLoading,
|
|
64
|
+
onInitialize: handleInitialize,
|
|
65
|
+
onSubmit: execute,
|
|
66
|
+
onComplete: (response) => {
|
|
67
|
+
refreshProfile();
|
|
68
|
+
onComplete?.(response);
|
|
69
|
+
},
|
|
70
|
+
onDone: () => {
|
|
71
|
+
refreshProfile();
|
|
72
|
+
onDone?.();
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
var VerifyAttribute_default = VerifyAttribute;
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
exports.default = VerifyAttribute_default;
|
|
80
|
+
//# sourceMappingURL=VerifyAttribute.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VerifyAttribute.cjs","names":["result: ExecuteSelfFlowActionResult","executeSelfFlowAction","ThunderIDAPIError","VerifyAttribute: FC<VerifyAttributeProps>","AttributeVerificationConstants","useThunderID","ThunderIDRuntimeError","EmbeddedFlowType","BaseVerifyAttribute"],"sources":["../../../../../../src/client/components/account/VerifyAttribute/VerifyAttribute.tsx"],"sourcesContent":["// Copyright 2026 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use client';\n\nimport {\n AttributeVerificationConstants,\n EmbeddedFlowType,\n EmbeddedSelfFlowRequest,\n EmbeddedSelfFlowResponse,\n ThunderIDAPIError,\n ThunderIDRuntimeError,\n isVerifiableAttribute,\n startCase,\n} from '@thunderid/node';\nimport {BaseVerifyAttribute, BaseVerifyAttributeProps, useUser} from '@thunderid/react';\nimport {FC, ReactElement, useCallback} from 'react';\nimport executeSelfFlowAction, {\n ExecuteSelfFlowActionResult,\n} from '../../../../server/actions/auth/executeSelfFlowAction';\nimport useThunderID from '../../../contexts/ThunderID/useThunderID';\n\n/**\n * Props for the VerifyAttribute component.\n * Mirrors `@thunderid/react`'s `VerifyAttributeProps`, so a consumer moving between the React and\n * Next.js SDKs doesn't need to change how they call it.\n */\nexport type VerifyAttributeProps = Omit<BaseVerifyAttributeProps, 'onInitialize' | 'onSubmit' | 'isInitialized'> & {\n /**\n * Name of the signed-in user's attribute to verify, such as `email`. Only a top-level, single-valued\n * `email` or `mobile` property of the user's schema can be verified; any other is refused without a\n * request, through `onError`, with `VerifyAttribute-handleInitialize-RuntimeError-001`.\n */\n attribute: string;\n /**\n * Handle of the `SELF` flow to run. Defaults to the server's shipped\n * `default-self-attribute-verification-flow`.\n */\n flowHandle?: string;\n};\n\n// Runs one step through the server action, which attaches the session's access token. A failure\n// raises `VerifyAttribute-execute-ResponseError-001` with the refusal's status, never the server's reply.\nconst execute = async (payload: EmbeddedSelfFlowRequest): Promise<EmbeddedSelfFlowResponse> => {\n const result: ExecuteSelfFlowActionResult = await executeSelfFlowAction(payload);\n\n if (!result.success) {\n throw new ThunderIDAPIError(\n 'SELF flow request failed',\n 'VerifyAttribute-execute-ResponseError-001',\n 'nextjs',\n result.statusCode,\n );\n }\n\n return result.data;\n};\n\n/**\n * VerifyAttribute verifies one of the signed-in user's attributes, such as their email address, by\n * running a self attribute verification flow named by `flowHandle`.\n *\n * This is the Next.js-specific implementation: it renders `BaseVerifyAttribute` from\n * `@thunderid/react`, but runs every step through `executeSelfFlowAction` (a server action that\n * attaches the server-held session's access token) instead of calling the ThunderID server from the\n * browser. Once the server records the verification, and when the user selects Done after a link is\n * sent, it re-reads the user's profile.\n *\n * Mount it with a `key` per attribute: each mount starts a new verification and sends a new code or\n * link.\n *\n * @example\n * ```tsx\n * <VerifyAttribute attribute=\"email\" onComplete={() => setOpen(false)} onCancel={() => setOpen(false)} />\n * ```\n */\nconst VerifyAttribute: FC<VerifyAttributeProps> = ({\n attribute,\n attributeDisplayName,\n flowHandle = AttributeVerificationConstants.DEFAULT_FLOW_HANDLE,\n onComplete,\n onDone,\n ...rest\n}: VerifyAttributeProps): ReactElement => {\n const {isLoading} = useThunderID();\n const {revalidateProfile, userSchema} = useUser();\n\n // Re-reads the profile so the recorded verification shows; a failure leaves it stale, not broken.\n const refreshProfile = useCallback(async (): Promise<void> => {\n try {\n await revalidateProfile?.();\n } catch {\n // Non-fatal: the profile stays stale until the next re-read.\n }\n }, [revalidateProfile]);\n\n const handleInitialize = useCallback((): Promise<EmbeddedSelfFlowResponse> => {\n if (!isVerifiableAttribute(userSchema, attribute)) {\n return Promise.reject(\n new ThunderIDRuntimeError(\n `Attribute \"${attribute}\" is not a verifiable email or mobile attribute.`,\n 'VerifyAttribute-handleInitialize-RuntimeError-001',\n 'nextjs',\n 'Only a top-level, single-valued email or mobile attribute of the user schema can be verified.',\n ),\n );\n }\n\n return execute({\n flowType: EmbeddedFlowType.Self,\n handle: flowHandle,\n inputs: {[AttributeVerificationConstants.ATTRIBUTE_INPUT]: attribute},\n });\n }, [attribute, flowHandle, userSchema]);\n\n return (\n <BaseVerifyAttribute\n {...rest}\n attributeDisplayName={attributeDisplayName ?? userSchema?.[attribute]?.displayName ?? startCase(attribute)}\n // The schema decides whether the attribute can be verified, so wait for the session to load.\n isInitialized={!isLoading}\n onInitialize={handleInitialize}\n onSubmit={execute}\n onComplete={(response: EmbeddedSelfFlowResponse): void => {\n void refreshProfile();\n onComplete?.(response);\n }}\n onDone={(): void => {\n void refreshProfile();\n onDone?.();\n }}\n />\n );\n};\n\nexport default VerifyAttribute;\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,MAAM,UAAU,OAAO,YAAwE;CAC7F,MAAMA,SAAsC,MAAMC,sCAAsB,QAAQ;AAEhF,KAAI,CAAC,OAAO,QACV,OAAM,IAAIC,mCACR,4BACA,6CACA,UACA,OAAO,WACR;AAGH,QAAO,OAAO;;;;;;;;;;;;;;;;;;;;AAqBhB,MAAMC,mBAA6C,EACjD,WACA,sBACA,aAAaC,gDAA+B,qBAC5C,YACA,OACA,GAAG,WACqC;CACxC,MAAM,EAAC,cAAaC,8BAAc;CAClC,MAAM,EAAC,mBAAmB,+CAAuB;CAGjD,MAAM,wCAA6B,YAA2B;AAC5D,MAAI;AACF,SAAM,qBAAqB;UACrB;IAGP,CAAC,kBAAkB,CAAC;CAEvB,MAAM,gDAAwE;AAC5E,MAAI,6CAAuB,YAAY,UAAU,CAC/C,QAAO,QAAQ,OACb,IAAIC,uCACF,cAAc,UAAU,mDACxB,qDACA,UACA,gGACD,CACF;AAGH,SAAO,QAAQ;GACb,UAAUC,kCAAiB;GAC3B,QAAQ;GACR,QAAQ,GAAEH,gDAA+B,kBAAkB,WAAU;GACtE,CAAC;IACD;EAAC;EAAW;EAAY;EAAW,CAAC;AAEvC,QACE,2CAACI;EACC,GAAI;EACJ,sBAAsB,wBAAwB,aAAa,YAAY,+CAAyB,UAAU;EAE1G,eAAe,CAAC;EAChB,cAAc;EACd,UAAU;EACV,aAAa,aAA6C;AACxD,GAAK,gBAAgB;AACrB,gBAAa,SAAS;;EAExB,cAAoB;AAClB,GAAK,gBAAgB;AACrB,aAAU;;GAEZ;;AAIN,8BAAe"}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs');
|
|
5
|
+
const require_getSessionId = require('../../../server/actions/getSessionId.cjs');
|
|
6
|
+
const require_getUserProfileAction = require('../../../server/actions/account/getUserProfileAction.cjs');
|
|
5
7
|
const require_logger = require('../../../utils/logger.cjs');
|
|
6
8
|
const require_ThunderIDContext = require('./ThunderIDContext.cjs');
|
|
7
9
|
const require_fetchFlowMetaFromServer = require('../../fetchFlowMetaFromServer.cjs');
|
|
@@ -145,6 +147,15 @@ const ThunderIDClientProvider = ({ baseUrl, children, endpoints, signIn, clearSe
|
|
|
145
147
|
profile: payload
|
|
146
148
|
}));
|
|
147
149
|
};
|
|
150
|
+
/**
|
|
151
|
+
* Re-reads `/users/me` through the server-held session, so a change made outside the profile API,
|
|
152
|
+
* such as a recorded verification, shows.
|
|
153
|
+
*/
|
|
154
|
+
const revalidateProfile = async () => {
|
|
155
|
+
if (preferences?.user?.fetchUserProfile === false) return;
|
|
156
|
+
const result = await require_getUserProfileAction.default(await require_getSessionId.default() ?? "");
|
|
157
|
+
if (result.success) handleProfileUpdate(result.data.userProfile.profile);
|
|
158
|
+
};
|
|
148
159
|
const unsupported = (name) => {
|
|
149
160
|
return () => Promise.reject(new __thunderid_node.ThunderIDRuntimeError(`\`${name}\` is not supported in @thunderid/nextjs.`, `ThunderIDClientProvider-${name}-NotSupportedError-001`, "nextjs"));
|
|
150
161
|
};
|
|
@@ -220,6 +231,7 @@ const ThunderIDClientProvider = ({ baseUrl, children, endpoints, signIn, clearSe
|
|
|
220
231
|
profile: userProfile,
|
|
221
232
|
userSchema,
|
|
222
233
|
onUpdateProfile: handleProfileUpdate,
|
|
234
|
+
revalidateProfile,
|
|
223
235
|
updateProfile,
|
|
224
236
|
children
|
|
225
237
|
}) })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThunderIDProvider.cjs","names":["ThunderIDClientProvider: FC<PropsWithChildren<ThunderIDClientProviderProps>>","reRenderCheckRef: RefObject<boolean>","router: AppRouterInstance","searchParams: ReadonlyURLSearchParams","code: string | null","state: string | null","result: {error?: string; redirectUrl?: string; success: boolean}","ThunderIDRuntimeError","result: any","contextValue: ThunderIDContextProps","reactContextValue: ReactThunderIDContextProps","fetchManagementFromServer","ThunderIDContext","ReactThunderIDContext","I18nProvider","FlowMetaProvider","fetchFlowMetaFromServer","ThemeProvider","FlowProvider","UserProvider"],"sources":["../../../../../src/client/contexts/ThunderID/ThunderIDProvider.tsx"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use client';\n\nimport {\n AttributeSchema,\n EmbeddedFlowExecuteRequestConfig,\n FlowMetadataResponse,\n generateFlattenedUserProfile,\n UpdateMeProfileConfig,\n User,\n UserProfile,\n ThunderIDRuntimeError,\n getVendorPrefix,\n} from '@thunderid/node';\nimport {\n I18nProvider,\n FlowMetaProvider,\n FlowProvider,\n UserProvider,\n ThemeProvider,\n ThunderIDContext as ReactThunderIDContext,\n ThunderIDContextProps as ReactThunderIDContextProps,\n ThunderIDProviderProps,\n} from '@thunderid/react';\nimport {ReadonlyURLSearchParams} from 'next/dist/client/components/navigation.react-server';\nimport {AppRouterInstance} from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport {useRouter, useSearchParams} from 'next/navigation';\nimport {FC, PropsWithChildren, RefObject, useEffect, useMemo, useRef, useState} from 'react';\nimport ThunderIDContext, {ThunderIDContextProps} from './ThunderIDContext';\nimport {RefreshResult} from '../../../server/actions/refreshToken';\nimport logger from '../../../utils/logger';\nimport fetchFlowMetaFromServer from '../../fetchFlowMetaFromServer';\nimport fetchManagementFromServer from '../../fetchManagementFromServer';\n\n/**\n * Props interface of {@link ThunderIDClientProvider}\n */\nexport type ThunderIDClientProviderProps = Partial<Omit<ThunderIDProviderProps, 'baseUrl' | 'clientId'>> &\n Pick<ThunderIDProviderProps, 'baseUrl' | 'clientId'> & {\n applicationId: ThunderIDContextProps['applicationId'];\n clearSession: () => Promise<void>;\n handleOAuthCallback: (\n code: string,\n state: string,\n ) => Promise<{error?: string; redirectUrl?: string; success: boolean}>;\n /**\n * Flow metadata fetched server-side ahead of time, seeding `FlowMetaProvider` so it can skip\n * its own initial client-side fetch (avoiding a flash of untranslated i18n keys).\n */\n initialMeta?: FlowMetadataResponse | null;\n isSignedIn: boolean;\n organizationHandle: ThunderIDContextProps['organizationHandle'];\n refreshToken: () => Promise<RefreshResult>;\n signIn: ThunderIDContextProps['signIn'];\n signOut: ThunderIDContextProps['signOut'];\n signUp: ThunderIDContextProps['signUp'];\n updateProfile: (\n requestConfig: UpdateMeProfileConfig,\n sessionId?: string,\n ) => Promise<{data: {user: User}; error: string; success: boolean}>;\n user: User | null;\n userProfile: UserProfile;\n userSchema?: Record<string, AttributeSchema> | null;\n };\n\nconst ThunderIDClientProvider: FC<PropsWithChildren<ThunderIDClientProviderProps>> = ({\n baseUrl,\n children,\n endpoints,\n signIn,\n clearSession,\n refreshToken,\n signOut,\n signUp,\n handleOAuthCallback,\n preferences,\n isSignedIn,\n signInUrl,\n signUpUrl,\n user: _user,\n userProfile: _userProfile,\n userSchema: _userSchema = null,\n updateProfile,\n applicationId,\n organizationHandle,\n scopes,\n vendor,\n initialMeta = null,\n}: PropsWithChildren<ThunderIDClientProviderProps>) => {\n const reRenderCheckRef: RefObject<boolean> = useRef(false);\n const router: AppRouterInstance = useRouter();\n const searchParams: ReadonlyURLSearchParams = useSearchParams();\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [user, setUser] = useState<User | null>(_user);\n const [userProfile, setUserProfile] = useState<UserProfile>(_userProfile);\n const [userSchema, setUserSchema] = useState<Record<string, AttributeSchema> | null>(_userSchema);\n\n useEffect(() => {\n setUserProfile(_userProfile);\n }, [_userProfile]);\n\n useEffect(() => {\n setUserSchema(_userSchema);\n }, [_userSchema]);\n\n useEffect(() => {\n setUser(_user);\n }, [_user]);\n\n // Handle OAuth callback automatically\n useEffect(() => {\n // React 18.x Strict.Mode has a new check for `Ensuring reusable state` to facilitate an upcoming react feature.\n // https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state\n // This will remount all the useEffects to ensure that there are no unexpected side effects.\n // When react remounts the signIn hook of the AuthProvider, it will cause a race condition. Hence, we have to\n // prevent the re-render of this hook as suggested in the following discussion.\n // https://github.com/reactwg/react-18/discussions/18#discussioncomment-795623\n if (reRenderCheckRef.current) {\n return;\n }\n\n reRenderCheckRef.current = true;\n\n // Don't handle callback if already signed in\n if (isSignedIn) return;\n\n (async (): Promise<void> => {\n try {\n const code: string | null = searchParams.get('code');\n const state: string | null = searchParams.get('state');\n const error: string | null = searchParams.get('error');\n\n // Check for OAuth errors first\n if (error) {\n logger.error('[ThunderIDClientProvider] An error was received for the initiated sign-in request.');\n\n return;\n }\n\n // Handle OAuth callback if code and state are present\n if (code && state) {\n setIsLoading(true);\n\n const result: {error?: string; redirectUrl?: string; success: boolean} = await handleOAuthCallback(\n code,\n state,\n );\n\n if (result.success) {\n // Redirect to the success URL\n if (result.redirectUrl) {\n router.push(result.redirectUrl);\n } else {\n // Refresh the page to update authentication state\n window.location.reload();\n }\n } else {\n logger.error(\n `[ThunderIDClientProvider] An error occurred while signing in: ${result.error || 'Authentication failed'}`,\n );\n }\n }\n } catch (error) {\n logger.error('[ThunderIDClientProvider] Failed to handle OAuth callback:', error);\n }\n })();\n }, []);\n\n useEffect(() => {\n // Set loading to false when server has resolved authentication state\n setIsLoading(false);\n }, [isSignedIn, user]);\n\n const handleSignIn = async (payload: any, request: EmbeddedFlowExecuteRequestConfig): Promise<any> => {\n if (!signIn) {\n throw new ThunderIDRuntimeError(\n '`signIn` function is not available.',\n 'ThunderIDClientProvider-handleSignIn-RuntimeError-001',\n 'nextjs',\n );\n }\n\n const result: any = await signIn(payload, request);\n\n // Redirect based flow URL is sent as `signInUrl` in the response.\n // Use window.location.href instead of router.push() — the OAuth authorization\n // endpoint is on an external server, and router.push() would send RSC fetch\n // headers that the identity provider doesn't understand, causing a CORS error.\n if (result?.data?.signInUrl) {\n window.location.href = result.data.signInUrl;\n\n return undefined;\n }\n\n // After the Embedded flow is successful, the URL to navigate next is sent as `afterSignInUrl` in the response.\n if (result?.data?.afterSignInUrl) {\n router.push(result.data.afterSignInUrl);\n\n return undefined;\n }\n\n if (result?.error) {\n throw new Error(result.error);\n }\n\n return result?.data ?? result;\n };\n\n const handleSignUp = async (payload: any, request: EmbeddedFlowExecuteRequestConfig): Promise<any> => {\n if (!signUp) {\n throw new ThunderIDRuntimeError(\n '`signUp` function is not available.',\n 'ThunderIDClientProvider-handleSignUp-RuntimeError-001',\n 'nextjs',\n );\n }\n\n const result: any = await signUp(payload, request);\n\n // Redirect based flow URL is sent as `signUpUrl` in the response.\n if (result?.data?.signUpUrl) {\n router.push(result.data.signUpUrl);\n\n return undefined;\n }\n\n // After the Embedded flow is successful, the URL to navigate next is sent as `afterSignUpUrl` in the response.\n if (result?.data?.afterSignUpUrl) {\n router.push(result.data.afterSignUpUrl);\n\n return undefined;\n }\n\n if (result?.error) {\n throw new Error(result.error);\n }\n\n return result?.data ?? result;\n };\n\n const handleSignOut = async (): Promise<any> => {\n logger.debug('[ThunderIDClientProvider][handleSignOut] `handleSignOut` called.');\n\n try {\n const result: any = await signOut();\n\n logger.debug('[ThunderIDClientProvider][handleSignOut] Sign out result:', result);\n\n if (result?.data?.afterSignOutUrl) {\n router.push(result.data.afterSignOutUrl);\n\n return {location: result.data.afterSignOutUrl, redirected: true};\n }\n\n if (result?.error) {\n logger.error(\n '[ThunderIDClientProvider][handleSignOut] Error result was returned during signing the user out with a button click:',\n result.error,\n );\n }\n\n return result?.data ?? result;\n } catch (error) {\n logger.error(\n '[ThunderIDClientProvider][handleSignOut] Error occurred during signing the user out with a button click:',\n error,\n );\n\n return undefined;\n }\n };\n\n const contextValue: ThunderIDContextProps = useMemo(\n () => ({\n applicationId,\n baseUrl,\n clearSession,\n isLoading,\n isSignedIn,\n organizationHandle,\n preferences,\n refreshToken,\n scopes,\n signIn: handleSignIn,\n signInUrl,\n signOut: handleSignOut,\n signUp: handleSignUp,\n signUpUrl,\n user,\n }),\n [\n baseUrl,\n user,\n isSignedIn,\n isLoading,\n signInUrl,\n signUpUrl,\n applicationId,\n organizationHandle,\n scopes,\n preferences,\n ],\n );\n\n const handleProfileUpdate = (payload: User): void => {\n setUser(payload);\n setUserProfile((prev: UserProfile) => ({\n ...prev,\n flattenedProfile: generateFlattenedUserProfile(payload),\n profile: payload,\n }));\n };\n\n // Bridge into @thunderid/react's own ThunderIDContext. Internal react components rendered by\n // BaseSignIn/BaseSignUp — most notably FlowMetaProvider, which fetches `/flow/meta` and injects\n // its i18n bundle — call react's `useThunderID()` directly. Without this bridge they'd only see\n // react's context default (applicationId/baseUrl undefined, isInitialized false), so the meta\n // fetch would never fire and flow labels would render as untranslated i18n keys. Fields with no\n // nextjs equivalent (token/http helpers meant for direct browser API calls) are stubbed out,\n // since nextjs routes those operations through server actions instead.\n const unsupported = (name: string): (() => Promise<never>) => {\n return () =>\n Promise.reject(\n new ThunderIDRuntimeError(\n `\\`${name}\\` is not supported in @thunderid/nextjs.`,\n `ThunderIDClientProvider-${name}-NotSupportedError-001`,\n 'nextjs',\n ),\n );\n };\n\n const reactContextValue: ReactThunderIDContextProps = useMemo(\n () => ({\n afterSignInUrl: undefined,\n applicationId,\n baseUrl,\n clearSession,\n clientId: undefined,\n discovery: {wellKnown: null},\n // Only the management collection overrides arrive here, so the admin hooks build the URLs the\n // management server action accepts.\n endpoints,\n exchangeToken: unsupported('exchangeToken'),\n getAccessToken: unsupported('getAccessToken'),\n getDecodedIdToken: unsupported('getDecodedIdToken'),\n // The Next.js useGrantedPermissions reads them through a server action instead.\n getGrantedPermissions: unsupported('getGrantedPermissions'),\n getIdToken: unsupported('getIdToken'),\n getStorageManager: () => Promise.resolve(null),\n http: {\n // The admin components and hooks send management requests through a server action that adds\n // the server-held access token, so the token never reaches the browser.\n fetcher: fetchManagementFromServer,\n request: unsupported('http.request'),\n requestAll: unsupported('http.requestAll'),\n },\n instanceId: 0,\n isInitialized: !isLoading,\n isLoading,\n isMetaLoading: false,\n isSignedIn,\n meta: initialMeta ?? null,\n organizationHandle,\n reInitialize: unsupported('reInitialize'),\n recover: unsupported('recover'),\n resolveFlowTemplateLiterals: (text: string | undefined): string => text ?? '',\n scopes,\n signIn: handleSignIn,\n signInSilently: unsupported('signInSilently'),\n signInUrl,\n signOut: handleSignOut,\n signUp: handleSignUp,\n signUpUrl,\n user,\n userSchema,\n vendor: getVendorPrefix(vendor),\n }),\n [\n applicationId,\n baseUrl,\n clearSession,\n endpoints,\n isLoading,\n isSignedIn,\n organizationHandle,\n scopes,\n signInUrl,\n signUpUrl,\n user,\n userSchema,\n initialMeta,\n vendor,\n ],\n );\n\n return (\n <ThunderIDContext.Provider value={contextValue}>\n <ReactThunderIDContext.Provider value={reactContextValue}>\n <I18nProvider preferences={preferences?.i18n}>\n <FlowMetaProvider\n enabled={preferences?.resolveFromMeta !== false}\n initialMeta={initialMeta}\n fetchMeta={fetchFlowMetaFromServer}\n >\n <ThemeProvider theme={preferences?.theme?.overrides} mode={preferences?.theme?.mode}>\n <FlowProvider>\n <UserProvider\n profile={userProfile}\n userSchema={userSchema}\n onUpdateProfile={handleProfileUpdate}\n updateProfile={updateProfile}\n >\n {children}\n </UserProvider>\n </FlowProvider>\n </ThemeProvider>\n </FlowMetaProvider>\n </I18nProvider>\n </ReactThunderIDContext.Provider>\n </ThunderIDContext.Provider>\n );\n};\n\nexport default ThunderIDClientProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmEA,MAAMA,2BAAgF,EACp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C,SAAS;OACG;OACZ,iBAAiB;OACF;OAEd;QACY,GACF;OACD;MACC;KACN;IACgB;GACP;;AAIhC,gCAAe"}
|
|
1
|
+
{"version":3,"file":"ThunderIDProvider.cjs","names":["ThunderIDClientProvider: FC<PropsWithChildren<ThunderIDClientProviderProps>>","reRenderCheckRef: RefObject<boolean>","router: AppRouterInstance","searchParams: ReadonlyURLSearchParams","code: string | null","state: string | null","result: {error?: string; redirectUrl?: string; success: boolean}","ThunderIDRuntimeError","result: any","contextValue: ThunderIDContextProps","result: Awaited<ReturnType<typeof getUserProfileAction>>","getUserProfileAction","getSessionId","reactContextValue: ReactThunderIDContextProps","fetchManagementFromServer","ThunderIDContext","ReactThunderIDContext","I18nProvider","FlowMetaProvider","fetchFlowMetaFromServer","ThemeProvider","FlowProvider","UserProvider"],"sources":["../../../../../src/client/contexts/ThunderID/ThunderIDProvider.tsx"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use client';\n\nimport {\n AttributeSchema,\n EmbeddedFlowExecuteRequestConfig,\n FlowMetadataResponse,\n generateFlattenedUserProfile,\n UpdateMeProfileConfig,\n User,\n UserProfile,\n ThunderIDRuntimeError,\n getVendorPrefix,\n} from '@thunderid/node';\nimport {\n I18nProvider,\n FlowMetaProvider,\n FlowProvider,\n UserProvider,\n ThemeProvider,\n ThunderIDContext as ReactThunderIDContext,\n ThunderIDContextProps as ReactThunderIDContextProps,\n ThunderIDProviderProps,\n} from '@thunderid/react';\nimport {ReadonlyURLSearchParams} from 'next/dist/client/components/navigation.react-server';\nimport {AppRouterInstance} from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport {useRouter, useSearchParams} from 'next/navigation';\nimport {FC, PropsWithChildren, RefObject, useEffect, useMemo, useRef, useState} from 'react';\nimport ThunderIDContext, {ThunderIDContextProps} from './ThunderIDContext';\nimport getUserProfileAction from '../../../server/actions/account/getUserProfileAction';\nimport getSessionId from '../../../server/actions/getSessionId';\nimport {RefreshResult} from '../../../server/actions/refreshToken';\nimport logger from '../../../utils/logger';\nimport fetchFlowMetaFromServer from '../../fetchFlowMetaFromServer';\nimport fetchManagementFromServer from '../../fetchManagementFromServer';\n\n/**\n * Props interface of {@link ThunderIDClientProvider}\n */\nexport type ThunderIDClientProviderProps = Partial<Omit<ThunderIDProviderProps, 'baseUrl' | 'clientId'>> &\n Pick<ThunderIDProviderProps, 'baseUrl' | 'clientId'> & {\n applicationId: ThunderIDContextProps['applicationId'];\n clearSession: () => Promise<void>;\n handleOAuthCallback: (\n code: string,\n state: string,\n ) => Promise<{error?: string; redirectUrl?: string; success: boolean}>;\n /**\n * Flow metadata fetched server-side ahead of time, seeding `FlowMetaProvider` so it can skip\n * its own initial client-side fetch (avoiding a flash of untranslated i18n keys).\n */\n initialMeta?: FlowMetadataResponse | null;\n isSignedIn: boolean;\n organizationHandle: ThunderIDContextProps['organizationHandle'];\n refreshToken: () => Promise<RefreshResult>;\n signIn: ThunderIDContextProps['signIn'];\n signOut: ThunderIDContextProps['signOut'];\n signUp: ThunderIDContextProps['signUp'];\n updateProfile: (\n requestConfig: UpdateMeProfileConfig,\n sessionId?: string,\n ) => Promise<{data: {user: User}; error: string; success: boolean}>;\n user: User | null;\n userProfile: UserProfile;\n userSchema?: Record<string, AttributeSchema> | null;\n };\n\nconst ThunderIDClientProvider: FC<PropsWithChildren<ThunderIDClientProviderProps>> = ({\n baseUrl,\n children,\n endpoints,\n signIn,\n clearSession,\n refreshToken,\n signOut,\n signUp,\n handleOAuthCallback,\n preferences,\n isSignedIn,\n signInUrl,\n signUpUrl,\n user: _user,\n userProfile: _userProfile,\n userSchema: _userSchema = null,\n updateProfile,\n applicationId,\n organizationHandle,\n scopes,\n vendor,\n initialMeta = null,\n}: PropsWithChildren<ThunderIDClientProviderProps>) => {\n const reRenderCheckRef: RefObject<boolean> = useRef(false);\n const router: AppRouterInstance = useRouter();\n const searchParams: ReadonlyURLSearchParams = useSearchParams();\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [user, setUser] = useState<User | null>(_user);\n const [userProfile, setUserProfile] = useState<UserProfile>(_userProfile);\n const [userSchema, setUserSchema] = useState<Record<string, AttributeSchema> | null>(_userSchema);\n\n useEffect(() => {\n setUserProfile(_userProfile);\n }, [_userProfile]);\n\n useEffect(() => {\n setUserSchema(_userSchema);\n }, [_userSchema]);\n\n useEffect(() => {\n setUser(_user);\n }, [_user]);\n\n // Handle OAuth callback automatically\n useEffect(() => {\n // React 18.x Strict.Mode has a new check for `Ensuring reusable state` to facilitate an upcoming react feature.\n // https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state\n // This will remount all the useEffects to ensure that there are no unexpected side effects.\n // When react remounts the signIn hook of the AuthProvider, it will cause a race condition. Hence, we have to\n // prevent the re-render of this hook as suggested in the following discussion.\n // https://github.com/reactwg/react-18/discussions/18#discussioncomment-795623\n if (reRenderCheckRef.current) {\n return;\n }\n\n reRenderCheckRef.current = true;\n\n // Don't handle callback if already signed in\n if (isSignedIn) return;\n\n (async (): Promise<void> => {\n try {\n const code: string | null = searchParams.get('code');\n const state: string | null = searchParams.get('state');\n const error: string | null = searchParams.get('error');\n\n // Check for OAuth errors first\n if (error) {\n logger.error('[ThunderIDClientProvider] An error was received for the initiated sign-in request.');\n\n return;\n }\n\n // Handle OAuth callback if code and state are present\n if (code && state) {\n setIsLoading(true);\n\n const result: {error?: string; redirectUrl?: string; success: boolean} = await handleOAuthCallback(\n code,\n state,\n );\n\n if (result.success) {\n // Redirect to the success URL\n if (result.redirectUrl) {\n router.push(result.redirectUrl);\n } else {\n // Refresh the page to update authentication state\n window.location.reload();\n }\n } else {\n logger.error(\n `[ThunderIDClientProvider] An error occurred while signing in: ${result.error || 'Authentication failed'}`,\n );\n }\n }\n } catch (error) {\n logger.error('[ThunderIDClientProvider] Failed to handle OAuth callback:', error);\n }\n })();\n }, []);\n\n useEffect(() => {\n // Set loading to false when server has resolved authentication state\n setIsLoading(false);\n }, [isSignedIn, user]);\n\n const handleSignIn = async (payload: any, request: EmbeddedFlowExecuteRequestConfig): Promise<any> => {\n if (!signIn) {\n throw new ThunderIDRuntimeError(\n '`signIn` function is not available.',\n 'ThunderIDClientProvider-handleSignIn-RuntimeError-001',\n 'nextjs',\n );\n }\n\n const result: any = await signIn(payload, request);\n\n // Redirect based flow URL is sent as `signInUrl` in the response.\n // Use window.location.href instead of router.push() — the OAuth authorization\n // endpoint is on an external server, and router.push() would send RSC fetch\n // headers that the identity provider doesn't understand, causing a CORS error.\n if (result?.data?.signInUrl) {\n window.location.href = result.data.signInUrl;\n\n return undefined;\n }\n\n // After the Embedded flow is successful, the URL to navigate next is sent as `afterSignInUrl` in the response.\n if (result?.data?.afterSignInUrl) {\n router.push(result.data.afterSignInUrl);\n\n return undefined;\n }\n\n if (result?.error) {\n throw new Error(result.error);\n }\n\n return result?.data ?? result;\n };\n\n const handleSignUp = async (payload: any, request: EmbeddedFlowExecuteRequestConfig): Promise<any> => {\n if (!signUp) {\n throw new ThunderIDRuntimeError(\n '`signUp` function is not available.',\n 'ThunderIDClientProvider-handleSignUp-RuntimeError-001',\n 'nextjs',\n );\n }\n\n const result: any = await signUp(payload, request);\n\n // Redirect based flow URL is sent as `signUpUrl` in the response.\n if (result?.data?.signUpUrl) {\n router.push(result.data.signUpUrl);\n\n return undefined;\n }\n\n // After the Embedded flow is successful, the URL to navigate next is sent as `afterSignUpUrl` in the response.\n if (result?.data?.afterSignUpUrl) {\n router.push(result.data.afterSignUpUrl);\n\n return undefined;\n }\n\n if (result?.error) {\n throw new Error(result.error);\n }\n\n return result?.data ?? result;\n };\n\n const handleSignOut = async (): Promise<any> => {\n logger.debug('[ThunderIDClientProvider][handleSignOut] `handleSignOut` called.');\n\n try {\n const result: any = await signOut();\n\n logger.debug('[ThunderIDClientProvider][handleSignOut] Sign out result:', result);\n\n if (result?.data?.afterSignOutUrl) {\n router.push(result.data.afterSignOutUrl);\n\n return {location: result.data.afterSignOutUrl, redirected: true};\n }\n\n if (result?.error) {\n logger.error(\n '[ThunderIDClientProvider][handleSignOut] Error result was returned during signing the user out with a button click:',\n result.error,\n );\n }\n\n return result?.data ?? result;\n } catch (error) {\n logger.error(\n '[ThunderIDClientProvider][handleSignOut] Error occurred during signing the user out with a button click:',\n error,\n );\n\n return undefined;\n }\n };\n\n const contextValue: ThunderIDContextProps = useMemo(\n () => ({\n applicationId,\n baseUrl,\n clearSession,\n isLoading,\n isSignedIn,\n organizationHandle,\n preferences,\n refreshToken,\n scopes,\n signIn: handleSignIn,\n signInUrl,\n signOut: handleSignOut,\n signUp: handleSignUp,\n signUpUrl,\n user,\n }),\n [\n baseUrl,\n user,\n isSignedIn,\n isLoading,\n signInUrl,\n signUpUrl,\n applicationId,\n organizationHandle,\n scopes,\n preferences,\n ],\n );\n\n const handleProfileUpdate = (payload: User): void => {\n setUser(payload);\n setUserProfile((prev: UserProfile) => ({\n ...prev,\n flattenedProfile: generateFlattenedUserProfile(payload),\n profile: payload,\n }));\n };\n\n /**\n * Re-reads `/users/me` through the server-held session, so a change made outside the profile API,\n * such as a recorded verification, shows.\n */\n const revalidateProfile = async (): Promise<void> => {\n if (preferences?.user?.fetchUserProfile === false) return;\n\n const result: Awaited<ReturnType<typeof getUserProfileAction>> = await getUserProfileAction(\n (await getSessionId()) ?? '',\n );\n\n if (result.success) {\n handleProfileUpdate(result.data.userProfile.profile);\n }\n };\n\n // Bridge into @thunderid/react's own ThunderIDContext. Internal react components rendered by\n // BaseSignIn/BaseSignUp — most notably FlowMetaProvider, which fetches `/flow/meta` and injects\n // its i18n bundle — call react's `useThunderID()` directly. Without this bridge they'd only see\n // react's context default (applicationId/baseUrl undefined, isInitialized false), so the meta\n // fetch would never fire and flow labels would render as untranslated i18n keys. Fields with no\n // nextjs equivalent (token/http helpers meant for direct browser API calls) are stubbed out,\n // since nextjs routes those operations through server actions instead.\n const unsupported = (name: string): (() => Promise<never>) => {\n return () =>\n Promise.reject(\n new ThunderIDRuntimeError(\n `\\`${name}\\` is not supported in @thunderid/nextjs.`,\n `ThunderIDClientProvider-${name}-NotSupportedError-001`,\n 'nextjs',\n ),\n );\n };\n\n const reactContextValue: ReactThunderIDContextProps = useMemo(\n () => ({\n afterSignInUrl: undefined,\n applicationId,\n baseUrl,\n clearSession,\n clientId: undefined,\n discovery: {wellKnown: null},\n // Only the management collection overrides arrive here, so the admin hooks build the URLs the\n // management server action accepts.\n endpoints,\n exchangeToken: unsupported('exchangeToken'),\n getAccessToken: unsupported('getAccessToken'),\n getDecodedIdToken: unsupported('getDecodedIdToken'),\n // The Next.js useGrantedPermissions reads them through a server action instead.\n getGrantedPermissions: unsupported('getGrantedPermissions'),\n getIdToken: unsupported('getIdToken'),\n getStorageManager: () => Promise.resolve(null),\n http: {\n // The admin components and hooks send management requests through a server action that adds\n // the server-held access token, so the token never reaches the browser.\n fetcher: fetchManagementFromServer,\n request: unsupported('http.request'),\n requestAll: unsupported('http.requestAll'),\n },\n instanceId: 0,\n isInitialized: !isLoading,\n isLoading,\n isMetaLoading: false,\n isSignedIn,\n meta: initialMeta ?? null,\n organizationHandle,\n reInitialize: unsupported('reInitialize'),\n recover: unsupported('recover'),\n resolveFlowTemplateLiterals: (text: string | undefined): string => text ?? '',\n scopes,\n signIn: handleSignIn,\n signInSilently: unsupported('signInSilently'),\n signInUrl,\n signOut: handleSignOut,\n signUp: handleSignUp,\n signUpUrl,\n user,\n userSchema,\n vendor: getVendorPrefix(vendor),\n }),\n [\n applicationId,\n baseUrl,\n clearSession,\n endpoints,\n isLoading,\n isSignedIn,\n organizationHandle,\n scopes,\n signInUrl,\n signUpUrl,\n user,\n userSchema,\n initialMeta,\n vendor,\n ],\n );\n\n return (\n <ThunderIDContext.Provider value={contextValue}>\n <ReactThunderIDContext.Provider value={reactContextValue}>\n <I18nProvider preferences={preferences?.i18n}>\n <FlowMetaProvider\n enabled={preferences?.resolveFromMeta !== false}\n initialMeta={initialMeta}\n fetchMeta={fetchFlowMetaFromServer}\n >\n <ThemeProvider theme={preferences?.theme?.overrides} mode={preferences?.theme?.mode}>\n <FlowProvider>\n <UserProvider\n profile={userProfile}\n userSchema={userSchema}\n onUpdateProfile={handleProfileUpdate}\n revalidateProfile={revalidateProfile}\n updateProfile={updateProfile}\n >\n {children}\n </UserProvider>\n </FlowProvider>\n </ThemeProvider>\n </FlowMetaProvider>\n </I18nProvider>\n </ReactThunderIDContext.Provider>\n </ThunderIDContext.Provider>\n );\n};\n\nexport default ThunderIDClientProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAMA,2BAAgF,EACpF,SACA,UACA,WACA,QACA,cACA,cACA,SACA,QACA,qBACA,aACA,YACA,WACA,WACA,MAAM,OACN,aAAa,cACb,YAAY,cAAc,MAC1B,eACA,eACA,oBACA,QACA,QACA,cAAc,WACuC;CACrD,MAAMC,qCAA8C,MAAM;CAC1D,MAAMC,yCAAuC;CAC7C,MAAMC,qDAAyD;CAC/D,MAAM,CAAC,WAAW,oCAAkC,KAAK;CACzD,MAAM,CAAC,MAAM,+BAAiC,MAAM;CACpD,MAAM,CAAC,aAAa,sCAAwC,aAAa;CACzE,MAAM,CAAC,YAAY,qCAAkE,YAAY;AAEjG,4BAAgB;AACd,iBAAe,aAAa;IAC3B,CAAC,aAAa,CAAC;AAElB,4BAAgB;AACd,gBAAc,YAAY;IACzB,CAAC,YAAY,CAAC;AAEjB,4BAAgB;AACd,UAAQ,MAAM;IACb,CAAC,MAAM,CAAC;AAGX,4BAAgB;AAOd,MAAI,iBAAiB,QACnB;AAGF,mBAAiB,UAAU;AAG3B,MAAI,WAAY;AAEhB,GAAC,YAA2B;AAC1B,OAAI;IACF,MAAMC,OAAsB,aAAa,IAAI,OAAO;IACpD,MAAMC,QAAuB,aAAa,IAAI,QAAQ;AAItD,QAH6B,aAAa,IAAI,QAAQ,EAG3C;AACT,4BAAO,MAAM,qFAAqF;AAElG;;AAIF,QAAI,QAAQ,OAAO;AACjB,kBAAa,KAAK;KAElB,MAAMC,SAAmE,MAAM,oBAC7E,MACA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rB;EACA,cAAc,YAAY,eAAe;EACzC,SAAS,YAAY,UAAU;EAC/B,8BAA8B,SAAqC,QAAQ;EAC3E;EACA,QAAQ;EACR,gBAAgB,YAAY,iBAAiB;EAC7C;EACA,SAAS;EACT,QAAQ;EACR;EACA;EACA;EACA,8CAAwB,OAAO;EAChC,GACD;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CACF;AAED,QACE,2CAACC,iCAAiB;EAAS,OAAO;YAChC,2CAACC,mCAAsB;GAAS,OAAO;aACrC,2CAACC;IAAa,aAAa,aAAa;cACtC,2CAACC;KACC,SAAS,aAAa,oBAAoB;KAC7B;KACb,WAAWC;eAEX,2CAACC;MAAc,OAAO,aAAa,OAAO;MAAW,MAAM,aAAa,OAAO;gBAC7E,2CAACC,4CACC,2CAACC;OACC,SAAS;OACG;OACZ,iBAAiB;OACE;OACJ;OAEd;QACY,GACF;OACD;MACC;KACN;IACgB;GACP;;AAIhC,gCAAe"}
|
|
@@ -9,6 +9,7 @@ const require_DeviceGrant = require('./components/auth/DeviceGrant/DeviceGrant.c
|
|
|
9
9
|
const require_SignOutButton = require('./components/auth/buttons/SignOutButton/SignOutButton.cjs');
|
|
10
10
|
const require_User = require('./components/account/User/User.cjs');
|
|
11
11
|
const require_SignUp = require('./components/auth/SignUp/SignUp.cjs');
|
|
12
|
+
const require_VerifyAttribute = require('./components/account/VerifyAttribute/VerifyAttribute.cjs');
|
|
12
13
|
const require_UserProfile = require('./components/account/UserProfile/UserProfile.cjs');
|
|
13
14
|
const require_UserDropdown = require('./components/account/UserDropdown/UserDropdown.cjs');
|
|
14
15
|
const require_UserAvatar = require('./components/account/UserAvatar/UserAvatar.cjs');
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -16,6 +16,7 @@ const require_DeviceGrant = require('./client/components/auth/DeviceGrant/Device
|
|
|
16
16
|
const require_SignOutButton = require('./client/components/auth/buttons/SignOutButton/SignOutButton.cjs');
|
|
17
17
|
const require_User = require('./client/components/account/User/User.cjs');
|
|
18
18
|
const require_SignUp = require('./client/components/auth/SignUp/SignUp.cjs');
|
|
19
|
+
const require_VerifyAttribute = require('./client/components/account/VerifyAttribute/VerifyAttribute.cjs');
|
|
19
20
|
const require_UserProfile = require('./client/components/account/UserProfile/UserProfile.cjs');
|
|
20
21
|
const require_UserDropdown = require('./client/components/account/UserDropdown/UserDropdown.cjs');
|
|
21
22
|
const require_UserAvatar = require('./client/components/account/UserAvatar/UserAvatar.cjs');
|
|
@@ -174,6 +175,7 @@ exports.UserList = require_UserList.default;
|
|
|
174
175
|
exports.UserProfile = require_UserProfile.default;
|
|
175
176
|
exports.UserSelect = require_UserSelect.default;
|
|
176
177
|
exports.UserTypeSelect = require_UserTypeSelect.default;
|
|
178
|
+
exports.VerifyAttribute = require_VerifyAttribute.default;
|
|
177
179
|
exports.backchannelLogout = require_backchannelLogout.default;
|
|
178
180
|
exports.createRouteMatcher = require_createRouteMatcher.default;
|
|
179
181
|
exports.removeChunkedCookieFromHeader = require_thunderIDProxy.removeChunkedCookieFromHeader;
|