diff --git a/packages/browser/CHANGELOG.md b/packages/browser/CHANGELOG.md index 1ea654aa..944a75fb 100644 --- a/packages/browser/CHANGELOG.md +++ b/packages/browser/CHANGELOG.md @@ -7,6 +7,8 @@ No changes to this SDK since sdk/browser/v1.26.0. ## 1.26.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 + +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/browser/v1.25.0...sdk/browser/v1.26.0 diff --git a/packages/browser/src/ThunderIDBrowserClient.ts b/packages/browser/src/ThunderIDBrowserClient.ts index c0e6f204..40391d4e 100644 --- a/packages/browser/src/ThunderIDBrowserClient.ts +++ b/packages/browser/src/ThunderIDBrowserClient.ts @@ -34,12 +34,17 @@ import { DeviceSecretSwitchResult, EmbeddedFlowSessionData, EmbeddedFlowType, + EmbeddedSignInFlowRequest, EmbeddedSignInFlowResponse, EmbeddedSignInFlowStatus, OrganizationUnitSwitchErrorCodes, OrganizationUnitSwitchFallbackErrors, SwitchOrganizationUnitOptions, ThunderIDAPIError, + ThunderIDRuntimeError, + ReauthenticationMethod, + ReauthenticationOptions, + ReauthenticationRequest, executeEmbeddedSignInFlow, Telemetry, TelemetryConfig, @@ -63,6 +68,13 @@ import BrowserTelemetry from './telemetry/BrowserTelemetry'; import AuthenticationHelper from './utils/AuthenticationHelper'; import createHttpClientFetcher from './utils/createHttpClientFetcher'; import navigate from './utils/navigate'; +import { + completeReauthenticationInPopup, + isReauthenticationPopup, + openReauthenticationPopup, + ReauthenticationMessage, + waitForReauthentication, +} from './utils/reauthenticationPopup'; import SPACryptoUtils from './utils/SPACryptoUtils'; import SPAHelper from './utils/SPAHelper'; import SPAUtils from './utils/SPAUtils'; @@ -124,6 +136,12 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC } public override async initialize(config: T, storage?: Storage): Promise { + // A re-sign-in popup's callback belongs to the window that opened it, so it is handed over before + // anything treats it as a sign-in callback, and the popup's SDK does nothing more. + if (completeReauthenticationInPopup()) { + return false; + } + this._startedInitialize = true; this._initialized = false; @@ -139,7 +157,14 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC }; const store: Storage = storage ?? initiateStore(this._storage as BrowserStorage); - await super.initialize(merged as unknown as T, store); + try { + await super.initialize(merged as unknown as T, store); + } catch (error) { + // A refused configuration leaves the client uninitialized, so later calls fail instead of waiting. + this._startedInitialize = false; + + throw error; + } const sm = this.getStorageManager(); this._spaHelper = new SPAHelper(sm); @@ -236,6 +261,11 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC let iterations = 0; while (!this._initialized) { + // A failed initialization ends the wait. + if (!this._startedInitialize) { + return false; + } + if (iterations === 1e4) { logger.warn('Initialization is taking longer than expected'); } @@ -297,6 +327,11 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC state?: string, tokenRequestConfig?: {params: Record}, ): Promise { + // In a re-sign-in popup the code belongs to the opener, which redeems it. + if (isReauthenticationPopup()) { + return undefined; + } + await this.isInitialized(); if (this._backend) { @@ -464,6 +499,211 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC return this.getUser(); } + /** + * Signs the signed-in user in again in a popup, for a change that needs a recent sign-in, such as + * setting a first credential or changing an email address. Pass the `maxAge` of the + * `StepUpRequiredError` the change failed with. The popup sends `max_age` (or `prompt=login`) and + * `id_token_hint`; the code it returns is redeemed here, and the session's tokens are replaced only when + * the ID token is valid, carries the request's nonce, and names the same user. Then retry the change + * once. Call it from the user action, such as a click, so the browser lets the popup open. + * + * For a session from a redirect sign-in only: see {@link getReauthenticationMethod}. A session from an + * embedded sign-in flow signs in again with {@link executeReauthenticationFlow}, and backend mode + * through the backend's sign-in. + * + * @param options - How recent the sign-in must be. + * @throws {ThunderIDRuntimeError} When the popup is blocked or closed, the sign-in fails, or it signs + * in a different user; the session is then left as it was. + */ + public async reauthenticate(options: ReauthenticationOptions = {}): Promise { + if (this._backend) { + throw new ThunderIDRuntimeError( + 'Signing in again in a popup is not available in backend mode.', + 'BROWSER-REAUTHENTICATION-UM01', + 'browser', + ); + } + + // Opened before any await, so the browser treats it as part of the user action. + const popup: Window = openReauthenticationPopup(this._browserInstanceId); + let refreshPaused = false; + + try { + await this.isInitialized(); + + const config: AuthClientConfig = await this.getStorageManager().getConfigData(); + + if (await this._isFlowSession(config)) { + throw new ThunderIDRuntimeError( + 'Signing in again in a popup is not available for a session from an embedded sign-in flow.', + 'BROWSER-REAUTHENTICATION-UM02', + 'browser', + ); + } + + const authorization: ReauthenticationRequest = await this.buildReauthenticationRequest( + options, + config?.afterSignInUrl ?? window.location.origin, + ); + + popup.location.href = authorization.url; + // A refresh while the user signs in again could store tokens with the old sign-in time over the new + // ones, so the timer stops here and starts again below. + await this._spaHelper?.clearRefreshTokenTimeout(); + refreshPaused = true; + + const message: ReauthenticationMessage = await waitForReauthentication(popup, authorization.state); + + if (message.error || !message.code) { + throw new ThunderIDRuntimeError( + message.errorDescription ?? message.error ?? 'The sign-in returned no authorization code.', + 'BROWSER-REAUTHENTICATION-AE01', + 'browser', + {error: message.error}, + ); + } + + await this.completeReauthentication(authorization, message.code); + } finally { + if (refreshPaused) { + await this._spaHelper?.refreshAccessTokenAutomatically((): Promise => this.refreshAccessToken()); + } + if (!popup.closed) { + popup.close(); + } + } + } + + /** + * How the signed-in user signs in again for a change that needs a recent sign-in: `popup` with + * {@link reauthenticate} for a session from a redirect sign-in, `flow` with + * {@link executeReauthenticationFlow} for a session from an embedded sign-in flow (or with `mode` + * set to `embedded`), and `unavailable` in backend mode. + * + * @returns The method for the current session. + */ + public async getReauthenticationMethod(): Promise { + if (this._backend) { + return 'unavailable'; + } + + await this.isInitialized(); + + const config: AuthClientConfig = await this.getStorageManager().getConfigData(); + + return (await this._isFlowSession(config)) ? 'flow' : 'popup'; + } + + /** + * Runs the sign-in flow again for the signed-in user, for a change that needs a recent sign-in, in a + * session from an embedded sign-in flow. Call it without an `executionId` to start the flow: it starts + * an `AUTHENTICATION` flow for the configured `applicationId` with `maxAge` (`0` when not given, so the + * user is always asked), and the server asks the user again when the sign-in is older. Then call it with + * each step's `executionId`, inputs and action, as `signIn` takes them, and render each response. + * + * When the flow completes, the session's tokens are replaced with its assertion only when it names the + * same user (`sub`) as the session; otherwise the session is left as it was. Then retry the change once. + * + * @param payload - A step of the flow; empty to start it. + * @param options - How recent the sign-in must be, read when starting. + * @returns The flow's response. + * @throws {ThunderIDRuntimeError} In backend mode (`BROWSER-REAUTHENTICATION-UM01`), without an + * `applicationId` (`BROWSER-REAUTHENTICATION-UM03`), or when a different user signed in + * (`BROWSER-REAUTHENTICATION-DU01`). + */ + public async executeReauthenticationFlow( + payload: EmbeddedSignInFlowRequest = {}, + options: ReauthenticationOptions = {}, + ): Promise { + if (this._backend) { + throw new ThunderIDRuntimeError( + 'Signing in again with a sign-in flow is not available in backend mode.', + 'BROWSER-REAUTHENTICATION-UM01', + 'browser', + ); + } + + await this.isInitialized(); + + const config: AuthClientConfig = await this.getStorageManager().getConfigData(); + let request: EmbeddedSignInFlowRequest; + + if (payload.executionId) { + const {action, challengeToken, executionId, inputs} = payload; + + request = {action, challengeToken, executionId, inputs}; + } else { + const applicationId: string | undefined = (config as {applicationId?: string})?.applicationId; + + if (!applicationId) { + throw new ThunderIDRuntimeError( + 'Signing in again with a sign-in flow needs the application ID.', + 'BROWSER-REAUTHENTICATION-UM03', + 'browser', + ); + } + + const maxAge: number = + options.maxAge !== undefined && Number.isFinite(options.maxAge) && options.maxAge >= 0 + ? Math.floor(options.maxAge) + : 0; + // The kept session handles let the server read the sign-in time where its cookie is not sent. + const sessionData: EmbeddedFlowSessionData[] = await this.getFlowSessions(); + + request = { + applicationId, + flowType: EmbeddedFlowType.Authentication, + maxAge, + ...(config?.scopes ? {scopes: config.scopes} : {}), + ...(sessionData.length > 0 ? {sessionData} : {}), + }; + } + + const response: EmbeddedSignInFlowResponse = await executeEmbeddedSignInFlow({ + baseUrl: config?.baseUrl, + payload: request, + url: resolveResourceEndpoint('flowExecute', config), + }); + + if (response?.flowStatus !== EmbeddedSignInFlowStatus.Complete || !response.assertion) { + await this.storeFlowSessions(response ?? {}); + + return response; + } + + const claims: Record = await this.decodeJwtToken>(response.assertion); + const idToken: string | undefined = (await this.getStorageManager().getSessionData())?.id_token; + const sessionSubject: unknown = idToken + ? (await this.decodeJwtToken>(idToken))['sub'] + : undefined; + + if (!sessionSubject || claims['sub'] !== sessionSubject) { + throw new ThunderIDRuntimeError( + 'The sign-in used a different account than the signed-in user.', + 'BROWSER-REAUTHENTICATION-DU01', + 'browser', + ); + } + + await this.storeFlowSessions(response); + await this.setSessionFromFlowAssertion({...response, assertion: response.assertion}); + + return response; + } + + /** + * Whether the session came from an embedded sign-in flow, or the SDK is configured for embedded mode. + */ + private async _isFlowSession(config: AuthClientConfig): Promise { + if ((config as {mode?: string})?.mode === 'embedded') { + return true; + } + + const session: Partial | undefined = await this.getStorageManager().getSessionData(); + + return Boolean(session?.embedded_sign_in); + } + /** * Signs in again bounded to the organization unit `organizationUnitId`, and replaces the session with * the one it gets. The server reuses the SSO session when the user can sign in there, so normally no @@ -682,9 +922,49 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC ); } + /** + * Replaces the session with the result of a completed embedded flow: the access token its assertion + * is exchanged for, with the assertion as the ID token. Only the kept SSO session handles carry over. + * A failed exchange drops the handles the step returned, so a retry shows the flow again. + * + * @param step - The flow step whose `flowStatus` is `COMPLETE`. + * @returns The assertion's claims. + */ + protected async setSessionFromFlowAssertion(step: { + assertion: string; + sessionData?: EmbeddedFlowSessionData[]; + }): Promise> { + let session: SessionData; + + try { + session = await this.exchangeFlowAssertion(step.assertion); + } catch (error) { + const clearedSessions: string[] = (step.sessionData ?? []).map( + ({flowIdentifier}: EmbeddedFlowSessionData) => flowIdentifier, + ); + + await this.storeFlowSessions({clearedSessions}); + + throw error; + } + + // The previous session's refresh would run against a session with no refresh token. + await this._spaHelper?.clearRefreshTokenTimeout(); + + const previous: Partial = (await this.getStorageManager().getSessionData()) ?? {}; + // Session writes merge and drop undefined keys, so every previous key is cleared in the same write. + const cleared: Record = Object.fromEntries( + Object.keys(previous).map((key: string): [string, undefined] => [key, undefined]), + ); + + await this.setSession({...cleared, embedded_sign_in: true, flow_sessions: previous.flow_sessions, ...session}); + + return this.decodeJwtToken>(step.assertion); + } + /** * Embedded mode: starts a sign-in flow bounded to the unit. When the SSO session is reused, the flow - * completes at once and its assertion replaces the session. + * completes at once and the token its assertion is exchanged for replaces the session. */ private async _switchOrganizationUnitEmbedded( organizationUnitId: string, @@ -718,18 +998,13 @@ class ThunderIDBrowserClient extends ThunderIDJavaScriptC await this.storeFlowSessions(response); if (response?.flowStatus === EmbeddedSignInFlowStatus.Complete && response.assertion) { - const claims: Record = await this.decodeJwtToken>(response.assertion); - const iat: number | undefined = typeof claims['iat'] === 'number' ? claims['iat'] : undefined; - const exp: number | undefined = typeof claims['exp'] === 'number' ? claims['exp'] : undefined; - - await this.setSession({ - access_token: response.assertion, - created_at: iat ? iat * 1000 : Date.now(), - expires_in: exp && iat ? exp - iat : 3600, - id_token: response.assertion, - scope: claims['scope'], - token_type: 'Bearer', - }); + try { + await this.setSessionFromFlowAssertion({...response, assertion: response.assertion}); + } catch (error) { + logger.error('Keeping the session of the organization unit failed.', error); + + throw ThunderIDBrowserClient._toSwitchError(undefined, error); + } const user: User = await this.getUser(); diff --git a/packages/browser/src/__tests__/ThunderIDBrowserClient.organizationUnit.test.ts b/packages/browser/src/__tests__/ThunderIDBrowserClient.organizationUnit.test.ts index fb386a77..a2f1dce3 100644 --- a/packages/browser/src/__tests__/ThunderIDBrowserClient.organizationUnit.test.ts +++ b/packages/browser/src/__tests__/ThunderIDBrowserClient.organizationUnit.test.ts @@ -172,26 +172,65 @@ describe('ThunderIDBrowserClient.switchOrganizationUnit()', () => { text: () => Promise.resolve(JSON.stringify(body)), }); - it('starts a sign-in flow with ouId and replaces the session with its assertion', async () => { + /** Answers the flow request with `flowBody` and the token request with `tokenBody`. */ + const flowThenToken = (flowBody: unknown, tokenBody: unknown = {access_token: 'ou-at', expires_in: 3600}): any => + vi.fn((url: string) => + Promise.resolve( + url.endsWith('/oauth2/token') + ? flowResponse(tokenBody, !('error' in (tokenBody as object)), 'error' in (tokenBody as object) ? 400 : 200) + : flowResponse(flowBody), + ), + ); + + it('starts a sign-in flow with ouId and replaces the session with the exchanged token', async () => { const client = await createClient({mode: 'embedded'} as any); + await (client as any).getStorageManager().setSessionData({refresh_token: 'old-rt', session_state: 'old-ss'}); const assertion: string = encode({ exp: Math.floor(Date.now() / 1000) + 600, iat: Math.floor(Date.now() / 1000), ouId: 'ou-1', sub: 'u1', }); - const fetchMock = vi.fn().mockResolvedValue(flowResponse({assertion, flowStatus: 'COMPLETE'})); + const fetchMock = flowThenToken({assertion, flowStatus: 'COMPLETE'}); vi.stubGlobal('fetch', fetchMock); + const clearRefreshTimer = vi.spyOn((client as any)._spaHelper, 'clearRefreshTokenTimeout'); await client.switchOrganizationUnit('ou-1'); + expect(clearRefreshTimer).toHaveBeenCalled(); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/flow/execute'); expect(body).toMatchObject({applicationId: 'app-1', flowType: 'AUTHENTICATION', ouId: 'ou-1'}); - expect(await sessionOf(client)).toMatchObject({access_token: assertion, id_token: assertion}); + expect(fetchMock.mock.calls[1][0]).toBe('https://example.com/oauth2/token'); + expect(fetchMock.mock.calls[1][1].body.get('subject_token')).toBe(assertion); + const session = await sessionOf(client); + expect(session).toMatchObject({access_token: 'ou-at', id_token: assertion}); + expect(session).not.toHaveProperty('refresh_token'); + expect(session).not.toHaveProperty('session_state'); expect(await client.getCurrentOrganizationUnit()).toEqual({id: 'ou-1'}); }); + it('fails and keeps the session when the assertion cannot be exchanged', async () => { + const client = await createClient({mode: 'embedded'} as any); + const assertion: string = encode({iat: Math.floor(Date.now() / 1000), ouId: 'ou-1', sub: 'u1'}); + vi.stubGlobal( + 'fetch', + flowThenToken( + {assertion, flowStatus: 'COMPLETE', sessionData: [{flowIdentifier: 'f9', sessionHandle: 'h9'}]}, + {error: 'unauthorized_client'}, + ), + ); + const clearRefreshTimer = vi.spyOn((client as any)._spaHelper, 'clearRefreshTokenTimeout'); + + await expect(client.switchOrganizationUnit('ou-1')).rejects.toMatchObject({ + code: OrganizationUnitSwitchErrorCodes.Failed, + }); + expect(await sessionOf(client)).toMatchObject({access_token: 'old-at', id_token: 'old-id'}); + // The previous session keeps refreshing, and the handle of the failed switch is not kept. + expect(clearRefreshTimer).not.toHaveBeenCalled(); + expect((await sessionOf(client)).flow_sessions ?? []).toEqual([]); + }); + it('maps FES-1023 to unauthorized_client and keeps the session', async () => { const client = await createClient({mode: 'embedded'} as any); vi.stubGlobal( @@ -225,7 +264,7 @@ describe('ThunderIDBrowserClient.switchOrganizationUnit()', () => { iat: Math.floor(Date.now() / 1000), sub: 'u1', }); - const fetchMock = vi.fn().mockResolvedValue(flowResponse({assertion, flowStatus: 'COMPLETE'})); + const fetchMock = flowThenToken({assertion, flowStatus: 'COMPLETE'}); vi.stubGlobal('fetch', fetchMock); await client.switchOrganizationUnit('ou-1'); @@ -234,7 +273,7 @@ describe('ThunderIDBrowserClient.switchOrganizationUnit()', () => { {flowIdentifier: 'f1', sessionHandle: 'h1'}, ]); expect(await sessionOf(client)).toMatchObject({ - access_token: assertion, + access_token: 'ou-at', flow_sessions: [{flowIdentifier: 'f1', sessionHandle: 'h1'}], }); }); @@ -254,13 +293,11 @@ describe('ThunderIDBrowserClient.switchOrganizationUnit()', () => { const assertion: string = encode({iat: Math.floor(Date.now() / 1000), sub: 'u1'}); vi.stubGlobal( 'fetch', - vi.fn().mockResolvedValue( - flowResponse({ - assertion, - flowStatus: 'COMPLETE', - sessionData: [{flowIdentifier: 'f2', sessionHandle: 'h2'}], - }), - ), + flowThenToken({ + assertion, + flowStatus: 'COMPLETE', + sessionData: [{flowIdentifier: 'f2', sessionHandle: 'h2'}], + }), ); await client.switchOrganizationUnit('ou-1'); diff --git a/packages/browser/src/__tests__/ThunderIDBrowserClient.reauthentication.test.ts b/packages/browser/src/__tests__/ThunderIDBrowserClient.reauthentication.test.ts new file mode 100644 index 00000000..e30a7cc6 --- /dev/null +++ b/packages/browser/src/__tests__/ThunderIDBrowserClient.reauthentication.test.ts @@ -0,0 +1,291 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment */ +import {afterEach, describe, expect, it, vi} from 'vitest'; +import ThunderIDBrowserClient from '../ThunderIDBrowserClient'; +import { + REAUTHENTICATION_MESSAGE, + REAUTHENTICATION_WINDOW_PREFIX, + completeReauthenticationInPopup, +} from '../utils/reauthenticationPopup'; + +const encode = (claims: Record): string => + `h.${btoa(JSON.stringify(claims)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_')}.s`; + +const SESSION = {access_token: 'old-at', created_at: Date.now(), expires_in: '3600', id_token: encode({sub: 'user-1'})}; + +let instance = 80; + +const createClient = async (): Promise => { + instance += 1; + const client: any = new ThunderIDBrowserClient(instance); + await client.initialize({ + afterSignInUrl: 'https://app.example.com/callback', + baseUrl: 'https://example.com', + clientId: 'test-client', + } as any); + const sm: any = client.getStorageManager(); + await sm.setOIDCProviderMetaData({ + authorization_endpoint: 'https://example.com/oauth2/authorize', + token_endpoint: 'https://example.com/oauth2/token', + }); + await sm.setTemporaryDataParameter('op_config_initiated', true); + await sm.setSessionData(SESSION); + + return client; +}; + +/** A popup that, once sent to the authorize URL, answers with the given callback parameters. */ +const fakePopup = (answer: (state: string) => Record): any => { + const popup: any = { + close: vi.fn(() => { + popup.closed = true; + }), + closed: false, + location: {}, + }; + + Object.defineProperty(popup.location, 'href', { + set(url: string) { + const state: string = new URL(url).searchParams.get('state') ?? ''; + popup.authorizeUrl = url; + setTimeout(() => { + window.dispatchEvent( + new MessageEvent('message', { + data: {type: REAUTHENTICATION_MESSAGE, state, ...answer(state)}, + origin: window.location.origin, + source: popup, + }), + ); + }, 0); + }, + }); + + return popup; +}; + +describe('ThunderIDBrowserClient.reauthenticate()', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('opens the popup before anything else, sends max_age, and completes with the returned code', async () => { + const client = await createClient(); + const popup = fakePopup(() => ({code: 'code-1'})); + const openSpy = vi.spyOn(window, 'open').mockReturnValue(popup); + const complete = vi.spyOn(client, 'completeReauthentication').mockResolvedValue({}); + const refresh = vi.spyOn(client, 'refreshAccessToken'); + + await client.reauthenticate({maxAge: 300}); + + expect(openSpy).toHaveBeenCalledWith('', `${REAUTHENTICATION_WINDOW_PREFIX}${instance}`, expect.any(String)); + const url = new URL(popup.authorizeUrl); + expect(url.searchParams.get('max_age')).toBe('300'); + expect(url.searchParams.get('id_token_hint')).toBe(SESSION.id_token); + expect(complete).toHaveBeenCalledWith(expect.objectContaining({state: url.searchParams.get('state')}), 'code-1'); + expect(refresh).not.toHaveBeenCalled(); + expect(popup.close).toHaveBeenCalled(); + }); + + it('fails with a blocked-popup error when the browser does not open it', async () => { + const client = await createClient(); + vi.spyOn(window, 'open').mockReturnValue(null); + + await expect(client.reauthenticate({maxAge: 300})).rejects.toMatchObject({code: 'BROWSER-REAUTHENTICATION-PB01'}); + }); + + it('fails and keeps the session when the sign-in returns an error', async () => { + const client = await createClient(); + vi.spyOn(window, 'open').mockReturnValue(fakePopup(() => ({error: 'access_denied'}))); + const complete = vi.spyOn(client, 'completeReauthentication'); + + await expect(client.reauthenticate({maxAge: 300})).rejects.toMatchObject({code: 'BROWSER-REAUTHENTICATION-AE01'}); + expect(complete).not.toHaveBeenCalled(); + expect((await client.getStorageManager().getSessionData()).access_token).toBe('old-at'); + }); + + it('ignores a message with another state', async () => { + const client = await createClient(); + const popup = fakePopup(() => ({code: 'code-1', state: 'another-state'})); + vi.spyOn(window, 'open').mockReturnValue(popup); + const complete = vi.spyOn(client, 'completeReauthentication').mockResolvedValue({}); + setTimeout(() => { + popup.closed = true; + }, 50); + + await expect(client.reauthenticate({maxAge: 300})).rejects.toMatchObject({code: 'BROWSER-REAUTHENTICATION-PC01'}); + expect(complete).not.toHaveBeenCalled(); + }); +}); + +describe('ThunderIDBrowserClient re-sign-in with a sign-in flow', () => { + const FLOW_SESSION = { + access_token: 'flow-at', + created_at: Date.now(), + embedded_sign_in: true, + expires_in: '3600', + id_token: encode({sub: 'user-1'}), + }; + + const flowSessionClient = async (): Promise => { + const client = await createClient(); + await client.getStorageManager().setConfigData({applicationId: 'app-1'}); + await client.getStorageManager().setSessionData(FLOW_SESSION); + + return client; + }; + + const stubFlow = (body: Record): any => { + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), {status: 200})); + vi.stubGlobal('fetch', fetchMock); + + return fetchMock; + }; + + const sentBody = (fetchMock: any): any => JSON.parse(fetchMock.mock.calls[0][1].body); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('reports popup for a redirect session and flow for a session from a sign-in flow', async () => { + expect(await (await createClient()).getReauthenticationMethod()).toBe('popup'); + expect(await (await flowSessionClient()).getReauthenticationMethod()).toBe('flow'); + }); + + it('reports flow in embedded mode', async () => { + const client = await createClient(); + await client.getStorageManager().setConfigData({mode: 'embedded'}); + + expect(await client.getReauthenticationMethod()).toBe('flow'); + }); + + it('keeps the session handles each step returns and ends', async () => { + const client = await flowSessionClient(); + await client.getStorageManager().setSessionData({flow_sessions: [{flowIdentifier: 'f1', sessionHandle: 'h1'}]}); + stubFlow({ + clearedSessions: ['f1'], + executionId: 'e-1', + flowStatus: 'INCOMPLETE', + sessionData: [{flowIdentifier: 'f2', sessionHandle: 'h2'}], + }); + + await client.executeReauthenticationFlow({executionId: 'e-1', inputs: {}}); + + const held = (await client.getStorageManager().getSessionData()).flow_sessions.map((s: any) => s.flowIdentifier); + expect(held).toEqual(['f2']); + }); + + it('refuses the popup for a session from a sign-in flow', async () => { + const client = await flowSessionClient(); + vi.spyOn(window, 'open').mockReturnValue(fakePopup(() => ({code: 'code-1'}))); + + await expect(client.reauthenticate({maxAge: 300})).rejects.toMatchObject({code: 'BROWSER-REAUTHENTICATION-UM02'}); + }); + + it('starts an authentication flow with maxAge and the application ID', async () => { + const client = await flowSessionClient(); + const fetchMock = stubFlow({executionId: 'e-1', flowStatus: 'INCOMPLETE'}); + + await client.executeReauthenticationFlow({}, {maxAge: 30}); + + expect(sentBody(fetchMock)).toMatchObject({applicationId: 'app-1', flowType: 'AUTHENTICATION', maxAge: 30}); + }); + + it('asks for a new sign-in with maxAge 0 when the challenge carries none', async () => { + const client = await flowSessionClient(); + const fetchMock = stubFlow({executionId: 'e-1', flowStatus: 'INCOMPLETE'}); + + await client.executeReauthenticationFlow(); + + expect(sentBody(fetchMock).maxAge).toBe(0); + }); + + it('sends only the step on a continuation', async () => { + const client = await flowSessionClient(); + const fetchMock = stubFlow({executionId: 'e-1', flowStatus: 'INCOMPLETE'}); + + await client.executeReauthenticationFlow({action: 'a-1', executionId: 'e-1', inputs: {password: 'p'}, maxAge: 5}); + + const body = sentBody(fetchMock); + expect(body).toMatchObject({action: 'a-1', executionId: 'e-1', inputs: {password: 'p'}}); + expect(body.maxAge).toBeUndefined(); + expect(body.applicationId).toBeUndefined(); + }); + + it('replaces the session with the token its assertion is exchanged for when the same user signed in', async () => { + const client = await flowSessionClient(); + const assertion = encode({exp: 2000, iat: 1000, sub: 'user-1'}); + const fetchMock = vi.fn((url: string) => + Promise.resolve( + new Response( + JSON.stringify( + url.endsWith('/oauth2/token') + ? {access_token: 'new-at', expires_in: 3600} + : {assertion, flowStatus: 'COMPLETE'}, + ), + {status: 200}, + ), + ), + ); + vi.stubGlobal('fetch', fetchMock); + + await client.executeReauthenticationFlow({executionId: 'e-1', inputs: {password: 'p'}}); + + expect(fetchMock.mock.calls[1][0]).toBe('https://example.com/oauth2/token'); + expect(fetchMock.mock.calls[1][1].body.get('subject_token')).toBe(assertion); + const session = await client.getStorageManager().getSessionData(); + expect(session).toMatchObject({access_token: 'new-at', embedded_sign_in: true, id_token: assertion}); + }); + + it('keeps the session when a different user signed in, without exchanging the assertion', async () => { + const client = await flowSessionClient(); + const fetchMock = stubFlow({assertion: encode({sub: 'user-2'}), flowStatus: 'COMPLETE'}); + + await expect(client.executeReauthenticationFlow({executionId: 'e-1', inputs: {}})).rejects.toMatchObject({ + code: 'BROWSER-REAUTHENTICATION-DU01', + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect((await client.getStorageManager().getSessionData()).access_token).toBe(FLOW_SESSION.access_token); + }); + + it('needs the application ID to start', async () => { + const client = await createClient(); + stubFlow({}); + + await expect(client.executeReauthenticationFlow()).rejects.toMatchObject({code: 'BROWSER-REAUTHENTICATION-UM03'}); + }); +}); + +describe('completeReauthenticationInPopup()', () => { + afterEach(() => { + window.name = ''; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('hands the callback to the opener and closes the popup', () => { + const opener = {postMessage: vi.fn()}; + window.name = `${REAUTHENTICATION_WINDOW_PREFIX}0`; + vi.stubGlobal('opener', opener); + window.history.replaceState({}, '', '/callback?code=c-1&state=s-1'); + const close = vi.spyOn(window, 'close').mockImplementation(() => undefined); + + expect(completeReauthenticationInPopup()).toBe(true); + expect(opener.postMessage).toHaveBeenCalledWith( + {code: 'c-1', error: undefined, errorDescription: undefined, state: 's-1', type: REAUTHENTICATION_MESSAGE}, + window.location.origin, + ); + expect(close).toHaveBeenCalled(); + }); + + it('does nothing in a window that is not a re-sign-in popup', () => { + window.name = ''; + window.history.replaceState({}, '', '/callback?code=c-1&state=s-1'); + + expect(completeReauthenticationInPopup()).toBe(false); + }); +}); diff --git a/packages/browser/src/__tests__/ThunderIDBrowserClient.test.ts b/packages/browser/src/__tests__/ThunderIDBrowserClient.test.ts index 061db617..57f1f929 100644 --- a/packages/browser/src/__tests__/ThunderIDBrowserClient.test.ts +++ b/packages/browser/src/__tests__/ThunderIDBrowserClient.test.ts @@ -47,6 +47,35 @@ describe('ThunderIDBrowserClient', () => { await expect(client.initialize(config)).resolves.toBe(true); }); + it('refuses embedded mode without a client ID, and later calls fail instead of waiting', async () => { + const client = new ThunderIDBrowserClient(); + + await expect( + client.initialize({ + ...config, + applicationId: 'app-1', + clientId: undefined, + mode: 'embedded', + } as BrowserAuthConfig), + ).rejects.toMatchObject({code: 'JS-AUTH_CORE-INIT-IV01'}); + expect(await client.isInitialized()).toBe(false); + await expect(client.getUser()).rejects.toMatchObject({code: 'SPA-AUTH_CLIENT-VM-NF01'}); + }); + + it('ends the wait of a call made while an initialization that fails is running', async () => { + const client = new ThunderIDBrowserClient(); + const init: Promise = client.initialize({ + ...config, + applicationId: 'app-1', + clientId: undefined, + mode: 'embedded', + } as BrowserAuthConfig); + const waiting: Promise = client.isInitialized(); + + await expect(init).rejects.toMatchObject({code: 'JS-AUTH_CORE-INIT-IV01'}); + await expect(waiting).resolves.toBe(false); + }); + describe('on()', () => { it('fires http-request-start and http-request-success hooks registered before initialize()', async () => { const client = new ThunderIDBrowserClient(); diff --git a/packages/browser/src/utils/__tests__/createHttpClientFetcher.test.ts b/packages/browser/src/utils/__tests__/createHttpClientFetcher.test.ts index fc5a826d..b59d4d31 100644 --- a/packages/browser/src/utils/__tests__/createHttpClientFetcher.test.ts +++ b/packages/browser/src/utils/__tests__/createHttpClientFetcher.test.ts @@ -47,6 +47,25 @@ describe('createHttpClientFetcher', () => { await expect(response.json()).resolves.toEqual({code: 'USR-1017'}); }); + it('keeps the response headers of a non-ok response so a challenge can be read', async () => { + mockRequest.mockRejectedValueOnce( + Object.assign(new Error('Unauthorized'), { + response: { + data: {code: 'AUTH-4011'}, + headers: {'www-authenticate': 'Bearer error="insufficient_user_authentication", max_age="300"'}, + status: 401, + statusText: 'Unauthorized', + }, + }), + ); + + const response = await createHttpClientFetcher()('https://localhost:8090/x', {method: 'POST'}); + + expect(response.headers.get('WWW-Authenticate')).toBe( + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); + }); + it('rethrows a genuine network error with no attached response', async () => { mockRequest.mockRejectedValueOnce(Object.assign(new Error('Failed to fetch'), {code: 'NETWORK_ERROR'})); diff --git a/packages/browser/src/utils/createHttpClientFetcher.ts b/packages/browser/src/utils/createHttpClientFetcher.ts index d0a9ba91..8bd751f7 100644 --- a/packages/browser/src/utils/createHttpClientFetcher.ts +++ b/packages/browser/src/utils/createHttpClientFetcher.ts @@ -34,8 +34,14 @@ const createHttpClientFetcher = ( return async (url: string, config: RequestInit): Promise => { const httpClient: FetchHttpClient = FetchHttpClient.getInstance(instanceId); - const toResponse = (data: unknown, status: number, statusText: string): Response => + const toResponse = ( + data: unknown, + status: number, + statusText: string, + headers?: Record, + ): Response => ({ + headers: new Headers(headers ?? {}), json: () => Promise.resolve(data), ok: status >= 200 && status < 300, status, @@ -53,11 +59,16 @@ const createHttpClientFetcher = ( url, } as HttpRequestConfig); - return toResponse(response.data, response.status, response.statusText || ''); + return toResponse(response.data, response.status, response.statusText || '', response.headers); } catch (error) { const httpError: HttpError = error as HttpError; if (httpError?.response) { - return toResponse(httpError.response.data, httpError.response.status, httpError.response.statusText ?? ''); + return toResponse( + httpError.response.data, + httpError.response.status, + httpError.response.statusText ?? '', + httpError.response.headers, + ); } throw error; } diff --git a/packages/browser/src/utils/reauthenticationPopup.ts b/packages/browser/src/utils/reauthenticationPopup.ts new file mode 100644 index 00000000..15f2324f --- /dev/null +++ b/packages/browser/src/utils/reauthenticationPopup.ts @@ -0,0 +1,127 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDRuntimeError} from '@thunderid/javascript'; + +/** + * The message a re-sign-in popup posts to the window that opened it. + */ +export const REAUTHENTICATION_MESSAGE = 'reauthentication-callback'; + +/** + * The window name a re-sign-in popup carries, so the SDK in the popup hands the callback to its opener + * instead of signing in. + */ +export const REAUTHENTICATION_WINDOW_PREFIX = 'reauthentication-'; + +const POPUP_FEATURES = 'width=520,height=720'; + +export interface ReauthenticationMessage { + code?: string; + error?: string; + errorDescription?: string; + state?: string; + type: string; +} + +/** + * Opens the re-sign-in popup. Call it from the user action, before any `await`, so the browser lets it + * open. + * + * @param instanceId - The client instance. + * @returns The popup window. + */ +export const openReauthenticationPopup = (instanceId: number): Window => { + const popup: Window | null = window.open('', `${REAUTHENTICATION_WINDOW_PREFIX}${instanceId}`, POPUP_FEATURES); + + if (!popup) { + throw new ThunderIDRuntimeError( + 'The browser blocked the sign-in window. Allow pop-ups for this site and try again.', + 'BROWSER-REAUTHENTICATION-PB01', + 'browser', + ); + } + + return popup; +}; + +/** + * Waits for the popup to post the callback of the request with this `state`. + * + * @param popup - The popup window. + * @param state - The request's state. + * @returns The callback parameters. + */ +export const waitForReauthentication = (popup: Window, state: string): Promise => + new Promise((resolve, reject) => { + const closedCheck: number = window.setInterval(() => { + if (popup.closed) { + done(); + reject(new ThunderIDRuntimeError('The sign-in window was closed.', 'BROWSER-REAUTHENTICATION-PC01', 'browser')); + } + }, 500); + + function done(): void { + window.clearInterval(closedCheck); + window.removeEventListener('message', onMessage); + } + + function onMessage(event: MessageEvent): void { + if ( + event.origin !== window.location.origin || + event.source !== popup || + event.data?.type !== REAUTHENTICATION_MESSAGE || + event.data.state !== state + ) { + return; + } + + done(); + resolve(event.data); + } + + window.addEventListener('message', onMessage); + }); + +/** + * Whether this window is a re-sign-in popup. + * + * @returns `true` in a re-sign-in popup that has an opener. + */ +export const isReauthenticationPopup = (): boolean => + typeof window !== 'undefined' && + typeof window.name === 'string' && + window.name.startsWith(REAUTHENTICATION_WINDOW_PREFIX) && + Boolean(window.opener); + +/** + * In a re-sign-in popup that landed on the callback, hands the callback to the opener and closes the + * popup. Elsewhere it does nothing. + * + * @returns `true` when the page was a re-sign-in callback. + */ +export const completeReauthenticationInPopup = (): boolean => { + if (!isReauthenticationPopup()) { + return false; + } + + const params: URLSearchParams = new URL(window.location.href).searchParams; + const state: string | null = params.get('state'); + + if (!state) { + return false; + } + + const message: ReauthenticationMessage = { + code: params.get('code') ?? undefined, + error: params.get('error') ?? undefined, + errorDescription: params.get('error_description') ?? undefined, + state, + type: REAUTHENTICATION_MESSAGE, + }; + + (window.opener as Window).postMessage(message, window.location.origin); + window.close(); + + return true; +}; diff --git a/packages/express/src/ThunderIDExpressClient.ts b/packages/express/src/ThunderIDExpressClient.ts index 507873d0..1fa1c6ec 100644 --- a/packages/express/src/ThunderIDExpressClient.ts +++ b/packages/express/src/ThunderIDExpressClient.ts @@ -10,6 +10,7 @@ import { ThunderIDRuntimeError, Storage, TokenResponse, + UpdateMeCredentialsPayload, User, CookieConfig as NodeCookieConfig, } from '@thunderid/node'; @@ -86,7 +87,10 @@ class ThunderIDExpressClient): Promise { + public async updateUserCredentialsFromRequest( + req: express.Request, + payload: UpdateMeCredentialsPayload, + ): Promise { const cookies = req.cookies as Record | undefined; const sessionId: string | undefined = cookies?.[this.getSessionCookieName()]; return this.updateUserCredentials(payload, sessionId); diff --git a/packages/express/src/__tests__/ThunderIDExpressClient.test.ts b/packages/express/src/__tests__/ThunderIDExpressClient.test.ts index da0121d9..48bcfb63 100644 --- a/packages/express/src/__tests__/ThunderIDExpressClient.test.ts +++ b/packages/express/src/__tests__/ThunderIDExpressClient.test.ts @@ -23,7 +23,7 @@ describe('ThunderIDExpressClient', () => { }, } as unknown as express.Request; - const payload = {password: 'new-password'}; + const payload = {currentValue: 'old-password', name: 'password', newValue: 'new-password'}; await client.updateUserCredentialsFromRequest(req, payload); expect(updateCredentialsSpy).toHaveBeenCalledWith(payload, 'session-cookie-123'); diff --git a/packages/javascript/CHANGELOG.md b/packages/javascript/CHANGELOG.md index db477693..5368bb8a 100644 --- a/packages/javascript/CHANGELOG.md +++ b/packages/javascript/CHANGELOG.md @@ -2,11 +2,15 @@ No changes to this SDK since sdk/javascript/v1.27.0. -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.27.0...sdk/javascript/v1.27.1 +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.27.0...sdk/javascript/v1.27.1 ## 1.27.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.26.0...sdk/javascript/v1.27.0 +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 + +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.26.0...sdk/javascript/v1.27.0 diff --git a/packages/javascript/src/ThunderIDJavaScriptClient.ts b/packages/javascript/src/ThunderIDJavaScriptClient.ts index 48a2191b..d339cb16 100644 --- a/packages/javascript/src/ThunderIDJavaScriptClient.ts +++ b/packages/javascript/src/ThunderIDJavaScriptClient.ts @@ -30,6 +30,7 @@ import {ExtendedAuthorizeRequestUrlParams} from './models/oauth-request'; import {OIDCDiscoveryApiResponse} from './models/oidc-discovery'; import {OIDCEndpoints} from './models/oidc-endpoints'; import {LogoutTokenClaims} from './models/logout-token'; +import type {ReauthenticationOptions, ReauthenticationRequest} from './models/reauthentication'; import {SessionData, StoredFlowSession, UserSession} from './models/session'; import {Storage, TemporaryStore} from './models/store'; import { @@ -108,7 +109,7 @@ const getOrganizationUnitStorageKey = (pkceKey: string): string => `${getStateSt const REVOKE_ACCESS_TOKEN_REQUEST_TIMEOUT_MS = 10_000; /** - * The subject token type of a device secret, which the server issues as a JWT. + * The subject token type of a device secret and of a flow assertion, both JWTs. */ const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt'; @@ -160,7 +161,7 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { public async initialize(config: T, storage?: Storage): Promise { const store = storage ?? this.cacheStore; const fullConfig = config as unknown as AuthClientConfig; - const {clientId, instanceId} = fullConfig as any; + const {clientId, instanceId, mode} = fullConfig as any; if (instanceId !== undefined) { this.instanceIdValue = instanceId; @@ -200,6 +201,16 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { this.baseURL = (fullConfig as any).baseUrl ?? ''; + // An embedded sign-in exchanges its assertion at the token endpoint, which needs the client ID. Checked + // last, so a refused client still answers calls instead of failing on unset state. + if (mode === 'embedded' && !clientId) { + throw new ThunderIDRuntimeError( + 'Embedded mode needs the `clientId` of the application, next to its `applicationId`.', + 'JS-AUTH_CORE-INIT-IV01', + 'javascript', + ); + } + return true; } @@ -321,6 +332,134 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { ); } + let response: Response; + + try { + response = await this.postTokenExchange( + resolveOrganizationUnitEndpoint(discoveredTokenEndpoint, organizationUnitId, configData.baseUrl), + deviceSecret, + processOpenIDScopes(configData.scopes), + ); + } catch (error) { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-SOUDS-NE02', + 'The device secret exchange failed.', + error instanceof Error ? error.message : 'The request to exchange the device secret failed.', + ); + } + + if (!response.ok) { + const errorBody: unknown = await response.json().catch((): undefined => undefined); + const errorCode: unknown = (errorBody as {error?: unknown} | undefined)?.error; + const error: string = typeof errorCode === 'string' && errorCode ? errorCode : 'server_error'; + + // The server answers a device secret it cannot use, expired or for another user, with these. + if (error === 'invalid_request' || error === 'invalid_grant') { + await this.storageManager.removeSessionDataParameter('device_secret', sessionId); + } + + return {error}; + } + + return {tokenResponse: await this.authHelper.handleTokenResponse(response, sessionId, true)}; + } + + /** + * Exchanges the assertion a completed embedded flow returned for an access token (RFC 8693), and + * returns the session data to keep. The assertion stays as the ID token, the source of the user's + * claims. The application needs the token exchange grant. + * + * @param assertion - The `assertion` of a flow step whose `flowStatus` is `COMPLETE`. + * @returns Session data holding the issued access token, with the assertion as `id_token`. + */ + protected async exchangeFlowAssertion(assertion: string): Promise { + if ( + !(await this.storageManager.getTemporaryDataParameter( + OIDCDiscoveryConstants.Storage.StorageKeys.OPENID_PROVIDER_CONFIG_INITIATED, + )) + ) { + await this.loadOpenIDProviderConfiguration(false); + } + + const tokenEndpoint: string | undefined = (await this.oidcProviderMetaDataProvider()).token_endpoint; + const configData = await this.configProvider(); + + if (!tokenEndpoint) { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-NF01', + 'Token endpoint not found.', + 'No token endpoint was found in the OIDC provider meta data returned by the well-known endpoint.', + ); + } + + if (!configData.clientId) { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-IV02', + 'Client ID not configured.', + 'An embedded sign-in exchanges its assertion for an access token, which needs the `clientId` ' + + 'of the application.', + ); + } + + let response: Response; + + try { + // No `scope`: the issued token carries what the flow granted. + response = await this.postTokenExchange(tokenEndpoint, assertion); + } catch (error) { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-NE03', + 'The sign-in assertion exchange failed.', + error instanceof Error ? error.message : 'The request to exchange the sign-in assertion failed.', + ); + } + + if (!response.ok) { + const errorBody: unknown = await response.json().catch((): undefined => undefined); + const errorCode: unknown = (errorBody as {error?: unknown} | undefined)?.error; + + if (errorCode === 'unauthorized_client') { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-UC04', + 'The application cannot exchange the sign-in assertion.', + `An embedded sign-in needs the ${OAuth2GrantTypes.TOKEN_EXCHANGE} grant type on the application ` + + `(${getOAuthErrorMessage(errorBody, String(errorCode))}).`, + ); + } + + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-HE05', + `The sign-in assertion exchange failed with ${response.status}.`, + getOAuthErrorMessage(errorBody, 'The sign-in assertion exchange was rejected.'), + ); + } + + const tokens: {access_token?: unknown; expires_in?: unknown; scope?: unknown; token_type?: unknown} = + ((await response.json().catch((): undefined => undefined)) as Record | undefined) ?? {}; + + if (typeof tokens.access_token !== 'string' || !tokens.access_token) { + throw new ThunderIDAuthException( + 'JS-AUTH_CORE-EFA-IV06', + 'No access token in the response.', + 'The token endpoint answered the sign-in assertion exchange without an access token.', + ); + } + + return { + access_token: tokens.access_token, + created_at: Date.now(), + expires_in: typeof tokens.expires_in === 'number' ? String(tokens.expires_in) : '3600', + id_token: assertion, + scope: typeof tokens.scope === 'string' ? tokens.scope : '', + token_type: typeof tokens.token_type === 'string' ? tokens.token_type : 'Bearer', + }; + } + + /** + * Posts a token exchange (RFC 8693) for a JWT subject token, authenticating the client as configured. + */ + private async postTokenExchange(tokenEndpoint: string, subjectToken: string, scope?: string): Promise { + const configData = await this.configProvider(); const body: URLSearchParams = new URLSearchParams(); body.set('client_id', configData.clientId ?? ''); @@ -333,8 +472,12 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { } body.set('grant_type', OAuth2GrantTypes.TOKEN_EXCHANGE); - body.set('scope', processOpenIDScopes(configData.scopes)); - body.set('subject_token', deviceSecret); + + if (scope !== undefined) { + body.set('scope', scope); + } + + body.set('subject_token', subjectToken); body.set('subject_token_type', JWT_TOKEN_TYPE); const headers: Record = { @@ -347,40 +490,186 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { headers['Authorization'] = `Basic ${base64Encode(credential)}`; } - let response: Response; + return fetch(tokenEndpoint, { + body, + credentials: configData.sendCookiesInRequests ? 'include' : 'same-origin', + headers, + method: 'POST', + }); + } - try { - response = await fetch( - resolveOrganizationUnitEndpoint(discoveredTokenEndpoint, organizationUnitId, configData.baseUrl), - { - body, - credentials: configData.sendCookiesInRequests ? 'include' : 'same-origin', - headers, - method: 'POST', - }, + /** + * Builds an authorization request that signs the signed-in user in again, for a change that needs a + * recent sign-in. It asks for the configured scopes with PKCE, a new `state` and `nonce`, `max_age` + * (or `prompt=login` when `maxAge` is not given), and `id_token_hint` naming the signed-in user. + * + * @param options - How recent the sign-in must be. + * @param redirectUri - A redirect URI registered on the application. + * @param userId - The session to sign in again. + * @returns The request URL and what redeeming its code needs. + */ + protected async buildReauthenticationRequest( + options: ReauthenticationOptions, + redirectUri: string, + userId?: string, + ): Promise { + const authorizeEndpoint: string | undefined = (await this.oidcProviderMetaDataProvider()).authorization_endpoint; + + if (!authorizeEndpoint) { + throw new ThunderIDRuntimeError( + 'No authorization endpoint was found in the OpenID provider metadata.', + 'JS-AUTH_CORE-BRR-NF01', + 'javascript', ); - } catch (error) { - throw new ThunderIDAuthException( - 'JS-AUTH_CORE-SOUDS-NE02', - 'The device secret exchange failed.', - error instanceof Error ? error.message : 'The request to exchange the device secret failed.', + } + + const configData = await this.configProvider(); + const codeVerifier: string = this.cryptoHelper.getCodeVerifier(); + const state: string = this.cryptoHelper.generateState(); + const nonce: string = this.cryptoHelper.generateState(); + const signInResource: unknown = (configData.signInOptions as Record | undefined)?.['resource']; + const resource: string | undefined = typeof signInResource === 'string' ? signInResource : undefined; + const url: URL = new URL(authorizeEndpoint); + + url.searchParams.set('response_type', 'code'); + url.searchParams.set('client_id', configData.clientId ?? ''); + url.searchParams.set('redirect_uri', redirectUri); + url.searchParams.set('scope', processOpenIDScopes(configData.scopes)); + url.searchParams.set('state', state); + url.searchParams.set('nonce', nonce); + url.searchParams.set('code_challenge', await this.cryptoHelper.getCodeChallenge(codeVerifier)); + url.searchParams.set('code_challenge_method', PKCEConstants.DEFAULT_CODE_CHALLENGE_METHOD); + + if (options.maxAge !== undefined && Number.isFinite(options.maxAge) && options.maxAge >= 0) { + url.searchParams.set('max_age', String(Math.floor(options.maxAge))); + } else { + url.searchParams.set('prompt', 'login'); + } + + if (resource) { + url.searchParams.set('resource', resource); + } + + const idToken: string | undefined = (await this.storageManager.getSessionData(userId))?.id_token; + + if (idToken) { + url.searchParams.set('id_token_hint', idToken); + } + + return {codeVerifier, nonce, redirectUri, resource, state, url: url.toString()}; + } + + /** + * Redeems the code of a request from {@link buildReauthenticationRequest} and, only when the sign-in + * belongs to the signed-in user, replaces the session's tokens with the new ones. The ID token must be + * valid, carry the request's `nonce`, and name the same `sub` as the session's ID token; otherwise the + * session is left as it was. The new access token carries the new sign-in time; a refresh never would. + * + * @param authorization - The request the code answers. + * @param code - The authorization code. + * @param userId - The session to update. + * @returns The new tokens. + */ + protected async completeReauthentication( + authorization: ReauthenticationRequest, + code: string, + userId?: string, + ): Promise { + const tokenEndpoint: string | undefined = (await this.oidcProviderMetaDataProvider()).token_endpoint; + const configData = await this.configProvider(); + + if (!tokenEndpoint) { + throw new ThunderIDRuntimeError( + 'No token endpoint was found in the OpenID provider metadata.', + 'JS-AUTH_CORE-CRA-NF01', + 'javascript', ); } - if (!response.ok) { - const errorBody: unknown = await response.json().catch((): undefined => undefined); - const errorCode: unknown = (errorBody as {error?: unknown} | undefined)?.error; - const error: string = typeof errorCode === 'string' && errorCode ? errorCode : 'server_error'; + const body: URLSearchParams = new URLSearchParams({ + client_id: configData.clientId ?? '', + code, + code_verifier: authorization.codeVerifier, + grant_type: 'authorization_code', + redirect_uri: authorization.redirectUri, + }); - // The server answers a device secret it cannot use, expired or for another user, with these. - if (error === 'invalid_request' || error === 'invalid_grant') { - await this.storageManager.removeSessionDataParameter('device_secret', sessionId); - } + if (authorization.resource) { + body.set('resource', authorization.resource); + } - return {error}; + const hasSecret = Boolean(configData.clientSecret && configData.clientSecret.trim().length > 0); + const tokenEndpointAuthMethod = configData.tokenRequest?.authMethod ?? 'client_secret_basic'; + const headers: Record = { + Accept: 'application/json', + 'Content-Type': 'application/x-www-form-urlencoded', + }; + + if (hasSecret && tokenEndpointAuthMethod === 'client_secret_post') { + body.set('client_secret', configData.clientSecret!); } - return {tokenResponse: await this.authHelper.handleTokenResponse(response, sessionId, true)}; + if (hasSecret && tokenEndpointAuthMethod === 'client_secret_basic') { + const credential = `${encodeURIComponent(configData.clientId!)}:${encodeURIComponent(configData.clientSecret!)}`; + headers['Authorization'] = `Basic ${base64Encode(credential)}`; + } + + const response: Response = await fetch(tokenEndpoint, { + body, + credentials: configData.sendCookiesInRequests ? 'include' : 'same-origin', + headers, + method: 'POST', + }); + const parsed: AccessTokenApiResponse = (await response.json().catch(() => ({}))) as AccessTokenApiResponse; + + if (!response.ok || !parsed.access_token) { + throw new ThunderIDRuntimeError('The sign-in could not be completed.', 'JS-AUTH_CORE-CRA-TE01', 'javascript', { + error: (parsed as {error?: unknown}).error, + }); + } + + const idToken: string | undefined = parsed.id_token; + + if (!idToken || !(await this.authHelper.validateIdToken(idToken))) { + throw new ThunderIDRuntimeError('The sign-in returned no valid ID token.', 'JS-AUTH_CORE-CRA-IV01', 'javascript'); + } + + const claims: IdToken = this.cryptoHelper.decodeJwtToken(idToken); + + if (claims['nonce'] !== authorization.nonce) { + throw new ThunderIDRuntimeError( + 'The ID token does not carry the nonce of its request.', + 'JS-AUTH_CORE-CRA-IV02', + 'javascript', + ); + } + + const sessionIdToken: string | undefined = (await this.storageManager.getSessionData(userId))?.id_token; + const sessionSubject: string | undefined = sessionIdToken + ? this.cryptoHelper.decodeJwtToken(sessionIdToken).sub + : undefined; + + if (!sessionSubject || claims.sub !== sessionSubject) { + throw new ThunderIDRuntimeError( + 'The sign-in used a different account than the signed-in user.', + 'JS-AUTH_CORE-CRA-IV03', + 'javascript', + ); + } + + parsed.created_at = new Date().getTime(); + await this.authHelper.storeTokenResponse(parsed, userId, true); + + return { + accessToken: parsed.access_token, + authorizationDetails: parsed.authorization_details, + createdAt: parsed.created_at, + expiresIn: parsed.expires_in, + idToken: parsed.id_token, + refreshToken: parsed.refresh_token, + scope: parsed.scope, + tokenType: parsed.token_type, + }; } /** @@ -1239,7 +1528,7 @@ class ThunderIDJavaScriptClient implements ThunderIDClient { ); } - return this.authHelper.handleTokenResponse(tokenResponse, userId); + return this.authHelper.handleTokenResponse(tokenResponse, userId, false, true); } /** diff --git a/packages/javascript/src/__tests__/AuthenticationHelper.test.ts b/packages/javascript/src/__tests__/AuthenticationHelper.test.ts index 8d7d3783..c6ab4270 100644 --- a/packages/javascript/src/__tests__/AuthenticationHelper.test.ts +++ b/packages/javascript/src/__tests__/AuthenticationHelper.test.ts @@ -119,6 +119,38 @@ describe('AuthenticationHelper', () => { expect((await storageManager.getSessionData()).authorization_details).toEqual(granted); }); + it('ends the embedded sign-in mark of the session it stores into', async () => { + const storageManager = new StorageManager('test-instance', new MemoryStore()); + await storageManager.setConfigData({baseUrl: BASE_URL, clientId: 'test-client'}); + await storageManager.setSessionData({access_token: 'flow-at', embedded_sign_in: true}); + const sessionHelper = new AuthenticationHelper( + storageManager, + {} as unknown as IsomorphicCrypto, + ); + + await sessionHelper.handleTokenResponse(tokenResponse(TOKEN_BODY)); + + const session = await storageManager.getSessionData(); + expect(session.access_token).toBe('access-token'); + expect(session.embedded_sign_in).toBeUndefined(); + }); + + it('keeps the embedded sign-in mark when the response refreshes the session', async () => { + const storageManager = new StorageManager('test-instance', new MemoryStore()); + await storageManager.setConfigData({baseUrl: BASE_URL, clientId: 'test-client'}); + await storageManager.setSessionData({access_token: 'flow-at', embedded_sign_in: true}); + const sessionHelper = new AuthenticationHelper( + storageManager, + {} as unknown as IsomorphicCrypto, + ); + + await sessionHelper.handleTokenResponse(tokenResponse(TOKEN_BODY), undefined, false, true); + + const session = await storageManager.getSessionData(); + expect(session.access_token).toBe('access-token'); + expect(session.embedded_sign_in).toBe(true); + }); + it('leaves the authorization details out when the server granted none', async () => { const response = await helper.handleTokenResponse(tokenResponse(TOKEN_BODY)); diff --git a/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.reauthentication.test.ts b/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.reauthentication.test.ts new file mode 100644 index 00000000..cb1a0db7 --- /dev/null +++ b/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.reauthentication.test.ts @@ -0,0 +1,197 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment */ +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {DefaultCrypto} from '../DefaultCrypto'; +import type {Storage} from '../models/store'; +import ThunderIDJavaScriptClient from '../ThunderIDJavaScriptClient'; + +class MemoryStore implements Storage { + private store = new Map(); + + getData(key: string): Promise { + return Promise.resolve(this.store.get(key) ?? null!); + } + + setData(key: string, value: string): Promise { + this.store.set(key, value); + return Promise.resolve(); + } + + removeData(key: string): Promise { + this.store.delete(key); + return Promise.resolve(); + } +} + +const OIDC_META: Record = { + authorization_endpoint: 'https://example.com/oauth2/authorize', + issuer: 'https://example.com', + token_endpoint: 'https://example.com/oauth2/token', +}; + +const token = (claims: Record): string => + `header.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.sig`; + +const jsonResponse = (body: unknown, ok = true, status = 200): unknown => ({ + json: () => Promise.resolve(body), + ok, + status, +}); + +const SESSION_ID_TOKEN: string = token({sub: 'user-1'}); + +const newClient = async (config: Record = {}): Promise => { + const client: any = new ThunderIDJavaScriptClient(new MemoryStore(), new DefaultCrypto()); + + await client.initialize({ + afterSignInUrl: 'https://app.example.com/callback', + baseUrl: 'https://example.com', + clientId: 'test-client', + scopes: ['openid', 'profile'], + ...config, + }); + await client.storageManager.setOIDCProviderMetaData(OIDC_META); + await client.storageManager.setTemporaryDataParameter('op_config_initiated', true); + await client.storageManager.setSessionData({ + access_token: 'old-access', + id_token: SESSION_ID_TOKEN, + refresh_token: 'old-refresh', + }); + + return client; +}; + +describe('ThunderIDJavaScriptClient re-sign-in', () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + describe('buildReauthenticationRequest', () => { + it('asks for the configured scopes with max_age, id_token_hint, PKCE, state and nonce', async () => { + const client = await newClient(); + + const request = await client.buildReauthenticationRequest({maxAge: 300}, 'https://app.example.com/callback'); + const url = new URL(request.url); + + expect(`${url.origin}${url.pathname}`).toBe('https://example.com/oauth2/authorize'); + expect(url.searchParams.get('max_age')).toBe('300'); + expect(url.searchParams.has('prompt')).toBe(false); + expect(url.searchParams.get('id_token_hint')).toBe(SESSION_ID_TOKEN); + expect(url.searchParams.get('scope')).toContain('openid'); + expect(url.searchParams.get('scope')).toContain('profile'); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('code_challenge')).toBeTruthy(); + expect(url.searchParams.get('state')).toBe(request.state); + expect(url.searchParams.get('nonce')).toBe(request.nonce); + expect(request.nonce).not.toBe(request.state); + expect(url.searchParams.get('redirect_uri')).toBe('https://app.example.com/callback'); + }); + + it('asks for prompt=login when maxAge is not known', async () => { + const client = await newClient(); + + const url = new URL((await client.buildReauthenticationRequest({}, 'https://app.example.com/callback')).url); + + expect(url.searchParams.get('prompt')).toBe('login'); + expect(url.searchParams.has('max_age')).toBe(false); + }); + }); + + describe('completeReauthentication', () => { + const complete = async ( + client: any, + idTokenClaims: Record, + ): Promise<{error?: unknown; fetchMock: ReturnType; request: any}> => { + const request = await client.buildReauthenticationRequest({maxAge: 300}, 'https://app.example.com/callback'); + const fetchMock = vi.fn().mockResolvedValue( + jsonResponse({ + access_token: 'new-access', + expires_in: 3600, + id_token: token({nonce: request.nonce, ...idTokenClaims}), + refresh_token: 'new-refresh', + }), + ); + vi.stubGlobal('fetch', fetchMock); + vi.spyOn(client.authHelper, 'validateIdToken').mockResolvedValue(true); + + try { + await client.completeReauthentication(request, 'code-1'); + return {fetchMock, request}; + } catch (error) { + return {error, fetchMock, request}; + } + }; + + it('redeems the code with its verifier and replaces the session tokens for the same user', async () => { + const client = await newClient(); + const refreshSpy = vi.spyOn(client, 'refreshAccessToken'); + + const {error, fetchMock, request} = await complete(client, {auth_time: 1_800_000_000, sub: 'user-1'}); + + expect(error).toBeUndefined(); + const body = new URLSearchParams(fetchMock.mock.calls[0][1].body as URLSearchParams); + expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/oauth2/token'); + expect(body.get('grant_type')).toBe('authorization_code'); + expect(body.get('code')).toBe('code-1'); + expect(body.get('code_verifier')).toBe(request.codeVerifier); + + const session = await client.storageManager.getSessionData(); + expect(session.access_token).toBe('new-access'); + expect(session.refresh_token).toBe('new-refresh'); + expect(refreshSpy).not.toHaveBeenCalled(); + }); + + it('keeps the session when the sign-in names another user', async () => { + const client = await newClient(); + + const {error} = await complete(client, {sub: 'someone-else'}); + + expect(error).toMatchObject({code: 'JS-AUTH_CORE-CRA-IV03'}); + const session = await client.storageManager.getSessionData(); + expect(session.access_token).toBe('old-access'); + expect(session.id_token).toBe(SESSION_ID_TOKEN); + }); + + it('keeps the session when the ID token does not carry the nonce', async () => { + const client = await newClient(); + + const {error} = await complete(client, {nonce: 'another-nonce', sub: 'user-1'}); + + expect(error).toMatchObject({code: 'JS-AUTH_CORE-CRA-IV02'}); + expect((await client.storageManager.getSessionData()).access_token).toBe('old-access'); + }); + + it('keeps the session when the ID token is not valid', async () => { + const client = await newClient(); + const request = await client.buildReauthenticationRequest({maxAge: 300}, 'https://app.example.com/callback'); + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + jsonResponse({access_token: 'new-access', id_token: token({nonce: request.nonce, sub: 'user-1'})}), + ), + ); + vi.spyOn(client.authHelper, 'validateIdToken').mockResolvedValue(false); + + await expect(client.completeReauthentication(request, 'code-1')).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-CRA-IV01', + }); + expect((await client.storageManager.getSessionData()).access_token).toBe('old-access'); + }); + + it('keeps the session when the token request is refused', async () => { + const client = await newClient(); + const request = await client.buildReauthenticationRequest({maxAge: 300}, 'https://app.example.com/callback'); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({error: 'invalid_grant'}, false, 400))); + + await expect(client.completeReauthentication(request, 'code-1')).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-CRA-TE01', + }); + expect((await client.storageManager.getSessionData()).access_token).toBe('old-access'); + }); + }); +}); diff --git a/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.session.test.ts b/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.session.test.ts index e0a0c673..543a766d 100644 --- a/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.session.test.ts +++ b/packages/javascript/src/__tests__/ThunderIDJavaScriptClient.session.test.ts @@ -336,4 +336,163 @@ describe('ThunderIDJavaScriptClient', () => { expect(fetchMock).not.toHaveBeenCalled(); }); }); + + describe('embedded mode configuration', () => { + it('refuses to initialize without a client ID', async () => { + const client: any = new ThunderIDJavaScriptClient(new MemoryStore(), new DefaultCrypto()); + + await expect( + client.initialize({applicationId: 'app-1', baseUrl: 'https://example.com', mode: 'embedded'}), + ).rejects.toMatchObject({code: 'JS-AUTH_CORE-INIT-IV01'}); + }); + + it('initializes with an application ID and a client ID', async () => { + const client: any = new ThunderIDJavaScriptClient(new MemoryStore(), new DefaultCrypto()); + + await expect( + client.initialize({applicationId: 'app-1', baseUrl: 'https://example.com', clientId: 'c1', mode: 'embedded'}), + ).resolves.toBe(true); + }); + + it('leaves redirect mode without a client ID to the sign-in request', async () => { + const client: any = new ThunderIDJavaScriptClient(new MemoryStore(), new DefaultCrypto()); + + await expect(client.initialize({baseUrl: 'https://example.com'})).resolves.toBe(true); + }); + }); + + describe('exchangeFlowAssertion()', () => { + const ASSERTION = 'flow.assertion.jwt'; + + it('exchanges the assertion for an access token without a scope, and keeps it as the ID token', async () => { + const client = await newClient(); + const fetchMock = vi + .fn() + .mockResolvedValue(jsonResponse({access_token: 'at', expires_in: 900, scope: 'self', token_type: 'Bearer'})); + vi.stubGlobal('fetch', fetchMock); + + const session = await client.exchangeFlowAssertion(ASSERTION); + + const [url, init] = fetchMock.mock.calls[0]; + const body: URLSearchParams = init.body; + expect(url).toBe('https://example.com/oauth2/token'); + expect(Object.fromEntries(body)).toEqual({ + client_id: 'test-client', + grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', + subject_token: ASSERTION, + subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', + }); + expect(init.headers).not.toHaveProperty('Authorization'); + expect(session).toMatchObject({ + access_token: 'at', + expires_in: '900', + id_token: ASSERTION, + scope: 'self', + token_type: 'Bearer', + }); + expect((await client.storageManager.getSessionData())?.access_token).toBeUndefined(); + }); + + it('authenticates a confidential client with its secret', async () => { + const client = await newClient({clientSecret: 'secret'}); + const fetchMock = vi.fn().mockResolvedValue(jsonResponse({access_token: 'at', expires_in: 900})); + vi.stubGlobal('fetch', fetchMock); + + await client.exchangeFlowAssertion(ASSERTION); + + expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe( + `Basic ${Buffer.from('test-client:secret').toString('base64')}`, + ); + }); + + it('sends the secret in the body for client_secret_post', async () => { + const client = await newClient({clientSecret: 'secret', tokenRequest: {authMethod: 'client_secret_post'}}); + const fetchMock = vi.fn().mockResolvedValue(jsonResponse({access_token: 'at', expires_in: 900})); + vi.stubGlobal('fetch', fetchMock); + + await client.exchangeFlowAssertion(ASSERTION); + + expect(fetchMock.mock.calls[0][1].body.get('client_secret')).toBe('secret'); + expect(fetchMock.mock.calls[0][1].headers).not.toHaveProperty('Authorization'); + }); + + it('reports a request that does not reach the server', async () => { + const client = await newClient(); + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline'))); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-EFA-NE03', + message: 'offline', + }); + }); + + it('names the missing grant when the application cannot exchange the assertion', async () => { + const client = await newClient(); + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(jsonResponse({error: 'unauthorized_client', error_description: 'x'}, false, 400)), + ); + + const error: Error = await client.exchangeFlowAssertion(ASSERTION).catch((e: Error) => e); + + expect(error).toMatchObject({code: 'JS-AUTH_CORE-EFA-UC04'}); + expect(error.message).toContain('urn:ietf:params:oauth:grant-type:token-exchange'); + }); + + it('reports any other rejection with the server message', async () => { + const client = await newClient(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({error: 'invalid_grant'}, false, 400))); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-EFA-HE05', + message: 'invalid_grant', + }); + }); + + it('reports a server without the grant as a rejection, not as an application setting', async () => { + const client = await newClient(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({error: 'unsupported_grant_type'}, false, 400))); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-EFA-HE05', + message: 'unsupported_grant_type', + }); + }); + + it('refuses a response without an access token', async () => { + const client = await newClient(); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({token_type: 'Bearer'}))); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({code: 'JS-AUTH_CORE-EFA-IV06'}); + }); + + it('needs a token endpoint', async () => { + const client = await newClient(); + await client.storageManager.setOIDCProviderMetaData({...OIDC_META, token_endpoint: undefined}); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({code: 'JS-AUTH_CORE-EFA-NF01'}); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses a successful response that is not JSON', async () => { + const client = await newClient(); + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({json: () => Promise.reject(new SyntaxError('x')), ok: true, status: 200}), + ); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({code: 'JS-AUTH_CORE-EFA-IV06'}); + }); + + it('needs the client ID', async () => { + const client = await newClient({clientId: undefined}); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + await expect(client.exchangeFlowAssertion(ASSERTION)).rejects.toMatchObject({code: 'JS-AUTH_CORE-EFA-IV02'}); + expect(fetchMock).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/javascript/src/api/account/__tests__/updateMeCredentials.test.ts b/packages/javascript/src/api/account/__tests__/updateMeCredentials.test.ts index 7677d798..b6570a06 100644 --- a/packages/javascript/src/api/account/__tests__/updateMeCredentials.test.ts +++ b/packages/javascript/src/api/account/__tests__/updateMeCredentials.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; +import StepUpRequiredError from '../../../errors/StepUpRequiredError'; import ThunderIDAPIError from '../../../errors/ThunderIDAPIError'; import updateMeCredentials from '../updateMeCredentials'; @@ -10,7 +11,7 @@ describe('updateMeCredentials', (): void => { vi.resetAllMocks(); }); - it('should wrap the payload under attributes and resolve with no value on 204', async (): Promise => { + it('should send the name and new value and resolve with no value on 204', async (): Promise => { global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 204, @@ -20,7 +21,7 @@ describe('updateMeCredentials', (): void => { const url = 'https://localhost:8090/users/me/update-credentials'; const result: void = await updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url, }); @@ -35,10 +36,10 @@ describe('updateMeCredentials', (): void => { expect((init.headers as Record)['Accept']).toBe('application/json'); const parsed = JSON.parse(init.body as string) as Record; - expect(parsed).toEqual({attributes: {password: 'n3wP@ssword!'}}); + expect(parsed).toEqual({name: 'password', newValue: 'n3wP@ssword!'}); }); - it('should support updating more than one credential in a single call', async (): Promise => { + it('should send the current value when one is given', async (): Promise => { global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 204, @@ -46,22 +47,44 @@ describe('updateMeCredentials', (): void => { }); await updateMeCredentials({ - payload: { - password: 'n3wP@ss!', - pin: '1234', - }, + payload: {currentValue: '0ldP@ss!', name: 'pin', newValue: '1234'}, url: 'https://localhost:8090/users/me/update-credentials', }); const [, init] = (fetch as unknown as Mock).mock.calls[0] as [string, RequestInit]; const parsed = JSON.parse(init.body as string) as Record; - expect(parsed).toEqual({ - attributes: { - password: 'n3wP@ss!', - pin: '1234', - }, + expect(parsed).toEqual({currentValue: '0ldP@ss!', name: 'pin', newValue: '1234'}); + expect(parsed).not.toHaveProperty('attributes'); + }); + + it('should leave out an empty current value', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + status: 204, + text: () => Promise.resolve(''), }); + + await updateMeCredentials({ + payload: {currentValue: '', name: 'password', newValue: 'n3wP@ssword!'}, + url: 'https://localhost:8090/users/me/update-credentials', + }); + + const [, init] = (fetch as unknown as Mock).mock.calls[0] as [string, RequestInit]; + + expect(JSON.parse(init.body as string)).toEqual({name: 'password', newValue: 'n3wP@ssword!'}); + }); + + it.each([ + ['a blank name', {name: ' ', newValue: 'n3wP@ssword!'}], + ['an empty new value', {name: 'password', newValue: ''}], + ])('should refuse %s before any request', async (_label: string, payload): Promise => { + global.fetch = vi.fn(); + + await expect( + updateMeCredentials({payload, url: 'https://localhost:8090/users/me/update-credentials'}), + ).rejects.toMatchObject({code: 'updateMeCredentials-ValidationError-002'}); + expect(fetch).not.toHaveBeenCalled(); }); it('should never read the response body on success', async (): Promise => { @@ -75,7 +98,7 @@ describe('updateMeCredentials', (): void => { }); await updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }); @@ -89,7 +112,10 @@ describe('updateMeCredentials', (): void => { text: () => Promise.resolve(''), }); - await updateMeCredentials({baseUrl: 'https://localhost:8090', payload: {password: 'n3wP@ssword!'}}); + await updateMeCredentials({ + baseUrl: 'https://localhost:8090', + payload: {name: 'password', newValue: 'n3wP@ssword!'}, + }); const [calledUrl] = (fetch as unknown as Mock).mock.calls[0] as [string, RequestInit]; @@ -103,7 +129,10 @@ describe('updateMeCredentials', (): void => { text: () => Promise.resolve(''), }); - await updateMeCredentials({baseUrl: 'https://localhost:8090/', payload: {password: 'n3wP@ssword!'}}); + await updateMeCredentials({ + baseUrl: 'https://localhost:8090/', + payload: {name: 'password', newValue: 'n3wP@ssword!'}, + }); const [calledUrl] = (fetch as unknown as Mock).mock.calls[0] as [string, RequestInit]; @@ -121,7 +150,7 @@ describe('updateMeCredentials', (): void => { await updateMeCredentials({ fetcher, - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }); @@ -132,10 +161,14 @@ describe('updateMeCredentials', (): void => { it('should throw a validation error for a malformed URL', async (): Promise => { global.fetch = vi.fn(); - await expect(updateMeCredentials({payload: {password: 'x'}, url: 'not-a-url'})).rejects.toThrow(ThunderIDAPIError); + await expect(updateMeCredentials({payload: {name: 'password', newValue: 'x'}, url: 'not-a-url'})).rejects.toThrow( + ThunderIDAPIError, + ); expect(fetch).not.toHaveBeenCalled(); - await expect(updateMeCredentials({payload: {password: 'x'}, url: 'not-a-url'})).rejects.toMatchObject({ + await expect( + updateMeCredentials({payload: {name: 'password', newValue: 'x'}, url: 'not-a-url'}), + ).rejects.toMatchObject({ code: 'updateMeCredentials-ValidationError-001', }); }); @@ -156,7 +189,7 @@ describe('updateMeCredentials', (): void => { await expect( updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }), ).rejects.toMatchObject({ @@ -165,12 +198,112 @@ describe('updateMeCredentials', (): void => { }); }); + it('should carry the server code and a readable message for a wrong current value', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 403, + statusText: 'Forbidden', + text: () => + Promise.resolve( + JSON.stringify({ + code: 'USR-1048', + description: { + defaultValue: 'The current value does not match the credential', + key: 'error.userservice.invalid_current_credential_description', + }, + message: {defaultValue: 'Invalid current credential', key: 'error.userservice.invalid_current_credential'}, + }), + ), + }); + + const error: ThunderIDAPIError = await updateMeCredentials({ + payload: {currentValue: 'wrong', name: 'password', newValue: 'n3wP@ssword!'}, + url: 'https://localhost:8090/users/me/update-credentials', + }).catch((caught: ThunderIDAPIError) => caught); + + expect(error.statusCode).toBe(403); + expect(error.serverError?.code).toBe('USR-1048'); + expect(error.message).toBe('Failed to update user credentials: Invalid current credential'); + expect(error.authenticationChallenge).toBeUndefined(); + }); + + it('should read the challenge of a 401 that asks for a recent sign-in', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + headers: new Headers({ + 'WWW-Authenticate': + 'Bearer error="insufficient_user_authentication", error_description="A more recent authentication is required", max_age="300"', + }), + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => + Promise.resolve( + JSON.stringify({ + code: 'AUTH-4011', + message: { + defaultValue: 'Recent authentication required', + key: 'error.security.recent_authentication_required', + }, + }), + ), + }); + + const error: ThunderIDAPIError = await updateMeCredentials({ + payload: {name: 'pin', newValue: '1234'}, + url: 'https://localhost:8090/users/me/update-credentials', + }).catch((caught: ThunderIDAPIError) => caught); + + expect(error).toBeInstanceOf(StepUpRequiredError); + expect(error.code).toBe('updateMeCredentials-StepUpRequired-001'); + expect((error as StepUpRequiredError).maxAge).toBe(300); + expect(error.statusCode).toBe(401); + expect(error.serverError?.code).toBe('AUTH-4011'); + expect(error.authenticationChallenge).toEqual({ + error: 'insufficient_user_authentication', + errorDescription: 'A more recent authentication is required', + maxAge: 300, + }); + }); + + it('should read the challenge from the body when the header is not readable', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => + Promise.resolve( + JSON.stringify({ + code: 'AUTH-4011', + description: { + defaultValue: + 'Authenticate again: this change needs an authentication within the last {{param(maxAge)}} seconds', + key: 'error.security.recent_authentication_required_description', + params: {maxAge: '120'}, + }, + message: { + defaultValue: 'Recent authentication required', + key: 'error.security.recent_authentication_required', + }, + }), + ), + }); + + const error: ThunderIDAPIError = await updateMeCredentials({ + payload: {name: 'pin', newValue: '1234'}, + url: 'https://localhost:8090/users/me/update-credentials', + }).catch((caught: ThunderIDAPIError) => caught); + + expect(error.authenticationChallenge).toEqual({error: 'insufficient_user_authentication', maxAge: 120}); + expect(error).toBeInstanceOf(StepUpRequiredError); + expect((error as StepUpRequiredError).maxAge).toBe(120); + }); + it('should throw a network error when the request itself fails', async (): Promise => { global.fetch = vi.fn().mockRejectedValue(new Error('connection refused')); await expect( updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }), ).rejects.toMatchObject({ diff --git a/packages/javascript/src/api/account/__tests__/updateMeProfile.test.ts b/packages/javascript/src/api/account/__tests__/updateMeProfile.test.ts index bfcb2cbd..c22e0f6d 100644 --- a/packages/javascript/src/api/account/__tests__/updateMeProfile.test.ts +++ b/packages/javascript/src/api/account/__tests__/updateMeProfile.test.ts @@ -1,7 +1,8 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; +import StepUpRequiredError from '../../../errors/StepUpRequiredError'; import ThunderIDAPIError from '../../../errors/ThunderIDAPIError'; import type {User} from '../../../models/user'; import updateMeProfile from '../updateMeProfile'; @@ -162,6 +163,61 @@ describe('updateMeProfile', (): void => { ); }); + it('should throw a StepUpRequiredError when an email change needs a recent sign-in', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + headers: new Headers({ + 'WWW-Authenticate': 'Bearer error="insufficient_user_authentication", max_age="300"', + }), + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => + Promise.resolve(JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}})), + }); + + const error: unknown = await updateMeProfile({ + baseUrl: 'https://localhost:8090', + payload: {email: 'new@example.com'}, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StepUpRequiredError); + expect(error).toMatchObject({code: 'updateMeProfile-StepUpRequired-001', maxAge: 300, statusCode: 401}); + }); + + it('should read a step-up from the AUTH-4011 body when the header is not readable', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => Promise.resolve(JSON.stringify({code: 'AUTH-4011', description: {params: {maxAge: '60'}}})), + }); + + const error: unknown = await updateMeProfile({ + baseUrl: 'https://localhost:8090', + payload: {mobile: '+15550100'}, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StepUpRequiredError); + expect(error).toMatchObject({maxAge: 60}); + }); + + it('should keep a plain API error for a 401 that is not a step-up', async (): Promise => { + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => Promise.resolve(JSON.stringify({code: 'AUTH-4010', message: {defaultValue: 'Unauthorized'}})), + }); + + const error: unknown = await updateMeProfile({baseUrl: 'https://localhost:8090', payload: {a: 'b'}}).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(ThunderIDAPIError); + expect(error).not.toBeInstanceOf(StepUpRequiredError); + expect(error).toMatchObject({code: 'updateMeProfile-ResponseError-001'}); + }); + it('should handle network or unknown errors with the generic message', async (): Promise => { // Rejection with Error global.fetch = vi.fn().mockRejectedValue(new Error('Network error')); diff --git a/packages/javascript/src/api/account/updateMeCredentials.ts b/packages/javascript/src/api/account/updateMeCredentials.ts index 619e55d7..f21befc1 100644 --- a/packages/javascript/src/api/account/updateMeCredentials.ts +++ b/packages/javascript/src/api/account/updateMeCredentials.ts @@ -2,6 +2,26 @@ // SPDX-License-Identifier: Apache-2.0 import ThunderIDAPIError from '../../errors/ThunderIDAPIError'; +import createApiResponseError from '../../utils/createApiResponseError'; + +/** + * One credential to set for the signed-in user. + */ +export interface UpdateMeCredentialsPayload { + /** + * The credential's current value. Required when the user holds the credential, and not used when + * the user sets it for the first time. + */ + currentValue?: string; + /** + * The credential attribute the user type's schema declares, such as `password` or `pin`. + */ + name: string; + /** + * The value to set. + */ + newValue: string; +} /** * Configuration for the updateMeCredentials request @@ -17,13 +37,9 @@ export interface UpdateMeCredentialsConfig extends Omit Promise; /** - * The new values to set, keyed by credential name, whatever attribute the user's entity - * type schema declares `credential: true` (for example `password` or `pin`). One or more - * may be included in a single call. The server requires each value here to be a plain - * string, and the whole map to be wrapped under `attributes` on the wire, which this - * function does; do not pass a pre-wrapped `{attributes: ...}` object. + * The credential to set: its name, its current value when the user holds it, and the new value. */ - payload: Record; + payload: UpdateMeCredentialsPayload; /** * The absolute API endpoint. */ @@ -31,11 +47,18 @@ export interface UpdateMeCredentialsConfig extends Omit { * const response = await httpClient({url, method: config.method, headers: config.headers, data: config.body}); * return { * ok: response.status >= 200 && response.status < 300, * status: response.status, * statusText: response.statusText, + * headers: new Headers(response.headers), * json: () => Promise.resolve(response.data), * text: () => Promise.resolve(typeof response.data === 'string' ? response.data : JSON.stringify(response.data)) * } as Response; @@ -87,13 +111,27 @@ const updateMeCredentials = async ({ ); } + if (!payload?.name?.trim() || !payload?.newValue) { + throw new ThunderIDAPIError( + 'Both a credential name and a new value are required.', + 'updateMeCredentials-ValidationError-002', + 'javascript', + 400, + 'The `payload` must carry a non-empty `name` and `newValue`.', + ); + } + const fetchFn: typeof fetch = fetcher ?? fetch; const resolvedUrl: string = url ?? `${baseUrl?.replace(/\/$/, '')}/users/me/update-credentials`; const requestInit: RequestInit = { ...requestConfig, method: 'POST', - body: JSON.stringify({attributes: payload}), + body: JSON.stringify({ + name: payload.name, + ...(payload.currentValue ? {currentValue: payload.currentValue} : {}), + newValue: payload.newValue, + }), headers: { ...requestConfig.headers, Accept: 'application/json', @@ -107,14 +145,7 @@ const updateMeCredentials = async ({ if (!response?.ok) { const errorText: string = await response.text(); - throw new ThunderIDAPIError( - errorText, - 'updateMeCredentials-ResponseError-001', - 'javascript', - response.status, - response.statusText, - 'Failed to update user credentials', - ); + throw createApiResponseError('updateMeCredentials', errorText, response, 'Failed to update user credentials'); } } catch (error) { if (error instanceof ThunderIDAPIError) { diff --git a/packages/javascript/src/api/account/updateMeProfile.ts b/packages/javascript/src/api/account/updateMeProfile.ts index a7618732..51db382d 100644 --- a/packages/javascript/src/api/account/updateMeProfile.ts +++ b/packages/javascript/src/api/account/updateMeProfile.ts @@ -1,7 +1,8 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import ThunderIDAPIError from '../../errors/ThunderIDAPIError'; +import createApiResponseError from '../../utils/createApiResponseError'; import {User} from '../../models/user'; /** @@ -111,14 +112,7 @@ const updateMeProfile = async ({ if (!response?.ok) { const errorText: string = await response.text(); - throw new ThunderIDAPIError( - errorText, - 'updateMeProfile-ResponseError-001', - 'javascript', - response.status, - response.statusText, - 'Failed to update user profile', - ); + throw createApiResponseError('updateMeProfile', errorText, response, 'Failed to update user profile'); } const user: User = (await response.json()) as User; diff --git a/packages/javascript/src/errors/StepUpRequiredError.ts b/packages/javascript/src/errors/StepUpRequiredError.ts new file mode 100644 index 00000000..9983c5c0 --- /dev/null +++ b/packages/javascript/src/errors/StepUpRequiredError.ts @@ -0,0 +1,51 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import ThunderIDAPIError from './ThunderIDAPIError'; + +export {INSUFFICIENT_USER_AUTHENTICATION} from '../utils/parseAuthenticationChallenge'; + +/** + * Thrown when a change needs a more recent sign-in, such as setting a credential the user does not hold + * yet or changing an email address. Sign the user in again with `maxAge` as `max_age` (for example with + * `reauthenticate`) and retry the change once. Refreshing the access token does not help: a refreshed + * token keeps the original sign-in time. + * + * @example + * ```typescript + * try { + * await updateMeProfile({baseUrl, payload, fetcher}); + * } catch (error) { + * if (error instanceof StepUpRequiredError) { + * await client.reauthenticate({maxAge: error.maxAge}); + * await updateMeProfile({baseUrl, payload, fetcher}); + * } + * } + * ``` + */ +export default class StepUpRequiredError extends ThunderIDAPIError { + /** + * How recent, in seconds, the sign-in must be, when the server said. + */ + public readonly maxAge?: number; + + constructor( + message: string, + code: string, + origin: string, + statusCode?: number, + statusText?: string, + prefix?: string, + wwwAuthenticate?: string | null, + ) { + super(message, code, origin, statusCode, statusText, prefix, wwwAuthenticate); + + this.maxAge = this.authenticationChallenge?.maxAge; + + Object.defineProperty(this, 'name', { + configurable: true, + value: 'StepUpRequiredError', + writable: true, + }); + } +} diff --git a/packages/javascript/src/errors/ThunderIDAPIError.ts b/packages/javascript/src/errors/ThunderIDAPIError.ts index 1c6e1663..cf611b76 100644 --- a/packages/javascript/src/errors/ThunderIDAPIError.ts +++ b/packages/javascript/src/errors/ThunderIDAPIError.ts @@ -1,8 +1,9 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import ThunderIDError from './ThunderIDError'; -import {ServerError} from '../models/api'; +import {AuthenticationChallenge, ServerError} from '../models/api'; +import parseAuthenticationChallenge from '../utils/parseAuthenticationChallenge'; import parseApiErrorMessage from '../utils/parseApiErrorMessage'; /** @@ -42,6 +43,20 @@ const parseServerError = (body: string): ServerError | undefined => { * ``` */ export default class ThunderIDAPIError extends ThunderIDError { + /** + * The error the server returned, when its response body was an error envelope: the server's own + * error code, and its message and description with their translation keys and parameters. Use it to + * show a message specific to the server's code. + */ + public readonly serverError?: ServerError; + + /** + * The challenge of a `401` that asks for a more recent sign-in (RFC 9470), from the + * `WWW-Authenticate` header or, when the header is not readable, from an `AUTH-4011` body. Sign the + * user in again with its `maxAge` and retry. + */ + public readonly authenticationChallenge?: AuthenticationChallenge; + /** * Creates an instance of ThunderIDAPIError. * @@ -51,15 +66,9 @@ export default class ThunderIDAPIError extends ThunderIDError { * @param statusCode - HTTP status code of the failed request * @param statusText - HTTP status text of the failed request * @param prefix - Optional prefix prepended to the resolved message + * @param wwwAuthenticate - The response's `WWW-Authenticate` header value, read into `authenticationChallenge` * @constructor */ - /** - * The error the server returned, when its response body was an error envelope: the server's own - * error code, and its message and description with their translation keys and parameters. Use it to - * show a message specific to the server's code. - */ - public readonly serverError?: ServerError; - constructor( message: string, code: string, @@ -67,12 +76,15 @@ export default class ThunderIDAPIError extends ThunderIDError { public readonly statusCode?: number, public readonly statusText?: string, prefix?: string, + wwwAuthenticate?: string | null, ) { const parsed: string = parseApiErrorMessage(message); const resolvedMessage: string = prefix ? `${prefix}: ${parsed}` : parsed; super(resolvedMessage, code, origin); this.serverError = parseServerError(message); + this.authenticationChallenge = + statusCode === 401 ? parseAuthenticationChallenge(wwwAuthenticate, this.serverError) : undefined; Object.defineProperty(this, 'name', { configurable: true, diff --git a/packages/javascript/src/i18n/models/i18n.ts b/packages/javascript/src/i18n/models/i18n.ts index 81b8a4cb..1a7c486c 100644 --- a/packages/javascript/src/i18n/models/i18n.ts +++ b/packages/javascript/src/i18n/models/i18n.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 /* eslint-disable typescript-sort-keys/interface */ @@ -148,6 +148,9 @@ export interface I18nTranslations { /* |---------------------------------------------------------------| */ 'user.change_password.heading': string; + 'user.change_password.current.label': string; + 'user.change_password.current.placeholder': string; + 'user.change_password.current.hint': string; 'user.change_password.new.label': string; 'user.change_password.new.placeholder': string; 'user.change_password.confirm.label': string; @@ -157,6 +160,17 @@ export interface I18nTranslations { 'user.change_password.success': string; 'user.change_password.mismatch.error': string; 'user.change_password.generic.error': string; + 'user.change_password.current.required.error': string; + 'user.change_password.current.invalid.error': string; + 'user.change_password.reauthentication.error': string; + 'user.reauthentication.required.error': string; + 'user.reauthentication.failed.error': string; + 'user.reauthentication.popup_blocked.error': string; + 'user.reauthentication.different_user.error': string; + 'user.reauthentication.heading': string; + 'user.reauthentication.description': string; + 'user.reauthentication.unsupported_option.error': string; + 'user.reauthentication.buttons.close.text': string; 'user.change_password.unavailable.heading': string; 'user.change_password.unavailable.description': string; 'user.agents.title': string; diff --git a/packages/javascript/src/i18n/translations/en-US.ts b/packages/javascript/src/i18n/translations/en-US.ts index b7cf2595..1d0ea886 100644 --- a/packages/javascript/src/i18n/translations/en-US.ts +++ b/packages/javascript/src/i18n/translations/en-US.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -148,6 +148,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': 'Change {credential}', + 'user.change_password.current.label': 'Current {credential}', + 'user.change_password.current.placeholder': 'Enter your current {credentialLower}', + 'user.change_password.current.hint': 'Leave this empty if you have not set one yet.', 'user.change_password.new.label': 'New {credential}', 'user.change_password.new.placeholder': 'Enter your new {credentialLower}', 'user.change_password.confirm.label': 'Confirm New {credential}', @@ -157,6 +160,18 @@ const translations: I18nTranslations = { 'user.change_password.success': 'Your {credentialLower} has been updated.', 'user.change_password.mismatch.error': '{credential}s do not match.', 'user.change_password.generic.error': 'An error occurred while updating your {credentialLower}. Please try again.', + 'user.change_password.current.required.error': 'Enter your current {credentialLower}.', + 'user.change_password.current.invalid.error': 'The current {credentialLower} is incorrect.', + 'user.change_password.reauthentication.error': 'Sign in again to set your {credentialLower}.', + 'user.reauthentication.required.error': 'Sign in again to save this change.', + 'user.reauthentication.failed.error': 'Signing in again did not finish. Try again.', + 'user.reauthentication.popup_blocked.error': 'Allow pop-ups for this site, then try again.', + 'user.reauthentication.different_user.error': + 'You signed in with a different account. Sign in as yourself and try again.', + 'user.reauthentication.heading': 'Sign in again', + 'user.reauthentication.description': 'Confirm it is you to save this change.', + 'user.reauthentication.unsupported_option.error': 'This sign-in option is not available here. Choose another one.', + 'user.reauthentication.buttons.close.text': 'Close', 'user.change_password.unavailable.heading': '{credential} changes unavailable', 'user.change_password.unavailable.description': 'Please contact your administrator.', diff --git a/packages/javascript/src/i18n/translations/fr-FR.ts b/packages/javascript/src/i18n/translations/fr-FR.ts index 41720daa..25fce3ee 100644 --- a/packages/javascript/src/i18n/translations/fr-FR.ts +++ b/packages/javascript/src/i18n/translations/fr-FR.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -150,6 +150,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': 'Modifier {credential}', + 'user.change_password.current.label': '{credential} actuel', + 'user.change_password.current.placeholder': 'Entrez votre {credentialLower} actuel', + 'user.change_password.current.hint': "Laissez ce champ vide si vous n'en avez pas encore défini.", 'user.change_password.new.label': 'Nouveau {credential}', 'user.change_password.new.placeholder': 'Entrez votre nouveau {credentialLower}', 'user.change_password.confirm.label': 'Confirmer le nouveau {credential}', @@ -160,6 +163,19 @@ const translations: I18nTranslations = { 'user.change_password.mismatch.error': 'Les {credentialLower}s ne correspondent pas.', 'user.change_password.generic.error': 'Une erreur est survenue lors de la mise à jour de votre {credentialLower}. Veuillez réessayer.', + 'user.change_password.current.required.error': 'Entrez votre {credentialLower} actuel.', + 'user.change_password.current.invalid.error': 'Le {credentialLower} actuel est incorrect.', + 'user.change_password.reauthentication.error': 'Reconnectez-vous pour définir votre {credentialLower}.', + 'user.reauthentication.required.error': 'Reconnectez-vous pour enregistrer cette modification.', + 'user.reauthentication.failed.error': "La reconnexion n'a pas abouti. Réessayez.", + 'user.reauthentication.popup_blocked.error': 'Autorisez les fenêtres pop-up pour ce site, puis réessayez.', + 'user.reauthentication.different_user.error': + 'Vous vous êtes connecté avec un autre compte. Connectez-vous avec votre compte et réessayez.', + 'user.reauthentication.heading': 'Reconnectez-vous', + 'user.reauthentication.description': 'Confirmez votre identité pour enregistrer cette modification.', + 'user.reauthentication.unsupported_option.error': + "Cette option de connexion n'est pas disponible ici. Choisissez-en une autre.", + 'user.reauthentication.buttons.close.text': 'Fermer', 'user.change_password.unavailable.heading': 'Modification du {credentialLower} indisponible', 'user.change_password.unavailable.description': 'Veuillez contacter votre administrateur.', diff --git a/packages/javascript/src/i18n/translations/hi-IN.ts b/packages/javascript/src/i18n/translations/hi-IN.ts index d46272eb..7a7f87c6 100644 --- a/packages/javascript/src/i18n/translations/hi-IN.ts +++ b/packages/javascript/src/i18n/translations/hi-IN.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -147,6 +147,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': '{credential} बदलें', + 'user.change_password.current.label': 'वर्तमान {credential}', + 'user.change_password.current.placeholder': 'अपना वर्तमान {credentialLower} दर्ज करें', + 'user.change_password.current.hint': 'यदि आपने अभी तक इसे सेट नहीं किया है तो इसे खाली छोड़ दें।', 'user.change_password.new.label': 'नया {credential}', 'user.change_password.new.placeholder': 'अपना नया {credentialLower} दर्ज करें', 'user.change_password.confirm.label': 'नए {credential} की पुष्टि करें', @@ -156,6 +159,18 @@ const translations: I18nTranslations = { 'user.change_password.success': 'आपका {credentialLower} अपडेट कर दिया गया है।', 'user.change_password.mismatch.error': '{credential} मेल नहीं खाते।', 'user.change_password.generic.error': 'आपका {credentialLower} अपडेट करते समय त्रुटि हुई। कृपया पुनः प्रयास करें।', + 'user.change_password.current.required.error': 'अपना वर्तमान {credentialLower} दर्ज करें।', + 'user.change_password.current.invalid.error': 'वर्तमान {credentialLower} गलत है।', + 'user.change_password.reauthentication.error': 'अपना {credentialLower} सेट करने के लिए फिर से साइन इन करें।', + 'user.reauthentication.required.error': 'यह बदलाव सहेजने के लिए फिर से साइन इन करें।', + 'user.reauthentication.failed.error': 'फिर से साइन इन पूरा नहीं हुआ। पुनः प्रयास करें।', + 'user.reauthentication.popup_blocked.error': 'इस साइट के लिए पॉप-अप की अनुमति दें, फिर पुनः प्रयास करें।', + 'user.reauthentication.different_user.error': + 'आपने किसी दूसरे खाते से साइन इन किया। अपने खाते से साइन इन करें और पुनः प्रयास करें।', + 'user.reauthentication.heading': 'फिर से साइन इन करें', + 'user.reauthentication.description': 'यह बदलाव सहेजने के लिए पुष्टि करें कि यह आप ही हैं।', + 'user.reauthentication.unsupported_option.error': 'यह साइन इन विकल्प यहाँ उपलब्ध नहीं है। कोई दूसरा विकल्प चुनें।', + 'user.reauthentication.buttons.close.text': 'बंद करें', 'user.change_password.unavailable.heading': '{credential} परिवर्तन उपलब्ध नहीं है', 'user.change_password.unavailable.description': 'कृपया अपने व्यवस्थापक से संपर्क करें।', diff --git a/packages/javascript/src/i18n/translations/ja-JP.ts b/packages/javascript/src/i18n/translations/ja-JP.ts index eda1a04b..1f8a416d 100644 --- a/packages/javascript/src/i18n/translations/ja-JP.ts +++ b/packages/javascript/src/i18n/translations/ja-JP.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -148,6 +148,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': '{credential}の変更', + 'user.change_password.current.label': '現在の{credential}', + 'user.change_password.current.placeholder': '現在の{credentialLower}を入力してください', + 'user.change_password.current.hint': 'まだ設定していない場合は空欄のままにしてください。', 'user.change_password.new.label': '新しい{credential}', 'user.change_password.new.placeholder': '新しい{credentialLower}を入力してください', 'user.change_password.confirm.label': '新しい{credential}の確認', @@ -157,6 +160,19 @@ const translations: I18nTranslations = { 'user.change_password.success': '{credentialLower}を更新しました。', 'user.change_password.mismatch.error': '{credentialLower}が一致しません。', 'user.change_password.generic.error': '{credentialLower}の更新中にエラーが発生しました。もう一度お試しください。', + 'user.change_password.current.required.error': '現在の{credentialLower}を入力してください。', + 'user.change_password.current.invalid.error': '現在の{credentialLower}が正しくありません。', + 'user.change_password.reauthentication.error': '{credentialLower}を設定するには、もう一度サインインしてください。', + 'user.reauthentication.required.error': 'この変更を保存するには、もう一度サインインしてください。', + 'user.reauthentication.failed.error': '再サインインが完了しませんでした。もう一度お試しください。', + 'user.reauthentication.popup_blocked.error': 'このサイトのポップアップを許可してから、もう一度お試しください。', + 'user.reauthentication.different_user.error': + '別のアカウントでサインインしました。ご自分のアカウントでサインインして、もう一度お試しください。', + 'user.reauthentication.heading': 'もう一度サインイン', + 'user.reauthentication.description': 'この変更を保存するには、本人であることを確認してください。', + 'user.reauthentication.unsupported_option.error': + 'このサインイン方法はここでは使用できません。別の方法を選択してください。', + 'user.reauthentication.buttons.close.text': '閉じる', 'user.change_password.unavailable.heading': '{credential}の変更はできません', 'user.change_password.unavailable.description': '管理者にお問い合わせください。', diff --git a/packages/javascript/src/i18n/translations/pt-BR.ts b/packages/javascript/src/i18n/translations/pt-BR.ts index 4ba69a61..272ac1d8 100644 --- a/packages/javascript/src/i18n/translations/pt-BR.ts +++ b/packages/javascript/src/i18n/translations/pt-BR.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -148,6 +148,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': 'Alterar {credential}', + 'user.change_password.current.label': '{credential} atual', + 'user.change_password.current.placeholder': 'Digite seu {credentialLower} atual', + 'user.change_password.current.hint': 'Deixe em branco se você ainda não definiu um.', 'user.change_password.new.label': 'Novo {credential}', 'user.change_password.new.placeholder': 'Digite seu novo {credentialLower}', 'user.change_password.confirm.label': 'Confirmar novo {credential}', @@ -157,6 +160,17 @@ const translations: I18nTranslations = { 'user.change_password.success': 'Seu {credentialLower} foi atualizado.', 'user.change_password.mismatch.error': 'Os {credentialLower}s não coincidem.', 'user.change_password.generic.error': 'Ocorreu um erro ao atualizar seu {credentialLower}. Tente novamente.', + 'user.change_password.current.required.error': 'Digite seu {credentialLower} atual.', + 'user.change_password.current.invalid.error': 'O {credentialLower} atual está incorreto.', + 'user.change_password.reauthentication.error': 'Entre novamente para definir seu {credentialLower}.', + 'user.reauthentication.required.error': 'Entre novamente para salvar esta alteração.', + 'user.reauthentication.failed.error': 'A nova entrada não foi concluída. Tente novamente.', + 'user.reauthentication.popup_blocked.error': 'Permita pop-ups para este site e tente novamente.', + 'user.reauthentication.different_user.error': 'Você entrou com outra conta. Entre com a sua conta e tente novamente.', + 'user.reauthentication.heading': 'Entre novamente', + 'user.reauthentication.description': 'Confirme que é você para salvar esta alteração.', + 'user.reauthentication.unsupported_option.error': 'Esta opção de entrada não está disponível aqui. Escolha outra.', + 'user.reauthentication.buttons.close.text': 'Fechar', 'user.change_password.unavailable.heading': 'Alteração de {credentialLower} indisponível', 'user.change_password.unavailable.description': 'Entre em contato com o administrador.', diff --git a/packages/javascript/src/i18n/translations/pt-PT.ts b/packages/javascript/src/i18n/translations/pt-PT.ts index abc5f150..9c644243 100644 --- a/packages/javascript/src/i18n/translations/pt-PT.ts +++ b/packages/javascript/src/i18n/translations/pt-PT.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -148,6 +148,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': 'Alterar {credential}', + 'user.change_password.current.label': '{credential} actual', + 'user.change_password.current.placeholder': 'Introduza o seu {credentialLower} actual', + 'user.change_password.current.hint': 'Deixe em branco se ainda não definiu um.', 'user.change_password.new.label': 'Novo {credential}', 'user.change_password.new.placeholder': 'Introduza o seu novo {credentialLower}', 'user.change_password.confirm.label': 'Confirmar novo {credential}', @@ -157,6 +160,19 @@ const translations: I18nTranslations = { 'user.change_password.success': 'O seu {credentialLower} foi atualizado.', 'user.change_password.mismatch.error': 'Os {credentialLower}s não coincidem.', 'user.change_password.generic.error': 'Ocorreu um erro ao actualizar o seu {credentialLower}. Tente novamente.', + 'user.change_password.current.required.error': 'Introduza o seu {credentialLower} actual.', + 'user.change_password.current.invalid.error': 'O {credentialLower} actual está incorrecto.', + 'user.change_password.reauthentication.error': 'Inicie sessão novamente para definir o seu {credentialLower}.', + 'user.reauthentication.required.error': 'Inicie sessão novamente para guardar esta alteração.', + 'user.reauthentication.failed.error': 'O novo início de sessão não foi concluído. Tente novamente.', + 'user.reauthentication.popup_blocked.error': 'Permita pop-ups para este site e tente novamente.', + 'user.reauthentication.different_user.error': + 'Iniciou sessão com outra conta. Inicie sessão com a sua conta e tente novamente.', + 'user.reauthentication.heading': 'Inicie sessão novamente', + 'user.reauthentication.description': 'Confirme a sua identidade para guardar esta alteração.', + 'user.reauthentication.unsupported_option.error': + 'Esta opção de início de sessão não está disponível aqui. Escolha outra.', + 'user.reauthentication.buttons.close.text': 'Fechar', 'user.change_password.unavailable.heading': 'Alteração de {credentialLower} indisponível', 'user.change_password.unavailable.description': 'Contacte o seu administrador.', diff --git a/packages/javascript/src/i18n/translations/si-LK.ts b/packages/javascript/src/i18n/translations/si-LK.ts index 89e441c7..41db4dbd 100644 --- a/packages/javascript/src/i18n/translations/si-LK.ts +++ b/packages/javascript/src/i18n/translations/si-LK.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -148,6 +148,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': '{credential} වෙනස් කරන්න', + 'user.change_password.current.label': 'වත්මන් {credential}', + 'user.change_password.current.placeholder': 'ඔබගේ වත්මන් {credentialLower} ඇතුළත් කරන්න', + 'user.change_password.current.hint': 'ඔබ තවමත් එකක් සකසා නොමැති නම් මෙය හිස්ව තබන්න.', 'user.change_password.new.label': 'නව {credential}', 'user.change_password.new.placeholder': 'ඔබේ නව {credentialLower} ඇතුළත් කරන්න', 'user.change_password.confirm.label': 'නව {credential} තහවුරු කරන්න', @@ -158,6 +161,18 @@ const translations: I18nTranslations = { 'user.change_password.mismatch.error': '{credentialLower} නොගැලපේ.', 'user.change_password.generic.error': 'ඔබේ {credentialLower} යාවත්කාලීන කිරීමේදී දෝෂයක් ඇතිවිය. කරුණාකර නැවත උත්සාහ කරන්න.', + 'user.change_password.current.required.error': 'ඔබගේ වත්මන් {credentialLower} ඇතුළත් කරන්න.', + 'user.change_password.current.invalid.error': 'වත්මන් {credentialLower} වැරදියි.', + 'user.change_password.reauthentication.error': 'ඔබගේ {credentialLower} සැකසීමට නැවත පුරනය වන්න.', + 'user.reauthentication.required.error': 'මෙම වෙනස සුරැකීමට නැවත පුරනය වන්න.', + 'user.reauthentication.failed.error': 'නැවත පුරනය වීම අවසන් නොවීය. නැවත උත්සාහ කරන්න.', + 'user.reauthentication.popup_blocked.error': 'මෙම අඩවිය සඳහා උත්පතන ඉඩ දී, නැවත උත්සාහ කරන්න.', + 'user.reauthentication.different_user.error': + 'ඔබ වෙනත් ගිණුමකින් පුරනය විය. ඔබගේම ගිණුමෙන් පුරනය වී නැවත උත්සාහ කරන්න.', + 'user.reauthentication.heading': 'නැවත පුරනය වන්න', + 'user.reauthentication.description': 'මෙම වෙනස සුරැකීමට එය ඔබ බව තහවුරු කරන්න.', + 'user.reauthentication.unsupported_option.error': 'මෙම පුරනය වීමේ විකල්පය මෙහි ලබා ගත නොහැක. වෙනත් එකක් තෝරන්න.', + 'user.reauthentication.buttons.close.text': 'වසන්න', 'user.change_password.unavailable.heading': '{credential} වෙනස් කිරීම් ලබා ගත නොහැක', 'user.change_password.unavailable.description': 'කරුණාකර ඔබේ පරිපාලක සම්බන්ධ කර ගන්න.', diff --git a/packages/javascript/src/i18n/translations/ta-IN.ts b/packages/javascript/src/i18n/translations/ta-IN.ts index dc5d744c..e4361d59 100644 --- a/packages/javascript/src/i18n/translations/ta-IN.ts +++ b/packages/javascript/src/i18n/translations/ta-IN.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -149,6 +149,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': '{credential} மாற்றவும்', + 'user.change_password.current.label': 'தற்போதைய {credential}', + 'user.change_password.current.placeholder': 'உங்கள் தற்போதைய {credentialLower} ஐ உள்ளிடவும்', + 'user.change_password.current.hint': 'நீங்கள் இன்னும் அமைக்கவில்லை என்றால் இதைக் காலியாக விடவும்.', 'user.change_password.new.label': 'புதிய {credential}', 'user.change_password.new.placeholder': 'உங்கள் புதிய {credentialLower}-ஐ உள்ளிடவும்', 'user.change_password.confirm.label': 'புதிய {credential}-ஐ உறுதிப்படுத்தவும்', @@ -159,6 +162,19 @@ const translations: I18nTranslations = { 'user.change_password.mismatch.error': '{credentialLower} பொருந்தவில்லை.', 'user.change_password.generic.error': 'உங்கள் {credentialLower}-ஐ புதுப்பிக்கும் போது பிழை ஏற்பட்டது. மீண்டும் முயற்சிக்கவும்.', + 'user.change_password.current.required.error': 'உங்கள் தற்போதைய {credentialLower} ஐ உள்ளிடவும்.', + 'user.change_password.current.invalid.error': 'தற்போதைய {credentialLower} தவறானது.', + 'user.change_password.reauthentication.error': 'உங்கள் {credentialLower} ஐ அமைக்க மீண்டும் உள்நுழையவும்.', + 'user.reauthentication.required.error': 'இந்த மாற்றத்தைச் சேமிக்க மீண்டும் உள்நுழையவும்.', + 'user.reauthentication.failed.error': 'மீண்டும் உள்நுழைவது முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + 'user.reauthentication.popup_blocked.error': 'இந்தத் தளத்திற்கு பாப்-அப்களை அனுமதித்து, மீண்டும் முயற்சிக்கவும்.', + 'user.reauthentication.different_user.error': + 'நீங்கள் வேறொரு கணக்கில் உள்நுழைந்தீர்கள். உங்கள் கணக்கில் உள்நுழைந்து மீண்டும் முயற்சிக்கவும்.', + 'user.reauthentication.heading': 'மீண்டும் உள்நுழையவும்', + 'user.reauthentication.description': 'இந்த மாற்றத்தைச் சேமிக்க இது நீங்கள்தான் என்பதை உறுதிப்படுத்தவும்.', + 'user.reauthentication.unsupported_option.error': + 'இந்த உள்நுழைவு விருப்பம் இங்கே கிடைக்கவில்லை. வேறொன்றைத் தேர்ந்தெடுக்கவும்.', + 'user.reauthentication.buttons.close.text': 'மூடு', 'user.change_password.unavailable.heading': '{credential} மாற்றங்கள் கிடைக்கவில்லை', 'user.change_password.unavailable.description': 'உங்கள் நிர்வாகியை தொடர்பு கொள்ளவும்.', diff --git a/packages/javascript/src/i18n/translations/te-IN.ts b/packages/javascript/src/i18n/translations/te-IN.ts index 50b6038d..d4ada12b 100644 --- a/packages/javascript/src/i18n/translations/te-IN.ts +++ b/packages/javascript/src/i18n/translations/te-IN.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {I18nTranslations, I18nMetadata, I18nBundle} from '../models/i18n'; @@ -149,6 +149,9 @@ const translations: I18nTranslations = { /* |---------------------------------------------------------------| */ 'user.change_password.heading': '{credential} మార్చండి', + 'user.change_password.current.label': 'ప్రస్తుత {credential}', + 'user.change_password.current.placeholder': 'మీ ప్రస్తుత {credentialLower}ను నమోదు చేయండి', + 'user.change_password.current.hint': 'మీరు ఇంకా సెట్ చేయకపోతే దీన్ని ఖాళీగా వదిలేయండి.', 'user.change_password.new.label': 'కొత్త {credential}', 'user.change_password.new.placeholder': 'మీ కొత్త {credentialLower} నమోదు చేయండి', 'user.change_password.confirm.label': 'కొత్త {credential} నిర్ధారించండి', @@ -159,6 +162,18 @@ const translations: I18nTranslations = { 'user.change_password.mismatch.error': '{credentialLower} సరిపోలలేదు.', 'user.change_password.generic.error': 'మీ {credentialLower} నవీకరించేటప్పుడు లోపం వచ్చింది. దయచేసి మళ్లీ ప్రయత్నించండి.', + 'user.change_password.current.required.error': 'మీ ప్రస్తుత {credentialLower}ను నమోదు చేయండి.', + 'user.change_password.current.invalid.error': 'ప్రస్తుత {credentialLower} తప్పు.', + 'user.change_password.reauthentication.error': 'మీ {credentialLower}ను సెట్ చేయడానికి మళ్లీ సైన్ ఇన్ చేయండి.', + 'user.reauthentication.required.error': 'ఈ మార్పును సేవ్ చేయడానికి మళ్లీ సైన్ ఇన్ చేయండి.', + 'user.reauthentication.failed.error': 'మళ్లీ సైన్ ఇన్ పూర్తి కాలేదు. మళ్లీ ప్రయత్నించండి.', + 'user.reauthentication.popup_blocked.error': 'ఈ సైట్‌కు పాప్-అప్‌లను అనుమతించి, మళ్లీ ప్రయత్నించండి.', + 'user.reauthentication.different_user.error': + 'మీరు వేరే ఖాతాతో సైన్ ఇన్ చేశారు. మీ ఖాతాతో సైన్ ఇన్ చేసి మళ్లీ ప్రయత్నించండి.', + 'user.reauthentication.heading': 'మళ్లీ సైన్ ఇన్ చేయండి', + 'user.reauthentication.description': 'ఈ మార్పును సేవ్ చేయడానికి ఇది మీరేనని నిర్ధారించండి.', + 'user.reauthentication.unsupported_option.error': 'ఈ సైన్ ఇన్ ఎంపిక ఇక్కడ అందుబాటులో లేదు. వేరొకదాన్ని ఎంచుకోండి.', + 'user.reauthentication.buttons.close.text': 'మూసివేయండి', 'user.change_password.unavailable.heading': '{credential} మార్పులు అందుబాటులో లేవు', 'user.change_password.unavailable.description': 'దయచేసి మీ నిర్వాహకుడిని సంప్రదించండి.', diff --git a/packages/javascript/src/index.ts b/packages/javascript/src/index.ts index c6edc95c..0f5e476b 100644 --- a/packages/javascript/src/index.ts +++ b/packages/javascript/src/index.ts @@ -31,7 +31,8 @@ export type {GetUsersMeMetaConfig, UsersMeMetaResponse, AttributeSchema} from '. export {default as getAccessibleOrganizationUnits} from './api/account/getAccessibleOrganizationUnits'; export type {GetAccessibleOrganizationUnitsConfig} from './api/account/getAccessibleOrganizationUnits'; export {default as updateMeCredentials} from './api/account/updateMeCredentials'; -export type {UpdateMeCredentialsConfig} from './api/account/updateMeCredentials'; +export type {UpdateMeCredentialsConfig, UpdateMeCredentialsPayload} from './api/account/updateMeCredentials'; +export type {ReauthenticationMethod, ReauthenticationOptions, ReauthenticationRequest} from './models/reauthentication'; export {default as updateMeProfile} from './api/account/updateMeProfile'; export type {UpdateMeProfileConfig} from './api/account/updateMeProfile'; export {default as getMeAgents} from './api/account/getMeAgents'; @@ -565,6 +566,7 @@ export {default as AttributeVerificationConstants} from './constants/AttributeVe export {default as ThunderIDError} from './errors/ThunderIDError'; export {default as ThunderIDAPIError} from './errors/ThunderIDAPIError'; +export {default as StepUpRequiredError, INSUFFICIENT_USER_AUTHENTICATION} from './errors/StepUpRequiredError'; export {default as AdministrationFlowError} from './errors/AdministrationFlowError'; export {default as ThunderIDRuntimeError} from './errors/ThunderIDRuntimeError'; export {InvalidLogoutTokenError, ThunderIDAuthException} from './errors/exception'; @@ -714,6 +716,7 @@ export type {AgentConfig} from './models/agent'; export type { ApiError, ApiFetcher, + AuthenticationChallenge, ApiFilteringParams, ApiPaginationLink, ManagementRequestConfig, @@ -1236,6 +1239,15 @@ export type {ChangePasswordFormValues, ChangePasswordFormEvaluation} from './uti export {default as resolveChangeCredentialPolicy} from './utils/resolveChangeCredentialPolicy'; export {default as supportsCredential} from './utils/supportsCredential'; export {default as mapCredentialUpdateError} from './utils/mapCredentialUpdateError'; +export {default as mapReauthenticationError} from './utils/mapReauthenticationError'; +export {default as pickRecentSignInParams} from './utils/pickRecentSignInParams'; +export type {RecentSignInParams} from './utils/pickRecentSignInParams'; +export {default as runWithStepUp, REAUTHENTICATION_FAILED, STEP_UP_ABANDONED} from './utils/runWithStepUp'; +export type {PendingStepUp, RunWithStepUpOptions} from './utils/runWithStepUp'; +export { + default as parseAuthenticationChallenge, + RECENT_AUTHENTICATION_REQUIRED_CODE, +} from './utils/parseAuthenticationChallenge'; export type {CredentialUpdateErrorField, CredentialUpdateErrorResult} from './utils/mapCredentialUpdateError'; export {default as mapSelectPageError} from './utils/mapSelectPageError'; export type {SelectPageErrorResult} from './utils/mapSelectPageError'; diff --git a/packages/javascript/src/models/api.ts b/packages/javascript/src/models/api.ts index c4d0b22b..51605092 100644 --- a/packages/javascript/src/models/api.ts +++ b/packages/javascript/src/models/api.ts @@ -83,3 +83,23 @@ export interface ServerError { description?: ServerErrorMessage; message?: ServerErrorMessage; } + +/** + * A `WWW-Authenticate: Bearer` challenge that asks for a more recent sign-in (RFC 9470), such as the one + * the self-service APIs return when a change needs one. Sign the user in again with `maxAge` as the + * `max_age` authorization parameter, or with `prompt=login`, and retry the request with the new token. + */ +export interface AuthenticationChallenge { + /** + * The challenge's `error`, such as `insufficient_user_authentication`. + */ + error: string; + /** + * The challenge's `error_description`, when the server sent one. + */ + errorDescription?: string; + /** + * The challenge's `max_age`: how recent, in seconds, the sign-in must be. + */ + maxAge?: number; +} diff --git a/packages/javascript/src/models/embedded-signin-flow.ts b/packages/javascript/src/models/embedded-signin-flow.ts index 7c0c592a..87b106e7 100644 --- a/packages/javascript/src/models/embedded-signin-flow.ts +++ b/packages/javascript/src/models/embedded-signin-flow.ts @@ -309,6 +309,13 @@ export interface EmbeddedSignInFlowInitiateRequest { */ flowType: EmbeddedFlowType; + /** + * How recent, in seconds, a sign-in the flow may reuse must be, as OIDC `max_age`. An older SSO + * session makes the flow prompt the user again; `0` always prompts. Accepted only on the request that + * starts an `AUTHENTICATION` flow. Never sent on a continuation. + */ + maxAge?: number; + /** * Identifier of the organization unit to sign in to. Accepted only on the request that starts an * `AUTHENTICATION` flow; the sign-in is then bounded to that unit. Never sent on a continuation. diff --git a/packages/javascript/src/models/reauthentication.ts b/packages/javascript/src/models/reauthentication.ts new file mode 100644 index 00000000..724a4cc0 --- /dev/null +++ b/packages/javascript/src/models/reauthentication.ts @@ -0,0 +1,34 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/** + * Options for signing the signed-in user in again. + */ +export interface ReauthenticationOptions { + /** + * How recent, in seconds, the sign-in must be, sent as `max_age` (RFC 9470). Take it from a + * `StepUpRequiredError`. Without it, the request asks for `prompt=login`. + */ + maxAge?: number; +} + +/** + * How the signed-in user signs in again for a change that needs a recent sign-in: + * + * - `popup`: an authorization request in a popup, for a session from a redirect sign-in. + * - `flow`: the sign-in flow run again in the app, for a session from an embedded sign-in flow. + * - `unavailable`: the session is held by a backend, which signs the user in again itself. + */ +export type ReauthenticationMethod = 'popup' | 'flow' | 'unavailable'; + +/** + * An authorization request that signs the signed-in user in again, and what redeeming its code needs. + */ +export interface ReauthenticationRequest { + codeVerifier: string; + nonce: string; + redirectUri: string; + resource?: string; + state: string; + url: string; +} diff --git a/packages/javascript/src/models/session.ts b/packages/javascript/src/models/session.ts index 705c1183..bf96d723 100644 --- a/packages/javascript/src/models/session.ts +++ b/packages/javascript/src/models/session.ts @@ -22,6 +22,8 @@ export interface SessionData { created_at: number; /** The device secret a sign-in with the `device_sso` scope returned, exchanged to switch organization units. */ device_secret?: string; + /** Set when the session came from an embedded sign-in flow. */ + embedded_sign_in?: boolean; expires_in: string; /** The SSO session handles embedded flow steps returned. */ flow_sessions?: StoredFlowSession[]; diff --git a/packages/javascript/src/utils/AuthenticationHelper.ts b/packages/javascript/src/utils/AuthenticationHelper.ts index a5525cc3..f2608b9c 100644 --- a/packages/javascript/src/utils/AuthenticationHelper.ts +++ b/packages/javascript/src/utils/AuthenticationHelper.ts @@ -464,6 +464,7 @@ class AuthenticationHelper { * @param userId - Optional user ID scoping the session. * @param replaceSession - Replace the whole session instead of merging into it, keeping only its device * secret and SSO session handles, so no token of the previous session survives. + * @param refreshed - The response refreshes the stored session, which keeps its embedded sign-in mark. * @returns A normalized `TokenResponse` object. * @throws {ThunderIDAuthException} When the response status is not 200. */ @@ -471,6 +472,7 @@ class AuthenticationHelper { response: Response, userId?: string, replaceSession = false, + refreshed = false, ): Promise { if (response.status !== 200 || !response.ok) { throw new ThunderIDAuthException( @@ -488,7 +490,7 @@ class AuthenticationHelper { if (shouldValidateIdToken) { return this.validateIdToken(parsedResponse.id_token).then(async () => { - await this.storeTokenResponse(parsedResponse, userId, replaceSession); + await this.storeTokenResponse(parsedResponse, userId, replaceSession, refreshed); return { accessToken: parsedResponse.access_token, @@ -503,7 +505,7 @@ class AuthenticationHelper { }); } - await this.storeTokenResponse(parsedResponse, userId, replaceSession); + await this.storeTokenResponse(parsedResponse, userId, replaceSession, refreshed); return { accessToken: parsedResponse.access_token, @@ -517,13 +519,27 @@ class AuthenticationHelper { }; } - private async storeTokenResponse( + /** + * Stores a token response in the session. With `replaceSession`, every earlier session key is cleared + * in the same write, except the device secret and the flow sessions. + * + * @param parsedResponse - The token response. + * @param userId - The session. + * @param replaceSession - Whether the response replaces the session. + * @param refreshed - Whether the response refreshes the stored session. + */ + public async storeTokenResponse( parsedResponse: AccessTokenApiResponse, userId: string | undefined, replaceSession: boolean, + refreshed = false, ): Promise { if (!replaceSession) { - await this.storageManager.setSessionData(parsedResponse, userId); + // A token endpoint response ends a session from an embedded sign-in flow, unless it refreshes that session. + await this.storageManager.setSessionData( + refreshed ? parsedResponse : {...parsedResponse, embedded_sign_in: undefined}, + userId, + ); return; } diff --git a/packages/javascript/src/utils/__tests__/mapCredentialUpdateError.test.ts b/packages/javascript/src/utils/__tests__/mapCredentialUpdateError.test.ts index 699e5f78..eff794da 100644 --- a/packages/javascript/src/utils/__tests__/mapCredentialUpdateError.test.ts +++ b/packages/javascript/src/utils/__tests__/mapCredentialUpdateError.test.ts @@ -2,13 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import {describe, expect, it} from 'vitest'; +import StepUpRequiredError from '../../errors/StepUpRequiredError'; import ThunderIDAPIError from '../../errors/ThunderIDAPIError'; import ThunderIDError from '../../errors/ThunderIDError'; +import ThunderIDRuntimeError from '../../errors/ThunderIDRuntimeError'; import mapCredentialUpdateError from '../mapCredentialUpdateError'; +import {REAUTHENTICATION_FAILED} from '../runWithStepUp'; const apiError = (statusCode: number, message = 'Server said no'): ThunderIDAPIError => new ThunderIDAPIError(message, 'test-code', 'test-origin', statusCode); +const serverError = (statusCode: number, code: string, header?: string): ThunderIDAPIError => + new ThunderIDAPIError( + JSON.stringify({code, message: {defaultValue: `Server text for ${code}`}}), + 'test-code', + 'test-origin', + statusCode, + undefined, + undefined, + header, + ); + describe('mapCredentialUpdateError', (): void => { it('should blame the new password on 400 and surface the server message', (): void => { const result = mapCredentialUpdateError(apiError(400, 'Password is too common')); @@ -17,7 +31,46 @@ describe('mapCredentialUpdateError', (): void => { expect(result.message).toContain('Password is too common'); }); - it('should report a 403 at form level, since this form collects no current-value field', (): void => { + it('should put a missing current value on the current field with translated text', (): void => { + expect(mapCredentialUpdateError(serverError(400, 'USR-1047'))).toEqual({ + field: 'currentPassword', + messageKey: 'user.change_password.current.required.error', + }); + }); + + it('should put a wrong current value on the current field with translated text', (): void => { + expect(mapCredentialUpdateError(serverError(403, 'USR-1048'))).toEqual({ + field: 'currentPassword', + messageKey: 'user.change_password.current.invalid.error', + }); + }); + + it('should report a needed recent sign-in at form level with its challenge', (): void => { + const result = mapCredentialUpdateError( + serverError(401, 'AUTH-4011', 'Bearer error="insufficient_user_authentication", max_age="300"'), + ); + + expect(result).toEqual({ + authenticationChallenge: {error: 'insufficient_user_authentication', maxAge: 300}, + field: null, + messageKey: 'user.change_password.reauthentication.error', + }); + }); + + it.each([ + ['BROWSER-REAUTHENTICATION-PB01', 'user.reauthentication.popup_blocked.error'], + ['JS-AUTH_CORE-CRA-IV03', 'user.reauthentication.different_user.error'], + ['BROWSER-REAUTHENTICATION-DU01', 'user.reauthentication.different_user.error'], + ['BROWSER-REAUTHENTICATION-PC01', 'user.reauthentication.failed.error'], + ])('should report a failed re-sign-in (%s) at form level', (code: string, messageKey: string): void => { + const cause = new ThunderIDRuntimeError('failed', code, 'browser'); + + expect( + mapCredentialUpdateError(new ThunderIDRuntimeError('x', REAUTHENTICATION_FAILED, 'javascript', {cause})), + ).toEqual({field: null, messageKey}); + }); + + it('should report another 403 at form level with the server message', (): void => { const result = mapCredentialUpdateError(apiError(403, 'Not allowed')); expect(result.field).toBeNull(); @@ -59,4 +112,21 @@ describe('mapCredentialUpdateError', (): void => { expect(result.message).toBeUndefined(); }, ); + + it('should treat a step-up error whose body is not a server error as a step-up', (): void => { + const error = new StepUpRequiredError( + 'Unauthorized', + 'updateMeCredentials-StepUpRequired-001', + 'javascript', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="60"', + ); + + expect(mapCredentialUpdateError(error)).toMatchObject({ + field: null, + messageKey: 'user.change_password.reauthentication.error', + }); + }); }); diff --git a/packages/javascript/src/utils/__tests__/parseAuthenticationChallenge.test.ts b/packages/javascript/src/utils/__tests__/parseAuthenticationChallenge.test.ts new file mode 100644 index 00000000..bacb267a --- /dev/null +++ b/packages/javascript/src/utils/__tests__/parseAuthenticationChallenge.test.ts @@ -0,0 +1,67 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it} from 'vitest'; +import ThunderIDAPIError from '../../errors/ThunderIDAPIError'; +import parseAuthenticationChallenge from '../parseAuthenticationChallenge'; + +describe('parseAuthenticationChallenge', (): void => { + it('reads error, error_description and max_age from a Bearer challenge', (): void => { + expect( + parseAuthenticationChallenge( + 'Bearer error="insufficient_user_authentication", error_description="A more recent authentication is required", max_age="300"', + ), + ).toEqual({ + error: 'insufficient_user_authentication', + errorDescription: 'A more recent authentication is required', + maxAge: 300, + }); + }); + + it('reads unquoted values and a scheme in any case', (): void => { + expect(parseAuthenticationChallenge('bearer error=insufficient_user_authentication, max_age=60')).toEqual({ + error: 'insufficient_user_authentication', + maxAge: 60, + }); + }); + + it('reads the Bearer challenge when another scheme comes first', (): void => { + expect(parseAuthenticationChallenge('DPoP algs="ES256", Bearer error="invalid_token"')).toEqual({ + error: 'invalid_token', + }); + }); + + it('leaves out a max_age that is not a number', (): void => { + expect(parseAuthenticationChallenge('Bearer error="insufficient_user_authentication", max_age="soon"')).toEqual({ + error: 'insufficient_user_authentication', + }); + }); + + it('returns undefined for a challenge without an error', (): void => { + expect(parseAuthenticationChallenge('Bearer realm="thunderid"')).toBeUndefined(); + expect(parseAuthenticationChallenge(null)).toBeUndefined(); + }); + + it('falls back to the maxAge parameter of an AUTH-4011 body', (): void => { + expect( + parseAuthenticationChallenge(undefined, {code: 'AUTH-4011', description: {params: {maxAge: '300'}}}), + ).toEqual({error: 'insufficient_user_authentication', maxAge: 300}); + }); + + it('returns undefined for another body without a header', (): void => { + expect(parseAuthenticationChallenge(undefined, {code: 'AUTH-4010'})).toBeUndefined(); + }); + + it('is read into ThunderIDAPIError only for a 401', (): void => { + const header = 'Bearer error="insufficient_user_authentication", max_age="30"'; + const body: string = JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}); + + expect(new ThunderIDAPIError(body, 'X', 'javascript', 401, 'Unauthorized', undefined, header)).toMatchObject({ + authenticationChallenge: {error: 'insufficient_user_authentication', maxAge: 30}, + message: 'Recent authentication required', + }); + expect( + new ThunderIDAPIError(body, 'X', 'javascript', 403, 'Forbidden', undefined, header).authenticationChallenge, + ).toBeUndefined(); + }); +}); diff --git a/packages/javascript/src/utils/__tests__/pickRecentSignInParams.test.ts b/packages/javascript/src/utils/__tests__/pickRecentSignInParams.test.ts new file mode 100644 index 00000000..0684a425 --- /dev/null +++ b/packages/javascript/src/utils/__tests__/pickRecentSignInParams.test.ts @@ -0,0 +1,28 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it} from 'vitest'; +import pickRecentSignInParams from '../pickRecentSignInParams'; + +describe('pickRecentSignInParams', () => { + it('keeps max_age and prompt=login, from strings or numbers', () => { + expect(pickRecentSignInParams({max_age: '180', prompt: 'login'})).toEqual({max_age: '180', prompt: 'login'}); + expect(pickRecentSignInParams({max_age: 0})).toEqual({max_age: '0'}); + }); + + it('drops every other parameter', () => { + expect(pickRecentSignInParams({redirect_uri: 'https://evil.example', returnTo: '/a', scope: 'x'})).toEqual({}); + }); + + it('drops a max_age that is not a whole number of seconds, and any other prompt', () => { + expect(pickRecentSignInParams({max_age: '-1'})).toEqual({}); + expect(pickRecentSignInParams({max_age: '1.5'})).toEqual({}); + expect(pickRecentSignInParams({max_age: '30&prompt=none'})).toEqual({}); + expect(pickRecentSignInParams({prompt: 'none'})).toEqual({}); + }); + + it('accepts nothing', () => { + expect(pickRecentSignInParams()).toEqual({}); + expect(pickRecentSignInParams(null)).toEqual({}); + }); +}); diff --git a/packages/javascript/src/utils/__tests__/runWithStepUp.test.ts b/packages/javascript/src/utils/__tests__/runWithStepUp.test.ts new file mode 100644 index 00000000..c9c892cc --- /dev/null +++ b/packages/javascript/src/utils/__tests__/runWithStepUp.test.ts @@ -0,0 +1,107 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it, vi} from 'vitest'; +import StepUpRequiredError from '../../errors/StepUpRequiredError'; +import ThunderIDAPIError from '../../errors/ThunderIDAPIError'; +import runWithStepUp, {PendingStepUp, REAUTHENTICATION_FAILED, STEP_UP_ABANDONED} from '../runWithStepUp'; + +const stepUp = (): StepUpRequiredError => + new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'updateMeProfile-StepUpRequired-001', + 'javascript', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); + +describe('runWithStepUp', () => { + it('sends once and does not sign in again when the change succeeds', async () => { + const send = vi.fn().mockResolvedValue('ok'); + const reauthenticate = vi.fn(); + + await expect(runWithStepUp({reauthenticate, send})).resolves.toBe('ok'); + expect(send).toHaveBeenCalledTimes(1); + expect(reauthenticate).not.toHaveBeenCalled(); + }); + + it('signs in again with the challenge maxAge and retries exactly once', async () => { + const send = vi.fn().mockRejectedValueOnce(stepUp()).mockResolvedValueOnce('ok'); + const reauthenticate = vi.fn().mockResolvedValue(undefined); + + await expect(runWithStepUp({reauthenticate, send})).resolves.toBe('ok'); + expect(reauthenticate).toHaveBeenCalledWith({maxAge: 300}); + expect(send).toHaveBeenCalledTimes(2); + }); + + it('throws a second refusal without trying again', async () => { + const send = vi.fn().mockRejectedValue(stepUp()); + const reauthenticate = vi.fn().mockResolvedValue(undefined); + + await expect(runWithStepUp({reauthenticate, send})).rejects.toBeInstanceOf(StepUpRequiredError); + expect(reauthenticate).toHaveBeenCalledTimes(1); + expect(send).toHaveBeenCalledTimes(2); + }); + + it('reports a failed re-sign-in, keeps the challenge, and signs in again first next time', async () => { + const pending: PendingStepUp = {}; + const cause = Object.assign(new Error('blocked'), {code: 'BROWSER-REAUTHENTICATION-PB01'}); + const send = vi.fn().mockRejectedValueOnce(stepUp()).mockResolvedValueOnce('ok'); + const reauthenticate = vi.fn().mockRejectedValueOnce(cause).mockResolvedValueOnce(undefined); + + await expect(runWithStepUp({pending, reauthenticate, send})).rejects.toMatchObject({ + code: REAUTHENTICATION_FAILED, + details: {cause}, + }); + expect(send).toHaveBeenCalledTimes(1); + expect(pending.current).toEqual({error: 'insufficient_user_authentication', maxAge: 300}); + + await expect(runWithStepUp({pending, reauthenticate, send})).resolves.toBe('ok'); + expect(reauthenticate).toHaveBeenNthCalledWith(2, {maxAge: 300}); + expect(reauthenticate.mock.invocationCallOrder[1]).toBeLessThan(send.mock.invocationCallOrder[1]); + expect(send).toHaveBeenCalledTimes(2); + expect(pending.current).toBeUndefined(); + }); + + it('hands the challenge to the application instead of signing in again', async () => { + const send = vi.fn().mockRejectedValue(stepUp()); + const reauthenticate = vi.fn(); + const onReauthenticationRequired = vi.fn(); + + await expect(runWithStepUp({onReauthenticationRequired, reauthenticate, send})).rejects.toBeInstanceOf( + StepUpRequiredError, + ); + expect(onReauthenticationRequired).toHaveBeenCalledWith({ + error: 'insufficient_user_authentication', + maxAge: 300, + }); + expect(reauthenticate).not.toHaveBeenCalled(); + expect(send).toHaveBeenCalledTimes(1); + }); + + it('passes any other failure through without signing in again', async () => { + const refused = new ThunderIDAPIError('Forbidden', 'x', 'javascript', 403); + const send = vi.fn().mockRejectedValue(refused); + const reauthenticate = vi.fn(); + + await expect(runWithStepUp({reauthenticate, send})).rejects.toBe(refused); + expect(reauthenticate).not.toHaveBeenCalled(); + }); + + it('does not send the change again when the caller is no longer active after signing in again', async () => { + const send = vi.fn().mockRejectedValueOnce(stepUp()).mockResolvedValueOnce('ok'); + let active = true; + const reauthenticate = vi.fn(() => { + active = false; + + return Promise.resolve(); + }); + + await expect(runWithStepUp({isActive: () => active, reauthenticate, send})).rejects.toMatchObject({ + code: STEP_UP_ABANDONED, + }); + expect(send).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/javascript/src/utils/createApiResponseError.ts b/packages/javascript/src/utils/createApiResponseError.ts new file mode 100644 index 00000000..c8351214 --- /dev/null +++ b/packages/javascript/src/utils/createApiResponseError.ts @@ -0,0 +1,50 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import StepUpRequiredError, {INSUFFICIENT_USER_AUTHENTICATION} from '../errors/StepUpRequiredError'; +import ThunderIDAPIError from '../errors/ThunderIDAPIError'; + +/** + * Builds the error for a failed self-service response. A `401` that asks for a more recent sign-in + * becomes a {@link StepUpRequiredError} with the code `-StepUpRequired-001`; anything else is + * a {@link ThunderIDAPIError} with the code `-ResponseError-001`. + * + * @param operation - The operation name used in the error code, such as `updateMeProfile`. + * @param errorText - The response body. + * @param response - The response. + * @param prefix - The prefix of the error message. + * @returns The error to throw. + */ +const createApiResponseError = ( + operation: string, + errorText: string, + response: Response, + prefix: string, +): ThunderIDAPIError => { + const wwwAuthenticate: string | null | undefined = response.headers?.get?.('www-authenticate'); + const error: ThunderIDAPIError = new ThunderIDAPIError( + errorText, + `${operation}-ResponseError-001`, + 'javascript', + response.status, + response.statusText, + prefix, + wwwAuthenticate, + ); + + if (error.authenticationChallenge?.error !== INSUFFICIENT_USER_AUTHENTICATION) { + return error; + } + + return new StepUpRequiredError( + errorText, + `${operation}-StepUpRequired-001`, + 'javascript', + response.status, + response.statusText, + prefix, + wwwAuthenticate, + ); +}; + +export default createApiResponseError; diff --git a/packages/javascript/src/utils/mapCredentialUpdateError.ts b/packages/javascript/src/utils/mapCredentialUpdateError.ts index fa9130b2..7cb5a543 100644 --- a/packages/javascript/src/utils/mapCredentialUpdateError.ts +++ b/packages/javascript/src/utils/mapCredentialUpdateError.ts @@ -1,25 +1,36 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 +import mapReauthenticationError from './mapReauthenticationError'; +import {RECENT_AUTHENTICATION_REQUIRED_CODE} from './parseAuthenticationChallenge'; +import {REAUTHENTICATION_FAILED} from './runWithStepUp'; +import StepUpRequiredError from '../errors/StepUpRequiredError'; import ThunderIDAPIError from '../errors/ThunderIDAPIError'; import ThunderIDError from '../errors/ThunderIDError'; +import ThunderIDRuntimeError from '../errors/ThunderIDRuntimeError'; +import {AuthenticationChallenge} from '../models/api'; /** * The form field a credential-update failure belongs to, or `null` when the failure has * no single field to blame and belongs at form level. */ -export type CredentialUpdateErrorField = 'newPassword' | null; +export type CredentialUpdateErrorField = 'currentPassword' | 'newPassword' | null; /** * Where a credential-update failure should be shown, and what it should say. * * `messageKey` is always set, so the caller can resolve text with a plain * `message ?? t(messageKey)` and never needs a non-null assertion. `message` is present - * only when the server supplied something human-readable, and takes precedence when it - * is. Translation is left to the caller, which keeps this module free of i18n concerns - * in the same way {@link evaluatePasswordPolicy} is. + * only when the server supplied something human-readable and the SDK has no translated + * text for the failure. Translation is left to the caller, which keeps this module free + * of i18n concerns in the same way {@link evaluatePasswordPolicy} is. */ export interface CredentialUpdateErrorResult { + /** + * Set when the change needs a more recent sign-in (`AUTH-4011`). Sign the user in again + * with its `maxAge` and retry. + */ + authenticationChallenge?: AuthenticationChallenge; /** * The field to attach the error to, or `null` for a form-level error. */ @@ -34,12 +45,27 @@ export interface CredentialUpdateErrorResult { messageKey: string; } +const GENERIC_MESSAGE_KEY = 'user.change_password.generic.error'; + +/** + * Server codes the SDK has its own translated text for. + */ +const KNOWN_FAILURES: Record = { + [RECENT_AUTHENTICATION_REQUIRED_CODE]: {field: null, messageKey: 'user.change_password.reauthentication.error'}, + 'USR-1047': {field: 'currentPassword', messageKey: 'user.change_password.current.required.error'}, + 'USR-1048': {field: 'currentPassword', messageKey: 'user.change_password.current.invalid.error'}, +}; + /** * Maps a failure from the credential write path onto the field that caused it. * - * `400` is the new password failing a server-side check. Everything else, including a - * `403`, has no single field to blame here: this form collects no current-value field for - * a `403` to attach to, since the server does not verify one on this path today. + * - `USR-1047` (current value missing) and `USR-1048` (current value does not match) belong + * to the current-value field. + * - `AUTH-4011` (the change needs a more recent sign-in) is form-level and carries the + * challenge, so the caller can sign the user in again. + * - A failed re-sign-in from {@link runWithStepUp} is form-level, with the text for why it failed. + * - Any other `400` is the new value failing a server-side check. + * - Everything else is form-level, with the server's message when it sent one. * * @param error - The value thrown by the credential update call. * @returns Where to show the failure and what to show. @@ -55,13 +81,30 @@ export interface CredentialUpdateErrorResult { * } * ``` */ -const GENERIC_MESSAGE_KEY = 'user.change_password.generic.error'; - const mapCredentialUpdateError = (error: unknown): CredentialUpdateErrorResult => { - const status: number | undefined = error instanceof ThunderIDAPIError ? error.statusCode : undefined; + if (error instanceof ThunderIDRuntimeError && error.code === REAUTHENTICATION_FAILED) { + return { + field: null, + messageKey: mapReauthenticationError((error.details as {cause?: unknown} | undefined)?.cause), + }; + } + + const apiError: ThunderIDAPIError | undefined = error instanceof ThunderIDAPIError ? error : undefined; + // A step-up error is known by its type too, for a challenge read from the header alone. + const serverCode: string | undefined = + error instanceof StepUpRequiredError ? RECENT_AUTHENTICATION_REQUIRED_CODE : apiError?.serverError?.code; + const known: {field: CredentialUpdateErrorField; messageKey: string} | undefined = + serverCode !== undefined ? KNOWN_FAILURES[serverCode] : undefined; + + if (known) { + return { + ...known, + ...(apiError?.authenticationChallenge && {authenticationChallenge: apiError.authenticationChallenge}), + }; + } - if (status === 400 && error instanceof ThunderIDError) { - return {field: 'newPassword', message: error.message, messageKey: GENERIC_MESSAGE_KEY}; + if (apiError?.statusCode === 400) { + return {field: 'newPassword', message: apiError.message, messageKey: GENERIC_MESSAGE_KEY}; } if (error instanceof ThunderIDError) { diff --git a/packages/javascript/src/utils/mapReauthenticationError.ts b/packages/javascript/src/utils/mapReauthenticationError.ts new file mode 100644 index 00000000..88894317 --- /dev/null +++ b/packages/javascript/src/utils/mapReauthenticationError.ts @@ -0,0 +1,29 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/** + * The i18n key for a failed re-sign-in: a blocked popup, a sign-in with a different account (in a popup + * or a sign-in flow), or any other failure. + * + * @param error - The value `reauthenticate` threw. + * @returns The i18n key to show. + * @example + * ```typescript + * setError(t(mapReauthenticationError(caughtError))); + * ``` + */ +const mapReauthenticationError = (error: unknown): string => { + const code: unknown = (error as {code?: unknown} | undefined)?.code; + + if (code === 'BROWSER-REAUTHENTICATION-PB01') { + return 'user.reauthentication.popup_blocked.error'; + } + + if (code === 'JS-AUTH_CORE-CRA-IV03' || code === 'BROWSER-REAUTHENTICATION-DU01') { + return 'user.reauthentication.different_user.error'; + } + + return 'user.reauthentication.failed.error'; +}; + +export default mapReauthenticationError; diff --git a/packages/javascript/src/utils/parseAuthenticationChallenge.ts b/packages/javascript/src/utils/parseAuthenticationChallenge.ts new file mode 100644 index 00000000..163fa53a --- /dev/null +++ b/packages/javascript/src/utils/parseAuthenticationChallenge.ts @@ -0,0 +1,101 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AuthenticationChallenge, ServerError} from '../models/api'; + +/** + * The error `error` value of a challenge that asks for a more recent sign-in (RFC 9470). + */ +export const INSUFFICIENT_USER_AUTHENTICATION = 'insufficient_user_authentication'; + +/** + * The server code that comes with a request for a more recent sign-in. + */ +export const RECENT_AUTHENTICATION_REQUIRED_CODE = 'AUTH-4011'; + +const toMaxAge = (value: string | undefined): number | undefined => { + if (value === undefined || !/^\d+$/.test(value.trim())) { + return undefined; + } + + return Number(value.trim()); +}; + +/** + * Reads the `Bearer` challenge from a `WWW-Authenticate` header value. + */ +const parseHeader = (header: string): AuthenticationChallenge | undefined => { + const bearer: RegExpExecArray | null = /(?:^|,)\s*Bearer\s+(.*)$/i.exec(header); + + if (!bearer) { + return undefined; + } + + const params: Record = {}; + const pattern = /([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,"]+))/g; + let match: RegExpExecArray | null = pattern.exec(bearer[1]); + + while (match !== null) { + const key: string = match[1].toLowerCase(); + + if (!(key in params)) { + params[key] = match[2] !== undefined ? match[2].replace(/\\(.)/g, '$1') : match[3]; + } + + match = pattern.exec(bearer[1]); + } + + if (!params['error']) { + return undefined; + } + + return { + error: params['error'], + ...(params['error_description'] !== undefined && {errorDescription: params['error_description']}), + ...(toMaxAge(params['max_age']) !== undefined && {maxAge: toMaxAge(params['max_age'])}), + }; +}; + +/** + * Reads the challenge of a `401` that asks for a more recent sign-in (RFC 9470). + * + * The `WWW-Authenticate` header is read first. When it is missing, for example because a browser + * does not expose it, a body with the code `AUTH-4011` gives the challenge and its `maxAge` parameter. + * + * @param wwwAuthenticate - The response's `WWW-Authenticate` header value, if any. + * @param serverError - The response's error body, if any. + * @returns The challenge, or `undefined` when the response carries none. + * @example + * ```typescript + * const challenge = parseAuthenticationChallenge(response.headers.get('www-authenticate')); + * if (challenge?.error === 'insufficient_user_authentication') { + * await signIn({max_age: String(challenge.maxAge ?? 0)}); + * } + * ``` + */ +const parseAuthenticationChallenge = ( + wwwAuthenticate?: string | null, + serverError?: ServerError, +): AuthenticationChallenge | undefined => { + const fromHeader: AuthenticationChallenge | undefined = wwwAuthenticate ? parseHeader(wwwAuthenticate) : undefined; + + if (fromHeader) { + if (fromHeader.maxAge === undefined && serverError?.code === RECENT_AUTHENTICATION_REQUIRED_CODE) { + const maxAge: number | undefined = toMaxAge(serverError.description?.params?.['maxAge']); + + return maxAge === undefined ? fromHeader : {...fromHeader, maxAge}; + } + + return fromHeader; + } + + if (serverError?.code === RECENT_AUTHENTICATION_REQUIRED_CODE) { + const maxAge: number | undefined = toMaxAge(serverError.description?.params?.['maxAge']); + + return {error: INSUFFICIENT_USER_AUTHENTICATION, ...(maxAge !== undefined && {maxAge})}; + } + + return undefined; +}; + +export default parseAuthenticationChallenge; diff --git a/packages/javascript/src/utils/pickRecentSignInParams.ts b/packages/javascript/src/utils/pickRecentSignInParams.ts new file mode 100644 index 00000000..20169f19 --- /dev/null +++ b/packages/javascript/src/utils/pickRecentSignInParams.ts @@ -0,0 +1,40 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/** + * The authorization parameters that ask for a recent sign-in. + */ +export interface RecentSignInParams { + max_age?: string; + prompt?: 'login'; +} + +/** + * Picks, from sign-in options or a sign-in route's query, the authorization parameters that ask for a + * recent sign-in: `max_age` as a whole number of seconds, zero or more, and `prompt` when it is `login`. + * Everything else is dropped, so a route can pass them on to the authorization request. + * + * @param options - The sign-in options or query. + * @returns The parameters to add to the authorization request. + * @example + * ```typescript + * pickRecentSignInParams({max_age: '180', returnTo: '/account'}); // {max_age: '180'} + * ``` + */ +const pickRecentSignInParams = (options?: Record | null): RecentSignInParams => { + const params: RecentSignInParams = {}; + const maxAge: unknown = options?.['max_age']; + const text: string = typeof maxAge === 'number' ? String(maxAge) : typeof maxAge === 'string' ? maxAge.trim() : ''; + + if (/^\d+$/.test(text)) { + params.max_age = String(Number(text)); + } + + if (options?.['prompt'] === 'login') { + params.prompt = 'login'; + } + + return params; +}; + +export default pickRecentSignInParams; diff --git a/packages/javascript/src/utils/runWithStepUp.ts b/packages/javascript/src/utils/runWithStepUp.ts new file mode 100644 index 00000000..3c02f9f3 --- /dev/null +++ b/packages/javascript/src/utils/runWithStepUp.ts @@ -0,0 +1,144 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {INSUFFICIENT_USER_AUTHENTICATION} from './parseAuthenticationChallenge'; +import StepUpRequiredError from '../errors/StepUpRequiredError'; +import ThunderIDRuntimeError from '../errors/ThunderIDRuntimeError'; +import {AuthenticationChallenge} from '../models/api'; +import {ReauthenticationOptions} from '../models/reauthentication'; + +/** + * The code of the error {@link runWithStepUp} throws when signing in again failed. Its `details.cause` is + * the error `reauthenticate` threw; map it with `mapReauthenticationError`. + */ +export const REAUTHENTICATION_FAILED = 'JS-STEP_UP-RF01'; + +/** + * The code of the error {@link runWithStepUp} throws when the caller stopped being active, for example a + * form that closed, while the user signed in again. The change is then not sent. + */ +export const STEP_UP_ABANDONED = 'JS-STEP_UP-AB01'; + +/** + * Holds a challenge the user has not answered yet, for example because the browser blocked the popup, + * so the next attempt signs in again first, inside the user action. + */ +export interface PendingStepUp { + current?: AuthenticationChallenge; +} + +export interface RunWithStepUpOptions { + /** + * Checked after signing in again, before the change is sent once more. When it returns `false`, for + * example because the form that holds the change has closed, the change is not sent. + */ + isActive?: () => boolean; + /** + * Called instead of signing in again, when the application handles the challenge itself. The + * `StepUpRequiredError` is then rethrown. + */ + onReauthenticationRequired?: (challenge: AuthenticationChallenge) => void; + /** + * The challenge left from an earlier attempt, if any. + */ + pending?: PendingStepUp; + /** + * Signs the user in again, replacing the session's tokens. + */ + reauthenticate: (options: ReauthenticationOptions) => Promise; + /** + * Sends the change. Called at most twice: once, and once more after signing in again. + */ + send: () => Promise; +} + +/** + * Sends a self-service change and, when the server asks for a more recent sign-in, signs the user in + * again with the challenge's `maxAge` and sends the change once more. The change stays in the caller's + * memory only. It never refreshes the token, since a refreshed token keeps the original sign-in time. + * + * - A second refusal, step-up included, is thrown as it is. + * - A failed re-sign-in throws a `ThunderIDRuntimeError` with the code {@link REAUTHENTICATION_FAILED}, + * and keeps the challenge in `pending`, so the next call signs in again before sending. + * + * @param options - The change, the re-sign-in, and the pending challenge. + * @returns What `send` returned. + * @example + * ```typescript + * await runWithStepUp({ + * pending, + * reauthenticate: (options) => client.reauthenticate(options), + * send: () => updateMeProfile({baseUrl, payload, fetcher}), + * }); + * ``` + */ +const runWithStepUp = async ({ + isActive, + onReauthenticationRequired, + pending, + reauthenticate, + send, +}: RunWithStepUpOptions): Promise => { + const signInAgain = async (challenge: AuthenticationChallenge): Promise => { + try { + await reauthenticate({maxAge: challenge.maxAge}); + } catch (cause: unknown) { + if (pending) { + pending.current = challenge; + } + + const details: {cause: unknown} = {cause}; + + throw new ThunderIDRuntimeError( + 'Signing in again did not complete.', + REAUTHENTICATION_FAILED, + 'javascript', + details, + ); + } + }; + + const sendAgain = (): Promise => { + if (isActive && !isActive()) { + throw new ThunderIDRuntimeError( + 'The change was not sent: it was left before signing in again completed.', + STEP_UP_ABANDONED, + 'javascript', + ); + } + + return send(); + }; + + const left: AuthenticationChallenge | undefined = pending?.current; + + if (left && !onReauthenticationRequired) { + pending!.current = undefined; + await signInAgain(left); + + return sendAgain(); + } + + try { + return await send(); + } catch (error) { + if (!(error instanceof StepUpRequiredError)) { + throw error; + } + + const challenge: AuthenticationChallenge = error.authenticationChallenge ?? { + error: INSUFFICIENT_USER_AUTHENTICATION, + }; + + if (onReauthenticationRequired) { + onReauthenticationRequired(challenge); + throw error; + } + + await signInAgain(challenge); + + return sendAgain(); + } +}; + +export default runWithStepUp; diff --git a/packages/nextjs/CHANGELOG.md b/packages/nextjs/CHANGELOG.md index adcfb057..40f864bf 100644 --- a/packages/nextjs/CHANGELOG.md +++ b/packages/nextjs/CHANGELOG.md @@ -7,6 +7,8 @@ No changes to this SDK since sdk/nextjs/v1.24.0. ## 1.24.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 + +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/nextjs/v1.23.0...sdk/nextjs/v1.24.0 diff --git a/packages/nextjs/src/ThunderIDNextClient.ts b/packages/nextjs/src/ThunderIDNextClient.ts index 572496b2..31d2cda6 100644 --- a/packages/nextjs/src/ThunderIDNextClient.ts +++ b/packages/nextjs/src/ThunderIDNextClient.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { @@ -27,6 +27,7 @@ import { getUsersMe, getUsersMeMeta, updateMeCredentials, + UpdateMeCredentialsPayload, updateMeProfile, resolveResourceEndpoint, } from '@thunderid/node'; @@ -209,8 +210,8 @@ class ThunderIDNextClient e } /** - * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other - * attribute the user type schema declares `credential: true`). + * Sets one of the signed-in user's credentials (e.g. `password`, or any other attribute the + * user type schema declares `credential: true`), with its current value when the user holds it. * * Not part of {@link ThunderIDJavaScriptClient}'s base surface — unlike `updateUserProfile`, * no other SDK routes credential updates through a client method (React/Vue's @@ -223,7 +224,7 @@ class ThunderIDNextClient e * included, to map a failure onto the right form field before it crosses the server action * boundary back to the client. */ - override async updateUserCredentials(payload: Record, userId?: string): Promise { + override async updateUserCredentials(payload: UpdateMeCredentialsPayload, userId?: string): Promise { await this.ensureInitialized(); const configData: AuthClientConfig = await this.getStorageManager().getConfigData(); diff --git a/packages/nextjs/src/client/components/account/ChangeCredential/ChangeCredential.tsx b/packages/nextjs/src/client/components/account/ChangeCredential/ChangeCredential.tsx index 0b5f0eb1..d5144a09 100644 --- a/packages/nextjs/src/client/components/account/ChangeCredential/ChangeCredential.tsx +++ b/packages/nextjs/src/client/components/account/ChangeCredential/ChangeCredential.tsx @@ -3,7 +3,13 @@ 'use client'; -import {CredentialConstants, PasswordPolicy, resolveChangeCredentialPolicy, supportsCredential} from '@thunderid/node'; +import { + AuthenticationChallenge, + CredentialConstants, + PasswordPolicy, + resolveChangeCredentialPolicy, + supportsCredential, +} from '@thunderid/node'; import { BaseChangeCredential, BaseChangeCredentialProps, @@ -41,6 +47,12 @@ export type ChangeCredentialProps = Omit< * `` for a PIN. */ attribute?: string; + /** + * Called when setting the credential needs a more recent sign-in (`AUTH-4011`), with the + * server's challenge. Sign the user in again with `challenge.maxAge` as the `max_age` + * authorization parameter, then let the user submit again. + */ + onReauthenticationRequired?: (challenge: AuthenticationChallenge) => void; /** * Called after the credential has been changed successfully. */ @@ -55,6 +67,11 @@ export type ChangeCredentialProps = Omit< * `updateUserCredentialsAction` (a server action) instead of calling the ThunderID server * directly from the browser, matching how `UserProfile` reaches `updateUserProfileAction`. * + * The server needs the current value when the user holds the credential. A user who has not + * set it yet leaves the current value empty; that change needs a recent sign-in, and when the + * sign-in is too old the form asks the user to sign in again and calls + * `onReauthenticationRequired`. + * * Defaults to managing the `password` credential. To manage a different one (for example a * PIN declared on the user type schema), set `attribute`; render the component once per * credential to let a user manage several. @@ -70,6 +87,7 @@ export type ChangeCredentialProps = Omit< */ const ChangeCredential: FC = ({ attribute = CredentialConstants.PASSWORD, + onReauthenticationRequired, onSuccess, policy, preferences, @@ -99,14 +117,14 @@ const ChangeCredential: FC = ({ [userSchema, attribute, policy], ); - const handleSubmit = async ({newPassword}: ChangePasswordValues): Promise => { + const handleSubmit = async ({currentPassword, newPassword}: ChangePasswordValues): Promise => { setError(null); setFieldErrors({}); setSuccess(false); setLoading(true); const result: UpdateUserCredentialsActionResult = await updateUserCredentialsAction( - {[attribute]: newPassword}, + {currentValue: currentPassword, name: attribute, newValue: newPassword}, await getSessionId(), ); @@ -123,6 +141,10 @@ const ChangeCredential: FC = ({ } else { setError(text); } + + if (result.authenticationChallenge) { + onReauthenticationRequired?.(result.authenticationChallenge); + } } setLoading(false); diff --git a/packages/nextjs/src/client/components/account/UserProfile/UserProfile.tsx b/packages/nextjs/src/client/components/account/UserProfile/UserProfile.tsx index 5d6c0a33..c1bf1718 100644 --- a/packages/nextjs/src/client/components/account/UserProfile/UserProfile.tsx +++ b/packages/nextjs/src/client/components/account/UserProfile/UserProfile.tsx @@ -1,9 +1,9 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 'use client'; -import {AttributeVerificationConstants, deepMerge, User} from '@thunderid/node'; +import {AttributeVerificationConstants, AuthenticationChallenge, deepMerge, User} from '@thunderid/node'; import { BaseUserProfile, BaseUserProfileProps, @@ -26,6 +26,12 @@ export type UserProfileProps = Omit void; }; /** @@ -55,6 +61,7 @@ const UserProfile: FC = ({ preferences, editable = true, verificationFlowHandle = AttributeVerificationConstants.DEFAULT_FLOW_HANDLE, + onReauthenticationRequired, ...rest }: UserProfileProps): ReactElement => { const {preferences: contextPreferences} = useThunderID(); @@ -83,13 +90,18 @@ const UserProfile: FC = ({ } }); - const result: {data: {user: User}; error: string; success: boolean} = await updateProfile( - {payload: updatedAttributes}, - await getSessionId(), - ); + const result: { + authenticationChallenge?: AuthenticationChallenge; + data: {user: User}; + error: string; + success: boolean; + } = await updateProfile({payload: updatedAttributes}, await getSessionId()); if (result.success) { onUpdateProfile(result.data.user); + } else if (result.authenticationChallenge) { + setError(t('user.reauthentication.required.error')); + onReauthenticationRequired?.(result.authenticationChallenge); } else { setError(result.error || t('user.profile.update.generic.error')); } diff --git a/packages/nextjs/src/client/contexts/ThunderID/ThunderIDProvider.tsx b/packages/nextjs/src/client/contexts/ThunderID/ThunderIDProvider.tsx index 1fe6c5af..f580fa81 100644 --- a/packages/nextjs/src/client/contexts/ThunderID/ThunderIDProvider.tsx +++ b/packages/nextjs/src/client/contexts/ThunderID/ThunderIDProvider.tsx @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 'use client'; @@ -475,6 +475,7 @@ const ThunderIDClientProvider: FC Promise.resolve(null), http: { // The admin components and hooks send management requests through a server action that adds diff --git a/packages/nextjs/src/server/actions/account/__tests__/updateUserProfileAction.test.ts b/packages/nextjs/src/server/actions/account/__tests__/updateUserProfileAction.test.ts new file mode 100644 index 00000000..4fd3a3b3 --- /dev/null +++ b/packages/nextjs/src/server/actions/account/__tests__/updateUserProfileAction.test.ts @@ -0,0 +1,59 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError} from '@thunderid/node'; +import {beforeEach, describe, expect, it, Mock, vi} from 'vitest'; +import getClient from '../../../getClient'; +import updateUserProfileAction from '../updateUserProfileAction'; + +vi.mock('../../../getClient', () => ({default: vi.fn()})); + +describe('updateUserProfileAction', () => { + const updateUserProfile: Mock = vi.fn(); + + beforeEach(() => { + vi.resetAllMocks(); + (getClient as unknown as Mock).mockReturnValue({updateUserProfile}); + }); + + it('returns the updated user', async () => { + updateUserProfile.mockResolvedValue({id: 'u-1'}); + + expect(await updateUserProfileAction({payload: {email: 'a@example.com'}}, 's-1')).toEqual({ + data: {user: {id: 'u-1'}}, + error: '', + success: true, + }); + expect(updateUserProfile).toHaveBeenCalledWith({payload: {email: 'a@example.com'}}, 's-1'); + }); + + it('returns the challenge when the change needs a more recent sign-in', async () => { + updateUserProfile.mockRejectedValue( + new ThunderIDAPIError( + JSON.stringify({code: 'AUTH-4011'}), + 'updateMeProfile-ResponseError-001', + 'javascript', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="180"', + ), + ); + + const result = await updateUserProfileAction({payload: {email: 'a@example.com'}}); + + expect(result).toMatchObject({ + authenticationChallenge: {error: 'insufficient_user_authentication', maxAge: 180}, + success: false, + }); + }); + + it('returns no challenge for any other failure', async () => { + updateUserProfile.mockRejectedValue(new Error('offline')); + + const result = await updateUserProfileAction({payload: {}}); + + expect(result.success).toBe(false); + expect(result).not.toHaveProperty('authenticationChallenge'); + }); +}); diff --git a/packages/nextjs/src/server/actions/account/updateUserCredentialsAction.ts b/packages/nextjs/src/server/actions/account/updateUserCredentialsAction.ts index fe0dfd48..729e4ad2 100644 --- a/packages/nextjs/src/server/actions/account/updateUserCredentialsAction.ts +++ b/packages/nextjs/src/server/actions/account/updateUserCredentialsAction.ts @@ -3,7 +3,7 @@ 'use server'; -import {CredentialUpdateErrorResult, mapCredentialUpdateError} from '@thunderid/node'; +import {CredentialUpdateErrorResult, UpdateMeCredentialsPayload, mapCredentialUpdateError} from '@thunderid/node'; import getClient from '../../getClient'; export interface UpdateUserCredentialsActionResult extends CredentialUpdateErrorResult { @@ -20,7 +20,7 @@ export interface UpdateUserCredentialsActionResult extends CredentialUpdateError * the plain, serializable result crosses back. */ const updateUserCredentialsAction = async ( - payload: Record, + payload: UpdateMeCredentialsPayload, sessionId?: string, ): Promise => { try { @@ -28,8 +28,7 @@ const updateUserCredentialsAction = async ( await client.updateUserCredentials(payload, sessionId); return {field: null, messageKey: '', success: true}; } catch (error) { - const {field, message, messageKey}: CredentialUpdateErrorResult = mapCredentialUpdateError(error); - return {field, message, messageKey, success: false}; + return {...mapCredentialUpdateError(error), success: false}; } }; diff --git a/packages/nextjs/src/server/actions/account/updateUserProfileAction.ts b/packages/nextjs/src/server/actions/account/updateUserProfileAction.ts index 1062c73e..3fb5ab3d 100644 --- a/packages/nextjs/src/server/actions/account/updateUserProfileAction.ts +++ b/packages/nextjs/src/server/actions/account/updateUserProfileAction.ts @@ -1,25 +1,40 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 'use server'; -import {UpdateMeProfileConfig, User} from '@thunderid/node'; +import { + AuthenticationChallenge, + INSUFFICIENT_USER_AUTHENTICATION, + ThunderIDAPIError, + UpdateMeProfileConfig, + User, +} from '@thunderid/node'; import getClient from '../../getClient'; /** - * Server action to get the current user. - * Returns the user profile if signed in. + * Server action that updates the signed-in user's profile. When the change needs a more recent sign-in + * (`AUTH-4011`), the result carries the server's `authenticationChallenge`. */ const updateUserProfileAction = async ( payload: UpdateMeProfileConfig, sessionId?: string, -): Promise<{data: {user: User}; error: string; success: boolean}> => { +): Promise<{ + authenticationChallenge?: AuthenticationChallenge; + data: {user: User}; + error: string; + success: boolean; +}> => { try { const client = getClient(); const user: User = await client.updateUserProfile(payload, sessionId); return {data: {user}, error: '', success: true}; } catch (error) { + const challenge: AuthenticationChallenge | undefined = + error instanceof ThunderIDAPIError ? error.authenticationChallenge : undefined; + return { + ...(challenge?.error === INSUFFICIENT_USER_AUTHENTICATION ? {authenticationChallenge: {...challenge}} : {}), data: { user: {}, }, diff --git a/packages/nextjs/src/server/actions/auth/__tests__/signInAction.test.ts b/packages/nextjs/src/server/actions/auth/__tests__/signInAction.test.ts index 8045a645..1466ddfb 100644 --- a/packages/nextjs/src/server/actions/auth/__tests__/signInAction.test.ts +++ b/packages/nextjs/src/server/actions/auth/__tests__/signInAction.test.ts @@ -12,21 +12,34 @@ vi.mock('next/headers', () => ({cookies: vi.fn()})); vi.mock('../../../getClient', () => ({default: vi.fn()})); vi.mock('../../../../utils/SessionManager', () => ({ default: { + createSessionToken: vi.fn(), createTempSession: vi.fn(), getSessionCookieName: vi.fn(), + getSessionCookieOptions: vi.fn(), getTempSessionCookieName: vi.fn(), getTempSessionCookieOptions: vi.fn(), + resolveSessionCookieExpiry: vi.fn(), }, })); describe('signInAction', () => { - let client: {signIn: Mock}; + let client: Record; + let cookieStore: Record; beforeEach(() => { vi.resetAllMocks(); - client = {signIn: vi.fn()}; + client = { + exchangeFlowAssertion: vi.fn(), + getAuthorizeRequestUrl: vi.fn().mockResolvedValue('https://idp.example.com/oauth2/authorize'), + getConfiguration: vi.fn().mockResolvedValue({}), + decodeJwtToken: vi.fn().mockResolvedValue({sid: 'sid-1', sub: 'user-1'}), + getDecodedIdToken: vi.fn().mockResolvedValue({sid: 'old-sid', sub: 'old-user'}), + getStorageManager: vi.fn().mockResolvedValue({getConfigDataParameter: vi.fn().mockResolvedValue('/home')}), + signIn: vi.fn(), + }; (getClient as unknown as Mock).mockReturnValue(client); - (cookies as unknown as Mock).mockResolvedValue({get: vi.fn(), getAll: vi.fn(() => []), set: vi.fn()}); + cookieStore = {delete: vi.fn(), get: vi.fn(), getAll: vi.fn(() => []), set: vi.fn()}; + (cookies as unknown as Mock).mockResolvedValue(cookieStore); (SessionManager.createTempSession as unknown as Mock).mockResolvedValue('temp-token'); }); @@ -47,4 +60,67 @@ describe('signInAction', () => { expect(result).toEqual({error: 'offline', success: false}); }); + + describe('a redirect sign-in', () => { + it('starts a new session for a recent sign-in, and sends only max_age and prompt', async () => { + (SessionManager.getTempSessionCookieName as unknown as Mock).mockReturnValue('temp'); + cookieStore['getAll'].mockReturnValue([{name: 'session', value: 'signed-in-token'}]); + + const result = await signInAction({login_hint: 'x', max_age: 180, prompt: 'login'}, {}); + + expect(SessionManager.createTempSession).toHaveBeenCalledTimes(1); + expect(cookieStore['set']).toHaveBeenCalledWith('temp', 'temp-token', undefined); + const [params, sessionId] = client['getAuthorizeRequestUrl'].mock.calls[0]; + expect(params).toEqual({max_age: '180', prompt: 'login'}); + expect(sessionId).toBe((SessionManager.createTempSession as unknown as Mock).mock.calls[0][0]); + expect(result).toEqual({data: {signInUrl: 'https://idp.example.com/oauth2/authorize'}, success: true}); + }); + + it('starts the embedded flow for a payload that names the flow type', async () => { + client['signIn'].mockResolvedValue({executionId: 'e-1', flowStatus: 'INCOMPLETE'}); + + await signInAction({flowType: 'AUTHENTICATION'}, {}); + + expect(client['signIn']).toHaveBeenCalled(); + expect(client['getAuthorizeRequestUrl']).not.toHaveBeenCalled(); + }); + }); + + describe('when the flow completes', () => { + beforeEach(() => { + client['signIn'].mockResolvedValue({assertion: 'flow-assertion', flowStatus: 'COMPLETE'}); + (SessionManager.getSessionCookieName as unknown as Mock).mockReturnValue('session'); + (SessionManager.createSessionToken as unknown as Mock).mockResolvedValue('session-token'); + }); + + it('keeps the access token the assertion is exchanged for in the session', async () => { + client['exchangeFlowAssertion'].mockResolvedValue({ + access_token: 'exchanged-at', + expires_in: '900', + id_token: 'flow-assertion', + scope: 'self', + }); + + const result = await signInAction({executionId: 'e-1'}, {}); + + expect(client['exchangeFlowAssertion']).toHaveBeenCalledWith('flow-assertion'); + // The identity comes from the new assertion, not an ID token stored for the session ID. + expect(client['decodeJwtToken']).toHaveBeenCalledWith('flow-assertion'); + expect(client['getDecodedIdToken']).not.toHaveBeenCalled(); + expect((SessionManager.createSessionToken as unknown as Mock).mock.calls).toEqual([ + ['exchanged-at', 'user-1', expect.any(String), 'self', 900, '', undefined, {sid: 'sid-1'}], + ]); + expect(cookieStore['set']).toHaveBeenCalledWith('session', 'session-token', undefined); + expect(result).toEqual({data: {afterSignInUrl: '/home'}, success: true}); + }); + + it('sets no session when the assertion cannot be exchanged', async () => { + client['exchangeFlowAssertion'].mockRejectedValue(new Error('needs the token exchange grant')); + + const result = await signInAction({executionId: 'e-1'}, {}); + + expect((SessionManager.createSessionToken as unknown as Mock).mock.calls).toEqual([]); + expect(result).toEqual({error: 'needs the token exchange grant', success: false}); + }); + }); }); diff --git a/packages/nextjs/src/server/actions/auth/signInAction.ts b/packages/nextjs/src/server/actions/auth/signInAction.ts index e2be25fe..9a629ae2 100644 --- a/packages/nextjs/src/server/actions/auth/signInAction.ts +++ b/packages/nextjs/src/server/actions/auth/signInAction.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 'use server'; @@ -9,7 +9,10 @@ import { EmbeddedFlowExecuteRequestConfig, IdToken, isEmpty, + pickRecentSignInParams, + RecentSignInParams, ServerError, + SessionData, ThunderIDAPIError, } from '@thunderid/node'; import {cookies} from 'next/headers'; @@ -50,10 +53,21 @@ const signInAction = async ( let sessionId: string | undefined; - const existingSessionToken: string | undefined = getChunkedCookie( - cookieStore, - SessionManager.getSessionCookieName(), - ); + // Without a flow payload, the user signs in by redirect. Of the sign-in options, only `max_age` and + // `prompt=login`, which ask for a recent sign-in, reach the authorization request. + const isRedirect: boolean = + !payload || + isEmpty(payload) || + !('executionId' in payload || 'applicationId' in payload || 'flowType' in payload); + const recentSignInParams: RecentSignInParams = isRedirect + ? pickRecentSignInParams(payload as Record | undefined) + : {}; + // A recent sign-in for a signed-in user starts a new session, whose callback then replaces the cookie. + const isRecentSignIn: boolean = Object.keys(recentSignInParams).length > 0; + + const existingSessionToken: string | undefined = isRecentSignIn + ? undefined + : getChunkedCookie(cookieStore, SessionManager.getSessionCookieName()); if (existingSessionToken) { try { @@ -64,7 +78,7 @@ const signInAction = async ( } } - if (!sessionId) { + if (!sessionId && !isRecentSignIn) { const tempSessionToken: string | undefined = cookieStore.get(SessionManager.getTempSessionCookieName())?.value; if (tempSessionToken) { @@ -89,9 +103,8 @@ const signInAction = async ( ); } - // If no payload provided, redirect to sign-in URL for redirect-based sign-in. - if (!payload || isEmpty(payload)) { - const defaultSignInUrl: string = await client.getAuthorizeRequestUrl({}, sessionId); + if (isRedirect) { + const defaultSignInUrl: string = await client.getAuthorizeRequestUrl({...recentSignInParams}, sessionId); return {data: {signInUrl: String(defaultSignInUrl)}, success: true}; } @@ -99,23 +112,21 @@ const signInAction = async ( const response: any = await client.signIn(payload, request!, sessionId); if (response.flowStatus === EmbeddedSignInFlowStatus.Complete) { - // On the V2 platform, a completed embedded flow (without a preceding `/authorize` redirect, - // i.e. no `authId`) returns a self-contained JWT `assertion` rather than an authorization - // code to exchange. This mirrors how @thunderid/react and @thunderid/vue treat it: the - // assertion is used directly as the bearer session token. + // A completed embedded flow (no preceding `/authorize` redirect, i.e. no `authId`) returns a + // JWT `assertion`, which is exchanged for the session's access token. if (!response.assertion) { throw new Error('[signInAction] Flow completed without an assertion.'); } - const idToken: IdToken = await client.getDecodedIdToken(sessionId, response.assertion); + const tokens: SessionData = await client.exchangeFlowAssertion(response.assertion); + // The new assertion, not an ID token stored for this session ID by an earlier sign-in. + const idToken: IdToken = await client.decodeJwtToken(response.assertion); const userIdFromToken: string = (idToken.sub as string | undefined) ?? sessionId; const organizationId: string | undefined = (idToken['user_org'] || idToken['organization_id']) as | string | undefined; - const scopes: string = (idToken['scope'] as string | undefined) ?? ''; - const iat: number = (idToken['iat'] as number | undefined) ?? Math.floor(Date.now() / 1000); - const exp: number = (idToken['exp'] as number | undefined) ?? iat + 3600; - const expiresIn: number = Math.max(exp - iat, 0); + const scopes: string = tokens.scope; + const expiresIn: number = Math.max(parseInt(tokens.expires_in, 10) || 0, 0); const config: ThunderIDNextConfig = await client.getConfiguration(); const sessionCookieExpiryTime: number = SessionManager.resolveSessionCookieExpiry( @@ -123,7 +134,7 @@ const signInAction = async ( ); const sessionToken: string = await SessionManager.createSessionToken( - response.assertion, + tokens.access_token, userIdFromToken, sessionId, scopes, diff --git a/packages/nextjs/src/server/actions/auth/switchOrganizationUnitAction.ts b/packages/nextjs/src/server/actions/auth/switchOrganizationUnitAction.ts index a31f2152..d674f3c8 100644 --- a/packages/nextjs/src/server/actions/auth/switchOrganizationUnitAction.ts +++ b/packages/nextjs/src/server/actions/auth/switchOrganizationUnitAction.ts @@ -35,8 +35,8 @@ export type SwitchOrganizationUnitActionResult = * endpoint and replaces the session. With `redirect: false` it fails with `interaction_required` * instead. * - Embedded mode starts an `AUTHENTICATION` flow with `ouId`. When the SSO session is reused the flow - * completes at once and its assertion replaces the session cookie; a flow that needs input fails - * with `interaction_required`. + * completes at once and the token its assertion is exchanged for replaces the session cookie; a flow + * that needs input fails with `interaction_required`. * * The previous session stays as it was on any failure. The error code is one of * `OrganizationUnitSwitchErrorCodes`. diff --git a/packages/node/src/ThunderIDNodeClient.ts b/packages/node/src/ThunderIDNodeClient.ts index 9662b87b..0e38bf92 100644 --- a/packages/node/src/ThunderIDNodeClient.ts +++ b/packages/node/src/ThunderIDNodeClient.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { @@ -36,6 +36,7 @@ import { ThunderIDRuntimeError, TokenResponse, updateMeCredentials, + UpdateMeCredentialsPayload, User, } from '@thunderid/javascript'; import evaluateAccessRequest from './api/access/evaluateAccess'; @@ -253,6 +254,15 @@ class ThunderIDNodeClient e return result; } + /** + * Exchanges the assertion a completed embedded flow returned for an access token, with the + * assertion kept as the ID token. Nothing is stored; the caller keeps the result in its session. + * The application needs the token exchange grant. + */ + public override async exchangeFlowAssertion(assertion: string): Promise { + return super.exchangeFlowAssertion(assertion); + } + /** * Starts a device authorization request (RFC 8628) for an input-constrained device or a CLI tool. Show * the user `userCode` and `verificationUri`; keep `deviceCode`, a credential, to yourself and pass it @@ -619,10 +629,11 @@ class ThunderIDNodeClient e } /** - * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other - * attribute the user type schema declares `credential: true`). + * Sets one of the signed-in user's credentials (e.g. `password`, or any other attribute the user + * type schema declares `credential: true`). Give `currentValue` when the user holds the credential; + * a first value needs a recent sign-in instead. See {@link updateMeCredentials}. */ - public async updateUserCredentials(payload: Record, userId?: string): Promise { + public async updateUserCredentials(payload: UpdateMeCredentialsPayload, userId?: string): Promise { const configData: AuthClientConfig = await this.getStorageManager().getConfigData(); const baseUrl: string | undefined = configData?.baseUrl; diff --git a/packages/node/src/__tests__/ThunderIDNodeClient.test.ts b/packages/node/src/__tests__/ThunderIDNodeClient.test.ts index b1433332..38e9c14b 100644 --- a/packages/node/src/__tests__/ThunderIDNodeClient.test.ts +++ b/packages/node/src/__tests__/ThunderIDNodeClient.test.ts @@ -28,7 +28,7 @@ describe('ThunderIDNodeClient', () => { vi.spyOn(client, 'getAccessToken').mockResolvedValue('test-access-token'); - const payload = {password: 'new-secure-password!'}; + const payload = {currentValue: 'old-secure-password!', name: 'password', newValue: 'new-secure-password!'}; await client.updateUserCredentials(payload, 'user-123'); expect(thunderJS.updateMeCredentials).toHaveBeenCalledWith({ diff --git a/packages/nuxt/CHANGELOG.md b/packages/nuxt/CHANGELOG.md index 10e45abc..bd65a0cb 100644 --- a/packages/nuxt/CHANGELOG.md +++ b/packages/nuxt/CHANGELOG.md @@ -1,7 +1,9 @@ ## 1.24.1 ### 🐛 Bug Fixes -* Report a failed passkey prompt to the flow by @KaveeshaPiumini in https://github.com/thunder-id/javascript-sdks/pull/189 + +- Report a failed passkey prompt to the flow by @KaveeshaPiumini in + https://github.com/thunder-id/javascript-sdks/pull/189 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/nuxt/v1.24.0...sdk/nuxt/v1.24.1 diff --git a/packages/nuxt/src/runtime/components/ThunderIDRoot.ts b/packages/nuxt/src/runtime/components/ThunderIDRoot.ts index 240d47b7..6ac3b808 100644 --- a/packages/nuxt/src/runtime/components/ThunderIDRoot.ts +++ b/packages/nuxt/src/runtime/components/ThunderIDRoot.ts @@ -1,8 +1,15 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {generateFlattenedUserProfile} from '@thunderid/browser'; -import type {AttributeSchema, FlowMetadataResponse, UpdateMeProfileConfig, User, UserProfile} from '@thunderid/node'; +import type { + AttributeSchema, + AuthenticationChallenge, + FlowMetadataResponse, + UpdateMeProfileConfig, + User, + UserProfile, +} from '@thunderid/node'; import {FlowMetaProvider, FlowProvider, I18nProvider, ThemeProvider, UserProvider} from '@thunderid/vue'; import {defineComponent, h, type Component, type Ref, type SetupContext, type VNode} from 'vue'; import NuxtAPIRoutes from '../constants/NuxtAPIRoutes'; @@ -111,12 +118,22 @@ const ThunderIDRoot: Component = defineComponent({ const updateProfile = async ( requestConfig: UpdateMeProfileConfig, _sessionId?: string, - ): Promise<{data: {user: User}; error: string; success: boolean}> => { + ): Promise<{ + authenticationChallenge?: AuthenticationChallenge; + data: {user: User}; + error: string; + success: boolean; + }> => { if (_sessionId) { // no-op: session is resolved server-side } try { - const result: {data: {user: User}; error: string; success: boolean} = await $fetch(NuxtAPIRoutes.USER_PROFILE, { + const result: { + authenticationChallenge?: AuthenticationChallenge; + data: {user: User}; + error: string; + success: boolean; + } = await $fetch(NuxtAPIRoutes.USER_PROFILE, { body: requestConfig, method: 'PATCH', }); diff --git a/packages/nuxt/src/runtime/components/account/ChangeCredential.ts b/packages/nuxt/src/runtime/components/account/ChangeCredential.ts index 60ca6e68..6b1733b6 100644 --- a/packages/nuxt/src/runtime/components/account/ChangeCredential.ts +++ b/packages/nuxt/src/runtime/components/account/ChangeCredential.ts @@ -59,12 +59,18 @@ type ChangeCredentialProps = Readonly<{ * same reason `ThunderIDRoot.ts`'s `fetchMeta` proxies flow metadata: the browser never talks * to the ThunderID server directly, so no CORS configuration is required there. * + * The server needs the current value when the user holds the credential. A user who has not + * set it yet leaves the current value empty; that change needs a recent sign-in, and when the + * sign-in is too old the form asks the user to sign in again and emits + * `reauthentication-required` with the server's challenge. + * * Preserves the same prop/event API as the Vue SDK's `ChangeCredential` component so consumers * don't need to change their templates. * * @example * ```vue * + * * * ``` */ @@ -79,7 +85,7 @@ const ChangeCredential: Component = defineComponent({ showRequirements: {default: true, type: Boolean}, title: {default: undefined, type: String}, }, - emits: ['success'], + emits: ['reauthentication-required', 'success'], setup(props: ChangeCredentialProps, {emit}: SetupContext): () => VNode { const {userSchema} = useUser(); const {t} = useI18n(); @@ -97,7 +103,7 @@ const ChangeCredential: Component = defineComponent({ resolveChangeCredentialPolicy(userSchema?.value, props.attribute, props.policy), ); - async function handleSubmit({newPassword}: ChangePasswordValues): Promise { + async function handleSubmit({currentPassword, newPassword}: ChangePasswordValues): Promise { error.value = null; fieldErrors.value = {}; success.value = false; @@ -105,7 +111,7 @@ const ChangeCredential: Component = defineComponent({ try { const result: UpdateUserCredentialsResult = await $fetch(NuxtAPIRoutes.USER_CREDENTIALS, { - body: {payload: {[props.attribute]: newPassword}}, + body: {payload: {currentValue: currentPassword, name: props.attribute, newValue: newPassword}}, method: 'PATCH', }); @@ -125,6 +131,10 @@ const ChangeCredential: Component = defineComponent({ } else { error.value = text; } + + if (result.authenticationChallenge) { + emit('reauthentication-required', result.authenticationChallenge); + } } } catch (caughtError: unknown) { // The Nitro route itself failed to respond (network error, session expired outright), diff --git a/packages/nuxt/src/runtime/components/account/UserProfile.ts b/packages/nuxt/src/runtime/components/account/UserProfile.ts index 4a23d3b5..f9df412b 100644 --- a/packages/nuxt/src/runtime/components/account/UserProfile.ts +++ b/packages/nuxt/src/runtime/components/account/UserProfile.ts @@ -1,7 +1,12 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {AttributeVerificationConstants, deepMerge, withVendorCSSClassPrefix} from '@thunderid/browser'; +import { + type AuthenticationChallenge, + AttributeVerificationConstants, + deepMerge, + withVendorCSSClassPrefix, +} from '@thunderid/browser'; import {BaseUserProfile, type BaseUserProfileVerificationSlotProps, useI18n} from '@thunderid/vue'; import {type Component, type PropType, type Ref, type SetupContext, type VNode, defineComponent, h, ref} from 'vue'; import VerifyAttribute from './VerifyAttribute'; @@ -17,12 +22,17 @@ import {useUser} from '#imports'; * Preserves the same prop/slot API as the Vue SDK's `UserProfile` component * so consumers don't need to change their templates. * + * A change that needs a more recent sign-in, such as a new email address, asks the user to sign in + * again and emits `reauthentication-required` with the server's challenge: sign the user in again + * with `challenge.maxAge` as the `max_age` sign-in option, then let the user save again. + * * @example * ```vue - * + * * ``` */ const UserProfile: Component = defineComponent({ + emits: ['reauthentication-required'], name: 'UserProfile', props: { cardLayout: {default: true, type: Boolean}, @@ -44,7 +54,7 @@ const UserProfile: Component = defineComponent({ title: string; verificationFlowHandle: string; }>, - {slots}: SetupContext, + {emit, slots}: SetupContext, ): () => VNode { const {flattenedProfile, profile, updateProfile, userSchema} = useUser(); const {t} = useI18n(); @@ -74,11 +84,16 @@ const UserProfile: Component = defineComponent({ }); error.value = null; - const result: Awaited>> = await updateProfile({ + const result: Awaited>> & { + authenticationChallenge?: AuthenticationChallenge; + } = await updateProfile({ payload: updatedAttributes, } as any); - // `result.error` carries the route and server text, which is not meant for the user. - if (result && !result.success) { + if (result?.authenticationChallenge) { + error.value = t('user.reauthentication.required.error'); + emit('reauthentication-required', result.authenticationChallenge); + } else if (result && !result.success) { + // `result.error` carries the route and server text, which is not meant for the user. error.value = t('user.profile.update.generic.error'); } } diff --git a/packages/nuxt/src/runtime/plugins/thunderid.ts b/packages/nuxt/src/runtime/plugins/thunderid.ts index 376683f6..93a3cef3 100644 --- a/packages/nuxt/src/runtime/plugins/thunderid.ts +++ b/packages/nuxt/src/runtime/plugins/thunderid.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { @@ -6,6 +6,8 @@ import { getTokenPermissions, OrganizationUnitSwitchErrorCodes, ThunderIDAPIError, + ThunderIDRuntimeError, + pickRecentSignInParams, } from '@thunderid/browser'; import {VendorConstants} from '@thunderid/node'; import type { @@ -177,10 +179,13 @@ export default defineNuxtPlugin((nuxtApp: NuxtApp) => { // ── 3. Action helpers (Nuxt-aware navigation) ─────────────────────────── const signIn = async (options?: Record): Promise => { const returnTo: string | undefined = typeof options?.returnTo === 'string' ? options.returnTo : undefined; - const url: string = returnTo - ? `${NuxtAPIRoutes.SIGN_IN}?returnTo=${encodeURIComponent(returnTo)}` - : NuxtAPIRoutes.SIGN_IN; - await navigateTo(url, {external: true}); + // Of the sign-in options, only `max_age` and `prompt=login`, which ask for a recent sign-in, are sent. + const query: URLSearchParams = new URLSearchParams({ + ...(returnTo ? {returnTo} : {}), + ...pickRecentSignInParams(options), + }); + const search: string = query.toString(); + await navigateTo(search ? `${NuxtAPIRoutes.SIGN_IN}?${search}` : NuxtAPIRoutes.SIGN_IN, {external: true}); }; const currentOrganizationUnit: ComputedRef = computed( @@ -299,6 +304,16 @@ export default defineNuxtPlugin((nuxtApp: NuxtApp) => { getCurrentOrganizationUnit: (): Promise => Promise.resolve(currentOrganizationUnit.value), switchOrganizationUnit, + // The session lives on the server, so a change that needs a recent sign-in is answered by signing in + // again through the sign-in route, not by a popup. + reauthenticate: (): Promise => + Promise.reject( + new ThunderIDRuntimeError( + 'Signing in again in the page is not available in @thunderid/nuxt; sign in again with `max_age`.', + 'NUXT-REAUTHENTICATION-UM01', + 'nuxt', + ), + ), // Lets the management composables build the URLs the management route accepts. endpoints: publicConfig.endpoints, exchangeToken: noop, diff --git a/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts b/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts index b46adb40..949dea2c 100644 --- a/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts +++ b/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { @@ -13,6 +13,7 @@ import { isEmpty, resolveResourceEndpoint, updateMeCredentials, + type UpdateMeCredentialsPayload, updateMeProfile, type AccessibleOrganizationUnitList, type AccessibleOrganizationUnitsOptions, @@ -302,14 +303,14 @@ class ThunderIDNuxtClient extends ThunderIDNodeClient } /** - * Updates one or more of the signed-in user's credentials (e.g. `password`, or any other - * attribute the user type schema declares `credential: true`). + * Sets one of the signed-in user's credentials (e.g. `password`, or any other attribute the + * user type schema declares `credential: true`), with its current value when the user holds it. * * Deliberately does not catch and rewrap errors the way `updateUserProfile` does: the caller * (the `PATCH /api/auth/user/credentials` Nitro route) needs the real `ThunderIDAPIError` * instance, status code included, to map a failure onto the right form field. */ - override async updateUserCredentials(payload: Record, sessionId?: string): Promise { + override async updateUserCredentials(payload: UpdateMeCredentialsPayload, sessionId?: string): Promise { const configData: AuthClientConfig = await this.getStorageManager().getConfigData(); const baseUrl: string | undefined = configData?.baseUrl; diff --git a/packages/nuxt/src/runtime/server/routes/auth/session/signin.get.ts b/packages/nuxt/src/runtime/server/routes/auth/session/signin.get.ts index 3f02b255..f2554a6d 100644 --- a/packages/nuxt/src/runtime/server/routes/auth/session/signin.get.ts +++ b/packages/nuxt/src/runtime/server/routes/auth/session/signin.get.ts @@ -1,7 +1,7 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {generateSessionId} from '@thunderid/node'; +import {type RecentSignInParams, generateSessionId, pickRecentSignInParams} from '@thunderid/node'; import {defineEventHandler, getQuery, sendRedirect, setCookie, createError} from 'h3'; import type {H3Event} from 'h3'; import ThunderIDNuxtClient from '../../../ThunderIDNuxtClient'; @@ -19,6 +19,7 @@ import {useRuntimeConfig} from '#imports'; * the user to a specific page after sign-in, and an optional `ouId` that bounds the sign-in to that * organization unit (`{baseUrl}/ou/{ouId}/oauth2/authorize`). Switching organization units uses this: * the server reuses the SSO session, and the callback replaces the session only when it succeeds. + * `max_age` (whole seconds) and `prompt=login` ask for a recent sign-in, for a change that needs one. */ export default defineEventHandler(async (event: H3Event) => { const client: ThunderIDNuxtClient = ThunderIDNuxtClient.getInstance(); @@ -35,6 +36,9 @@ export default defineEventHandler(async (event: H3Event) => { const ouId: unknown = query.ouId; const organizationUnitId: string | undefined = typeof ouId === 'string' && ouId.trim() !== '' ? ouId : undefined; + // Only `max_age` and `prompt=login`, which ask for a recent sign-in, reach the authorization request. + const recentSignInParams: RecentSignInParams = pickRecentSignInParams(query); + const sessionId: string = generateSessionId(); // Create temp session JWT and set as cookie (includes returnTo if provided) @@ -51,7 +55,7 @@ export default defineEventHandler(async (event: H3Event) => { sessionId, undefined, // no authorization code (initial redirect) undefined, // no state - organizationUnitId ? {organizationUnitId} : {}, + {...recentSignInParams, ...(organizationUnitId ? {organizationUnitId} : {})}, ); if (!authorizationUrl) { diff --git a/packages/nuxt/src/runtime/server/routes/auth/session/signin.post.ts b/packages/nuxt/src/runtime/server/routes/auth/session/signin.post.ts index 3f7115d2..197b2457 100644 --- a/packages/nuxt/src/runtime/server/routes/auth/session/signin.post.ts +++ b/packages/nuxt/src/runtime/server/routes/auth/session/signin.post.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {EmbeddedSignInFlowStatus, generateSessionId, isEmpty} from '@thunderid/node'; -import type {IdToken, TokenResponse} from '@thunderid/node'; +import type {SessionData, TokenResponse} from '@thunderid/node'; import {defineEventHandler, readBody, getCookie, setCookie, deleteCookie, createError} from 'h3'; import type {H3Event} from 'h3'; import ThunderIDNuxtClient from '../../../ThunderIDNuxtClient'; @@ -106,9 +106,8 @@ export default defineEventHandler(async (event: H3Event) => { } // ── Flow complete — establish the session from the flow's JWT assertion ──── - // A completed embedded flow returns a self-contained JWT `assertion` rather than an - // authorization code to exchange (mirrors how @thunderid/react and @thunderid/vue treat it: - // the assertion is used directly as the bearer session token). + // A completed embedded flow returns a JWT `assertion` rather than an authorization code. It is + // exchanged for the session's access token and kept as the ID token. if ((response as {flowStatus?: unknown})?.flowStatus === EmbeddedSignInFlowStatus.Complete) { const assertion: string | undefined = (response as {assertion?: string})?.assertion; @@ -117,19 +116,16 @@ export default defineEventHandler(async (event: H3Event) => { } try { - const idToken: IdToken = await client.getDecodedIdToken(sessionId, assertion); - const iat: number = typeof idToken.iat === 'number' ? idToken.iat : Math.floor(Date.now() / 1000); - const exp: number = typeof idToken.exp === 'number' ? idToken.exp : iat + 3600; - const scope: string = typeof idToken.scope === 'string' ? idToken.scope : ''; + const tokens: SessionData = await client.exchangeFlowAssertion(assertion); const tokenResponse: TokenResponse = { - accessToken: assertion, - createdAt: iat, - expiresIn: String(Math.max(exp - iat, 0)), + accessToken: tokens.access_token, + createdAt: tokens.created_at, + expiresIn: tokens.expires_in, idToken: assertion, refreshToken: '', - scope, - tokenType: 'Bearer', + scope: tokens.scope, + tokenType: tokens.token_type, } as TokenResponse; await issueSessionCookie(event, sessionId, tokenResponse, sessionSecret); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/credentials.patch.ts b/packages/nuxt/src/runtime/server/routes/auth/user/credentials.patch.ts index 3f7bcdca..89d9f178 100644 --- a/packages/nuxt/src/runtime/server/routes/auth/user/credentials.patch.ts +++ b/packages/nuxt/src/runtime/server/routes/auth/user/credentials.patch.ts @@ -1,7 +1,7 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import type {CredentialUpdateErrorResult} from '@thunderid/node'; +import type {CredentialUpdateErrorResult, UpdateMeCredentialsPayload} from '@thunderid/node'; import {mapCredentialUpdateError} from '@thunderid/node'; import {defineEventHandler, readBody, createError} from 'h3'; import type {H3Event} from 'h3'; @@ -14,7 +14,7 @@ export interface UpdateUserCredentialsResult extends CredentialUpdateErrorResult } interface UpdateUserCredentialsBody { - payload: Record; + payload: UpdateMeCredentialsPayload; } /** @@ -23,10 +23,12 @@ interface UpdateUserCredentialsBody { * Updates one of the signed-in user's own credentials (e.g. `password`). Mirrors the * `updateUserCredentialsAction` Next.js server action. * - * Request body: `{ payload: Record }` — `payload` is keyed by credential attribute - * (e.g. `{ password: "n3wP@ssword!" }`), the same shape `updateMeCredentials`'s own `payload` takes. + * Request body: `{ payload: { name, currentValue?, newValue } }` (e.g. + * `{ payload: { name: "password", currentValue: "0ldP@ssword!", newValue: "n3wP@ssword!" } }`), the + * same shape `updateMeCredentials`'s own `payload` takes. * - * Response: `{ success: boolean; field: 'newPassword' | null; message?: string; messageKey: string }`. + * Response: `{ success: boolean; field: 'currentPassword' | 'newPassword' | null; message?: string; + * messageKey: string; authenticationChallenge?: { error, errorDescription?, maxAge? } }`. * Always resolves 200, even on a failed credential write — the failure is carried in the body * (`success: false` plus `field`/`message`/`messageKey`, from {@link mapCredentialUpdateError}) * rather than the HTTP status, so ``'s client component can attach the @@ -58,7 +60,6 @@ export default defineEventHandler(async (event: H3Event): Promise => { + async ( + event: H3Event, + ): Promise<{ + authenticationChallenge?: AuthenticationChallenge; + data: {user: User}; + error: string; + success: boolean; + }> => { const config: ReturnType = useRuntimeConfig(); const sessionSecret: string | undefined = config.thunderid?.sessionSecret; const publicConfig: ThunderIDNuxtConfig = config.public.thunderid as ThunderIDNuxtConfig; @@ -44,6 +54,10 @@ export default defineEventHandler( const user: User = await client.updateUserProfile(payload, session.sessionId); return {data: {user}, error: '', success: true}; } catch (err) { + if (err instanceof ThunderIDAPIError && err.authenticationChallenge?.error === INSUFFICIENT_USER_AUTHENTICATION) { + return {authenticationChallenge: {...err.authenticationChallenge}, data: {user: {}}, error: '', success: false}; + } + throw createError({ statusCode: 500, statusMessage: `Failed to update user profile: ${err instanceof Error ? err.message : String(err)}`, diff --git a/packages/nuxt/src/runtime/server/utils/session.ts b/packages/nuxt/src/runtime/server/utils/session.ts index 5ad89f6c..2d3c4919 100644 --- a/packages/nuxt/src/runtime/server/utils/session.ts +++ b/packages/nuxt/src/runtime/server/utils/session.ts @@ -195,7 +195,10 @@ export async function issueSessionCookie( const {default: ThunderIDNuxtClient} = await import('../ThunderIDNuxtClient'); const client: ReturnType = ThunderIDNuxtClient.getInstance(); - const idToken: IdToken = await client.getDecodedIdToken(sessionId, tokenResponse.idToken); + // The issued ID token, not one stored for this session ID by an earlier sign-in. + const idToken: IdToken = tokenResponse.idToken + ? await client.decodeJwtToken(tokenResponse.idToken) + : await client.getDecodedIdToken(sessionId); const userId: string = idToken.sub || sessionId; const organizationId: string | undefined = (idToken.user_org || idToken.organization_id) as string | undefined; diff --git a/packages/nuxt/tests/unit/profile-patch.test.ts b/packages/nuxt/tests/unit/profile-patch.test.ts new file mode 100644 index 00000000..6aa08056 --- /dev/null +++ b/packages/nuxt/tests/unit/profile-patch.test.ts @@ -0,0 +1,75 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable @typescript-eslint/typedef, sort-keys, @typescript-eslint/explicit-function-return-type */ + +import {ThunderIDAPIError} from '@thunderid/node'; +import {readBody} from 'h3'; +import {describe, it, expect, vi, beforeEach} from 'vitest'; + +import profilePatchHandler from '../../src/runtime/server/routes/auth/user/profile.patch'; +import {verifyAndRehydrateSession} from '../../src/runtime/server/utils/serverSession'; + +const mockClientInstance = vi.hoisted(() => ({ + updateUserProfile: vi.fn<(...args: any[]) => Promise>(), +})); + +vi.mock('h3', () => ({ + defineEventHandler: (fn: Function) => fn, + readBody: vi.fn(), + createError: vi.fn((opts: any) => Object.assign(new Error(opts.statusMessage), opts)), +})); + +vi.mock('#imports', () => ({ + useRuntimeConfig: vi.fn(() => ({public: {thunderid: {}}, thunderid: {sessionSecret: 'test-secret'}})), +})); + +vi.mock('../../src/runtime/server/ThunderIDNuxtClient', () => ({ + default: {getInstance: () => mockClientInstance}, +})); + +vi.mock('../../src/runtime/server/utils/serverSession', () => ({ + verifyAndRehydrateSession: vi.fn(), +})); + +const body = {payload: {email: 'a@example.com'}}; + +describe('PATCH /api/auth/user/profile', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(verifyAndRehydrateSession).mockResolvedValue({sessionId: 'session-1'} as any); + vi.mocked(readBody).mockResolvedValue(body); + }); + + it('returns the updated user', async () => { + mockClientInstance.updateUserProfile.mockResolvedValue({id: 'u-1'}); + + expect(await (profilePatchHandler as any)({})).toEqual({data: {user: {id: 'u-1'}}, error: '', success: true}); + expect(mockClientInstance.updateUserProfile).toHaveBeenCalledWith(body, 'session-1'); + }); + + it('returns the challenge when the change needs a more recent sign-in', async () => { + mockClientInstance.updateUserProfile.mockRejectedValue( + new ThunderIDAPIError( + JSON.stringify({code: 'AUTH-4011'}), + 'updateMeProfile-ResponseError-001', + 'javascript', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="180"', + ), + ); + + expect(await (profilePatchHandler as any)({})).toMatchObject({ + authenticationChallenge: {error: 'insufficient_user_authentication', maxAge: 180}, + success: false, + }); + }); + + it('fails with 500 for any other error', async () => { + mockClientInstance.updateUserProfile.mockRejectedValue(new Error('offline')); + + await expect((profilePatchHandler as any)({})).rejects.toMatchObject({statusCode: 500}); + }); +}); diff --git a/packages/nuxt/tests/unit/session-manager.test.ts b/packages/nuxt/tests/unit/session-manager.test.ts index ed95ac39..7ab7cb51 100644 --- a/packages/nuxt/tests/unit/session-manager.test.ts +++ b/packages/nuxt/tests/unit/session-manager.test.ts @@ -3,14 +3,24 @@ /* eslint-disable @typescript-eslint/typedef, sort-keys */ -import {describe, it, expect} from 'vitest'; +import {describe, it, expect, vi} from 'vitest'; +import {setChunkedCookie} from '../../src/runtime/server/utils/chunkedCookie'; import { createSessionToken, + issueSessionCookie, verifySessionToken, createTempSessionToken, verifyTempSessionToken, } from '../../src/runtime/server/utils/session'; +const mockClient = vi.hoisted(() => ({ + decodeJwtToken: vi.fn(), + getDecodedIdToken: vi.fn(), +})); + +vi.mock('../../src/runtime/server/ThunderIDNuxtClient', () => ({default: {getInstance: () => mockClient}})); +vi.mock('../../src/runtime/server/utils/chunkedCookie', () => ({setChunkedCookie: vi.fn()})); + const TEST_SECRET = 'test-secret-at-least-32-characters-long!!'; describe('createSessionToken / verifySessionToken', () => { @@ -258,3 +268,24 @@ describe('createSessionToken — Phase 2 fields (accessTokenExpiresAt / refreshT expect(payload.idToken).toBeUndefined(); }); }); + +describe('issueSessionCookie', () => { + it('takes the identity from the issued ID token, not one stored for the session ID', async () => { + mockClient.decodeJwtToken.mockResolvedValue({sid: 'new-sid', sub: 'new-user'}); + mockClient.getDecodedIdToken.mockResolvedValue({sid: 'old-sid', sub: 'old-user'}); + + await issueSessionCookie( + {} as any, + 'session-1', + {accessToken: 'at', expiresIn: '900', idToken: 'new-id-token', scope: ''} as any, + TEST_SECRET, + ); + + const token: string = vi.mocked(setChunkedCookie).mock.calls[0][2]; + const payload = await verifySessionToken(token, TEST_SECRET); + + expect(mockClient.decodeJwtToken).toHaveBeenCalledWith('new-id-token'); + expect(mockClient.getDecodedIdToken).not.toHaveBeenCalled(); + expect(payload).toMatchObject({sid: 'new-sid', sub: 'new-user'}); + }); +}); diff --git a/packages/nuxt/tests/unit/signin-get-organization-unit.test.ts b/packages/nuxt/tests/unit/signin-get-organization-unit.test.ts index 9dd4660f..319a11e4 100644 --- a/packages/nuxt/tests/unit/signin-get-organization-unit.test.ts +++ b/packages/nuxt/tests/unit/signin-get-organization-unit.test.ts @@ -12,7 +12,10 @@ const mockClientInstance = vi.hoisted(() => ({ signIn: vi.fn<(...args: any[]) => Promise>(), })); -vi.mock('@thunderid/node', () => ({generateSessionId: () => 'session-new'})); +vi.mock('@thunderid/node', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + generateSessionId: () => 'session-new', +})); vi.mock('h3', () => ({ createError: vi.fn((opts: any) => Object.assign(new Error(opts.statusMessage), opts)), @@ -68,4 +71,20 @@ describe('GET /api/auth/signin organization unit', () => { {}, ); }); + + it('passes on only max_age and prompt=login to ask for a recent sign-in', async () => { + vi.mocked(getQuery).mockReturnValue({ + max_age: '180', + prompt: 'login', + redirect_uri: 'https://other.example', + scope: 'x', + }); + + await (signInHandler as any)({}); + + expect(mockClientInstance.signIn).toHaveBeenCalledWith(expect.any(Function), 'session-new', undefined, undefined, { + max_age: '180', + prompt: 'login', + }); + }); }); diff --git a/packages/nuxt/tests/unit/signin-post.test.ts b/packages/nuxt/tests/unit/signin-post.test.ts index aa6052e7..721edbfa 100644 --- a/packages/nuxt/tests/unit/signin-post.test.ts +++ b/packages/nuxt/tests/unit/signin-post.test.ts @@ -28,6 +28,14 @@ const mockClientInstance = vi.hoisted(() => ({ .fn<() => Promise>() .mockResolvedValue('https://localhost:8090/oauth2/authorize?code_challenge=x'), signIn: vi.fn<() => Promise>().mockResolvedValue(undefined), + exchangeFlowAssertion: vi.fn<() => Promise>().mockResolvedValue({ + access_token: 'exchanged-at', + created_at: 1000, + expires_in: '900', + id_token: 'assertion-jwt-xyz', + scope: 'self', + token_type: 'Bearer', + }), getDecodedIdToken: vi.fn<() => Promise>().mockResolvedValue({iat: 1000, exp: 4600, scope: 'openid profile'}), })); @@ -167,7 +175,7 @@ describe('POST /api/auth/signin', () => { }); describe('embedded flow completion (SUCCESS_COMPLETED)', () => { - it('establishes the session from the assertion and issues a session cookie on flow completion', async () => { + it('exchanges the assertion and issues a session cookie on flow completion', async () => { const flowPayload = { flowId: 'flow-abc', selectedAuthenticator: {authenticatorId: 'BasicAuthenticator'}, @@ -187,11 +195,16 @@ describe('POST /api/auth/signin', () => { const result = await (signinHandler as any)(mockEvent); - expect(mockClientInstance.getDecodedIdToken).toHaveBeenCalledWith(expect.any(String), 'assertion-jwt-xyz'); + expect(mockClientInstance.exchangeFlowAssertion).toHaveBeenCalledWith('assertion-jwt-xyz'); expect(issueSessionCookie).toHaveBeenCalledWith( mockEvent, expect.any(String), - expect.objectContaining({accessToken: 'assertion-jwt-xyz', idToken: 'assertion-jwt-xyz'}), + expect.objectContaining({ + accessToken: 'exchanged-at', + expiresIn: '900', + idToken: 'assertion-jwt-xyz', + scope: 'self', + }), expect.any(String), ); expect(deleteCookie).toHaveBeenCalled(); @@ -209,5 +222,14 @@ describe('POST /api/auth/signin', () => { statusCode: 502, }); }); + + it('issues no session cookie when the assertion cannot be exchanged', async () => { + mockClientInstance.signIn.mockResolvedValueOnce({assertion: 'assertion-jwt-xyz', flowStatus: 'COMPLETE'}); + mockClientInstance.exchangeFlowAssertion.mockRejectedValueOnce(new Error('needs the token exchange grant')); + vi.mocked(readBody).mockResolvedValue({payload: {flowId: 'flow-abc'}}); + + await expect((signinHandler as any)(mockEvent)).rejects.toMatchObject({statusCode: 500}); + expect(issueSessionCookie).not.toHaveBeenCalled(); + }); }); }); diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index 6c6e33cd..7a70a19d 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -2,11 +2,15 @@ No changes to this SDK since sdk/react-router/v1.23.0. -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/react-router/v1.23.0...sdk/react-router/v1.23.1 +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/react-router/v1.23.0...sdk/react-router/v1.23.1 ## 1.23.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/react-router/v1.22.0...sdk/react-router/v1.23.0 +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 + +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/react-router/v1.22.0...sdk/react-router/v1.23.0 diff --git a/packages/react/CHANGELOG.md b/packages/react/CHANGELOG.md index e5cdc3f5..5a26daf9 100644 --- a/packages/react/CHANGELOG.md +++ b/packages/react/CHANGELOG.md @@ -1,13 +1,17 @@ ## 1.28.1 ### 🐛 Bug Fixes -* Report a failed passkey prompt to the flow by @KaveeshaPiumini in https://github.com/thunder-id/javascript-sdks/pull/189 + +- Report a failed passkey prompt to the flow by @KaveeshaPiumini in + https://github.com/thunder-id/javascript-sdks/pull/189 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/react/v1.28.0...sdk/react/v1.28.1 ## 1.28.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 + +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/react/v1.27.0...sdk/react/v1.28.0 diff --git a/packages/react/src/ThunderIDReactClient.ts b/packages/react/src/ThunderIDReactClient.ts index 036d038b..93f03488 100644 --- a/packages/react/src/ThunderIDReactClient.ts +++ b/packages/react/src/ThunderIDReactClient.ts @@ -195,32 +195,16 @@ class ThunderIDReactClient(response.assertion); - - const createdAt: number = decodedAssertion.iat ? decodedAssertion.iat * 1000 : Date.now(); - const expiresIn: number = - decodedAssertion.exp && decodedAssertion.iat ? decodedAssertion.exp - decodedAssertion.iat : 3600; - - await this.setSession({ - access_token: response.assertion, - created_at: createdAt, - expires_in: expiresIn, - id_token: response.assertion, - scope: decodedAssertion.scope, - token_type: 'Bearer', + const claims: Record = await this.setSessionFromFlowAssertion({ + ...response, + assertion: response.assertion, + }).catch((error: unknown) => { + this.notifySignInFailed((error as {code?: unknown})?.code); + + throw error; }); - this.notifySignIn(extractUserClaimsFromIdToken(decodedAssertion as IdToken) as User); + this.notifySignIn(extractUserClaimsFromIdToken(claims as IdToken) as User); } return response; @@ -266,32 +250,9 @@ class ThunderIDReactClient(response.assertion); - - const createdAt: number = decodedAssertion.iat ? decodedAssertion.iat * 1000 : Date.now(); - const expiresIn: number = - decodedAssertion.exp && decodedAssertion.iat ? decodedAssertion.exp - decodedAssertion.iat : 3600; - - await this.setSession({ - access_token: response.assertion, - created_at: createdAt, - expires_in: expiresIn, - id_token: response.assertion, - scope: decodedAssertion.scope, - token_type: 'Bearer', - }); - - this.notifySignIn(extractUserClaimsFromIdToken(decodedAssertion as IdToken) as User); + const claims: Record = await this.setSessionFromFlowAssertion(response); + + this.notifySignIn(extractUserClaimsFromIdToken(claims as IdToken) as User); } return response; diff --git a/packages/react/src/__tests__/ThunderIDReactClient.flowSessions.test.ts b/packages/react/src/__tests__/ThunderIDReactClient.flowSessions.test.ts index 341d2157..8183db50 100644 --- a/packages/react/src/__tests__/ThunderIDReactClient.flowSessions.test.ts +++ b/packages/react/src/__tests__/ThunderIDReactClient.flowSessions.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return */ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, type Mock, vi} from 'vitest'; import ThunderIDReactClient from '../ThunderIDReactClient'; const CONFIG = {applicationId: 'app-1', baseUrl: 'https://localhost:8090', clientId: 'flow-sessions-client'}; @@ -92,3 +92,82 @@ describe('ThunderIDReactClient embedded SSO session handles', () => { expect(await keptSessions(client)).toEqual([]); }); }); + +describe('ThunderIDReactClient embedded session', () => { + const encode = (claims: Record): string => + `h.${btoa(JSON.stringify(claims)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_')}.s`; + const assertion: string = encode({ + exp: Math.floor(Date.now() / 1000) + 600, + iat: Math.floor(Date.now() / 1000), + sub: 'u1', + }); + + /** Answers discovery, the flow step and the token request. */ + const serverAnswering = (flowBody: unknown, tokenBody: unknown, tokenStatus = 200): Mock => + vi.fn((url: string) => { + if (url.includes('/.well-known/')) { + return Promise.resolve( + flowResponse({issuer: 'https://localhost:8090', token_endpoint: 'https://localhost:8090/oauth2/token'}), + ); + } + + if (url.endsWith('/oauth2/token')) { + return Promise.resolve( + new Response(JSON.stringify(tokenBody), {headers: {'Content-Type': 'application/json'}, status: tokenStatus}), + ); + } + + return Promise.resolve(flowResponse(flowBody)); + }); + + let client: ThunderIDReactClient; + + beforeEach(async () => { + sessionStorage.clear(); + client = new ThunderIDReactClient(); + await client.initialize(CONFIG as any); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + sessionStorage.clear(); + }); + + it.each([ + ['sign-in', (c: ThunderIDReactClient): Promise => c.signIn({executionId: 'e1', inputs: {}} as any)], + ['sign-up', (c: ThunderIDReactClient): Promise => c.signUp({executionId: 'e1', inputs: {}} as any)], + ])('keeps the access token a completed %s exchanges its assertion for', async (_name: string, run: any) => { + const fetchMock = serverAnswering({assertion, flowStatus: 'COMPLETE'}, {access_token: 'at', expires_in: 900}); + vi.stubGlobal('fetch', fetchMock); + // The test browser has no Buffer for the default JWT decoder. + vi.spyOn(client, 'decodeJwtToken').mockResolvedValue({sub: 'u1'} as any); + + await run(client); + + const tokenCall: any[] = fetchMock.mock.calls.find(([url]: any[]) => String(url).endsWith('/oauth2/token'))!; + expect(tokenCall[1].body.get('subject_token')).toBe(assertion); + expect(await client.getAccessToken()).toBe('at'); + expect((await client.getStorageManager().getSessionData()).id_token).toBe(assertion); + }); + + it('fails a completed sign-in and keeps no session when the application lacks the grant', async () => { + vi.stubGlobal( + 'fetch', + serverAnswering( + {assertion, flowStatus: 'COMPLETE', sessionData: [{flowIdentifier: 'f1', sessionHandle: 'h1'}]}, + {error: 'unauthorized_client'}, + 400, + ), + ); + const notifySignInFailed = vi.spyOn(client as any, 'notifySignInFailed'); + + await expect(client.signIn({executionId: 'e1', inputs: {}} as any)).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-EFA-UC04', + }); + expect((await client.getStorageManager().getSessionData())?.access_token).toBeUndefined(); + // A retry shows the flow again instead of completing at once with the same handle. + expect(await keptSessions(client)).toEqual([]); + expect(notifySignInFailed).toHaveBeenCalledWith('JS-AUTH_CORE-EFA-UC04'); + }); +}); diff --git a/packages/react/src/api/account/__tests__/updateMeProfile.test.ts b/packages/react/src/api/account/__tests__/updateMeProfile.test.ts new file mode 100644 index 00000000..92bcc395 --- /dev/null +++ b/packages/react/src/api/account/__tests__/updateMeProfile.test.ts @@ -0,0 +1,58 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {StepUpRequiredError} from '@thunderid/browser'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import updateMeProfile from '../updateMeProfile'; + +// The httpClient-to-Response adapter is covered in @thunderid/browser's createHttpClientFetcher tests. +// This checks that the wrapper uses it, so a refused write reaches the core function's error mapping. +const mockFetcher = vi.fn(); + +vi.mock('@thunderid/browser', async () => { + const actual = await vi.importActual('@thunderid/browser'); + return { + ...actual, + createHttpClientFetcher: () => mockFetcher, + }; +}); + +describe('updateMeProfile (react)', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('turns a step-up challenge into a StepUpRequiredError with its maxAge', async () => { + mockFetcher.mockResolvedValueOnce({ + headers: new Headers({ + 'WWW-Authenticate': 'Bearer error="insufficient_user_authentication", max_age="180"', + }), + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => + Promise.resolve(JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}})), + } as Response); + + const error: unknown = await updateMeProfile({ + payload: {email: 'new@example.com'}, + url: 'https://localhost:8090/users/me', + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StepUpRequiredError); + expect((error as StepUpRequiredError).maxAge).toBe(180); + }); + + it('resolves with the updated profile', async () => { + mockFetcher.mockResolvedValueOnce({ + json: () => Promise.resolve({email: 'new@example.com', id: 'user-1'}), + ok: true, + status: 200, + statusText: 'OK', + } as Response); + + await expect( + updateMeProfile({payload: {email: 'new@example.com'}, url: 'https://localhost:8090/users/me'}), + ).resolves.toMatchObject({id: 'user-1'}); + }); +}); diff --git a/packages/react/src/api/account/updateMeProfile.ts b/packages/react/src/api/account/updateMeProfile.ts index e76bb1a5..030e2d48 100644 --- a/packages/react/src/api/account/updateMeProfile.ts +++ b/packages/react/src/api/account/updateMeProfile.ts @@ -1,11 +1,9 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { User, - HttpResponse, - FetchHttpClient, - HttpRequestConfig, + createHttpClientFetcher, updateMeProfile as baseUpdateMeProfile, UpdateMeProfileConfig as BaseUpdateMeProfileConfig, } from '@thunderid/browser'; @@ -51,27 +49,10 @@ export interface UpdateMeProfileConfig extends Omit => { - const defaultFetcher = async (url: string, config: RequestInit): Promise => { - const httpClient: FetchHttpClient = FetchHttpClient.getInstance(instanceId); - const response: HttpResponse = await httpClient.request({ - data: config.body ? JSON.parse(config.body as string) : undefined, - headers: config.headers as Record, - method: config.method || 'PUT', - url, - } as HttpRequestConfig); - - return { - json: () => Promise.resolve(response.data), - ok: response.status >= 200 && response.status < 300, - status: response.status, - statusText: response.statusText || '', - text: () => Promise.resolve(typeof response.data === 'string' ? response.data : JSON.stringify(response.data)), - } as Response; - }; - return baseUpdateMeProfile({ ...requestConfig, - fetcher: fetcher || defaultFetcher, + // Keeps a refused response, so the server's error, such as a step-up challenge, reaches the caller. + fetcher: fetcher ?? createHttpClientFetcher(instanceId), }); }; diff --git a/packages/react/src/components/account/ChangeCredential/BaseChangeCredential.tsx b/packages/react/src/components/account/ChangeCredential/BaseChangeCredential.tsx index 797aaa7d..4a010892 100644 --- a/packages/react/src/components/account/ChangeCredential/BaseChangeCredential.tsx +++ b/packages/react/src/components/account/ChangeCredential/BaseChangeCredential.tsx @@ -24,12 +24,13 @@ import Typography from '../../primitives/Typography/Typography'; /** * The values collected by the form and handed to `onSubmit`. - * - * There is deliberately no current-value field here. The self-service credential write - * endpoint does not verify the account's existing value today, so a field the server - * ignores would only teach the user a false sense of security. */ export interface ChangePasswordValues { + /** + * The credential's current value, present only when the user filled it in. The server + * needs it when the user holds the credential, and not when the user sets a first one. + */ + currentPassword?: string; /** * The value to set. */ @@ -58,7 +59,7 @@ export interface BaseChangeCredentialProps { */ error?: string | null; /** - * Server-supplied errors keyed by field name (`newPassword`). + * Server-supplied errors keyed by field name (`currentPassword` or `newPassword`). */ fieldErrors?: Record; /** @@ -104,8 +105,9 @@ export interface BaseChangeCredentialProps { } /** - * Presentational change-credential form with just the two fields a first-time or - * unverified credential change needs: new value and confirmation. + * Presentational change-credential form: the current value, the new value and its + * confirmation. The current value is optional, so a user who has not set the credential + * yet can set a first one. * * Holds no context and performs no network calls: it renders the fields, evaluates the * policy for the checklist and the submit gate, and hands validated values to `onSubmit`. @@ -148,6 +150,7 @@ const BaseChangeCredential: FC = ({ // `title` overrides the default heading; an explicit empty string omits it entirely. const resolvedTitle: string = title ?? t('user.change_password.heading', labelParams); + const [currentPassword, setCurrentPassword] = useState(''); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [submitted, setSubmitted] = useState(false); @@ -162,6 +165,7 @@ const BaseChangeCredential: FC = ({ setPrevSuccess(success); if (success) { + setCurrentPassword(''); setNewPassword(''); setConfirmPassword(''); setSubmitted(false); @@ -186,7 +190,7 @@ const BaseChangeCredential: FC = ({ return; } - onSubmit?.({newPassword}); + onSubmit?.(currentPassword ? {currentPassword, newPassword} : {newPassword}); }; const renderRequirement = (rule: PasswordRuleResult): ReactElement => ( @@ -217,6 +221,7 @@ const BaseChangeCredential: FC = ({ // not flag fields the user has not finished filling in. const confirmError: string | undefined = submitted && !confirmMatches ? t('user.change_password.mismatch.error', labelParams) : undefined; + const currentPasswordError: string | undefined = fieldErrors['currentPassword']; const newPasswordError: string | undefined = fieldErrors['newPassword']; const form: ReactElement = ( @@ -259,6 +264,18 @@ const BaseChangeCredential: FC = ({ )}
+ + ` for a PIN. */ attribute?: string; + /** + * Called when setting the credential needs a more recent sign-in (`AUTH-4011`), with the + * server's challenge, instead of the component signing the user in again by itself. Sign the + * user in again with `challenge.maxAge` as the `max_age` authorization parameter, then let the + * user submit again. The form also shows a "sign in again" message. + */ + onReauthenticationRequired?: (challenge: AuthenticationChallenge) => void; /** * Called after the credential has been changed successfully. */ @@ -45,10 +55,15 @@ export interface ChangeCredentialProps /** * ChangeCredential lets the signed-in user set a new value for one of their own credentials. * - * It collects only a new value and its confirmation. The self-service credential write path - * does not verify the account's existing value today, so this component does not ask for one; - * once server-side current-value verification ships, that field returns without a breaking - * change to this component's public props. + * It collects the current value, the new value and its confirmation. The server needs the + * current value when the user holds the credential, and answers a wrong or missing one on the + * current-value field. A user who has not set the credential yet leaves the current value + * empty; that change needs a recent sign-in. When the sign-in is too old, the component signs + * the user in again with the server's `max_age`, checks that the same user signed in, and sends + * the change once more; the values stay in memory only. A session from a redirect sign-in signs in + * again in a popup, and one from an embedded sign-in flow runs the sign-in flow in a dialog. If the + * browser blocks the popup, the next submit opens it first. Set `onReauthenticationRequired` to handle the challenge in your + * app instead. Changing a credential the user holds ends the user's sessions, including this one. * * It reads the applicable rules from the user schema already resolved by the ThunderID * provider, so it adds no network request beyond the write itself, and posts to @@ -68,6 +83,9 @@ export interface ChangeCredentialProps * // Basic usage, manages the password * toast('Password updated')} /> * + * // A first PIN: the component signs the user in again by itself when the sign-in is too old + * + * * // With an explicit rule instead of the schema-derived policy * = ({ attribute = CredentialConstants.PASSWORD, + onReauthenticationRequired = undefined, onSuccess = undefined, policy = undefined, preferences = undefined, ...rest }: ChangeCredentialProps) => { - const {baseUrl, endpoints, instanceId, preferences: contextPreferences} = useThunderID(); + const {baseUrl, endpoints, instanceId, preferences: contextPreferences, reauthenticate} = useThunderID(); + const pendingStepUp: PendingStepUp = useRef(undefined); + // Whether the component is still on screen, so a change is not sent after it has closed. + const mountedRef = useRef(true); + + useEffect(() => { + mountedRef.current = true; + + return (): void => { + mountedRef.current = false; + }; + }, []); const {userSchema} = useUser(); const resolvedDisplayName: string = userSchema?.[attribute]?.displayName ?? defaultDisplayName(attribute); @@ -109,18 +139,25 @@ const ChangeCredential: FC = ({ [userSchema, attribute, policy], ); - const handleSubmit = async ({newPassword}: ChangePasswordValues): Promise => { + const handleSubmit = async ({currentPassword, newPassword}: ChangePasswordValues): Promise => { setError(null); setFieldErrors({}); setSuccess(false); setLoading(true); try { - await updateMeCredentials({ - baseUrl, - instanceId, - payload: {[attribute]: newPassword}, - url: resolveResourceEndpoint('usersMeCredentials', {endpoints}), + await runWithStepUp({ + onReauthenticationRequired, + isActive: (): boolean => mountedRef.current, + pending: pendingStepUp, + reauthenticate, + send: () => + updateMeCredentials({ + baseUrl, + instanceId, + payload: {currentValue: currentPassword, name: attribute, newValue: newPassword}, + url: resolveResourceEndpoint('usersMeCredentials', {endpoints}), + }), }); setSuccess(true); diff --git a/packages/react/src/components/account/ChangeCredential/__tests__/ChangeCredential.test.tsx b/packages/react/src/components/account/ChangeCredential/__tests__/ChangeCredential.test.tsx index b3bc6a1a..41f178e4 100644 --- a/packages/react/src/components/account/ChangeCredential/__tests__/ChangeCredential.test.tsx +++ b/packages/react/src/components/account/ChangeCredential/__tests__/ChangeCredential.test.tsx @@ -10,6 +10,7 @@ import UserContext, {UserContextProps} from '../../../../contexts/User/UserConte import ChangeCredential from '../ChangeCredential'; const mockUpdateMeCredentials = vi.fn() as Mock; +const mockReauthenticate = vi.fn() as Mock; vi.mock('../../../../api/account/updateMeCredentials', () => ({ default: (...args: unknown[]): unknown => mockUpdateMeCredentials(...args) as unknown, @@ -20,6 +21,7 @@ const thunderIDContext: ThunderIDContextProps = { instanceId: 0, isInitialized: true, isLoading: false, + reauthenticate: (...args: unknown[]): unknown => mockReauthenticate(...args) as unknown, vendor: 'thunderid', } as unknown as ThunderIDContextProps; @@ -70,17 +72,20 @@ describe('ChangeCredential', () => { cleanup(); }); - it('renders only the two fields, with no current-value field', () => { + it('renders an optional current-value field above the new value and its confirmation', () => { renderChangeCredential(); + expect(fieldByName('currentPassword')).toBeTruthy(); + expect(fieldByName('currentPassword').required).toBe(false); expect(fieldByName('newPassword')).toBeTruthy(); expect(fieldByName('confirmPassword')).toBeTruthy(); - expect(document.querySelector('input[name="currentPassword"]')).toBeNull(); + expect(screen.getByText(/leave this empty if you have not set one yet/i)).toBeTruthy(); }); - it('marks both fields as new-password for password managers', () => { + it('marks the current field as current-password and the new fields as new-password', () => { renderChangeCredential(); + expect(fieldByName('currentPassword').getAttribute('autocomplete')).toBe('current-password'); expect(fieldByName('newPassword').getAttribute('autocomplete')).toBe('new-password'); expect(fieldByName('confirmPassword').getAttribute('autocomplete')).toBe('new-password'); }); @@ -124,7 +129,7 @@ describe('ChangeCredential', () => { expect(mockUpdateMeCredentials).not.toHaveBeenCalled(); }); - it('sends only the new value, keyed by password by default', async () => { + it('sends the name and new value without a current value when it is left empty', async () => { mockUpdateMeCredentials.mockResolvedValueOnce(undefined); renderChangeCredential({policy: {regex: '^.{8,}$'}}); @@ -137,15 +142,16 @@ describe('ChangeCredential', () => { expect(mockUpdateMeCredentials).toHaveBeenCalledWith( expect.objectContaining({ baseUrl: 'https://localhost:8090', - payload: {password: 'n3wP@ssword'}, + payload: {currentValue: undefined, name: 'password', newValue: 'n3wP@ssword'}, }), ); }); - it('keys the payload by attribute when set to something other than password', async () => { + it('sends the current value and names the attribute when set to something other than password', async () => { mockUpdateMeCredentials.mockResolvedValueOnce(undefined); renderChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + setField('currentPassword', '0000'); setField('newPassword', '1234'); setField('confirmPassword', '1234'); fireEvent.click(submitButton()); @@ -154,7 +160,7 @@ describe('ChangeCredential', () => { expect(mockUpdateMeCredentials).toHaveBeenCalledWith( expect.objectContaining({ - payload: {pin: '1234'}, + payload: {currentValue: '0000', name: 'pin', newValue: '1234'}, }), ); }); @@ -182,6 +188,7 @@ describe('ChangeCredential', () => { await waitFor(() => expect(fieldByName('newPassword').value).toBe('')); + expect(fieldByName('currentPassword').value).toBe(''); expect(fieldByName('confirmPassword').value).toBe(''); }); @@ -200,6 +207,138 @@ describe('ChangeCredential', () => { await waitFor(() => expect(screen.getByText(/password is too common/i)).toBeTruthy()); }); + it.each([ + ['USR-1047', 400, /enter your current password/i], + ['USR-1048', 403, /the current password is incorrect/i], + ])('shows %s on the current field with translated text', async (code: string, status: number, text: RegExp) => { + const {ThunderIDAPIError} = await import('@thunderid/browser'); + + mockUpdateMeCredentials.mockRejectedValueOnce( + new ThunderIDAPIError(JSON.stringify({code, message: {defaultValue: 'Server text'}}), 'x-003', 'react', status), + ); + renderChangeCredential({policy: {regex: '^.{8,}$'}}); + + setField('currentPassword', 'wr0ngValue'); + setField('newPassword', 'n3wP@ssword'); + setField('confirmPassword', 'n3wP@ssword'); + fireEvent.click(submitButton()); + + await waitFor(() => expect(screen.getByText(text)).toBeTruthy()); + expect(fieldByName('currentPassword').getAttribute('aria-invalid')).toBe('true'); + expect(screen.queryByText('Server text')).toBeNull(); + }); + + it('asks the user to sign in again and hands over the challenge on AUTH-4011', async () => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + const onReauthenticationRequired = vi.fn(); + + mockUpdateMeCredentials.mockRejectedValueOnce( + new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'x-004', + 'react', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ), + ); + renderChangeCredential({attribute: 'pin', onReauthenticationRequired, policy: {regex: '^.{4,}$'}}); + + setField('newPassword', '1234'); + setField('confirmPassword', '1234'); + fireEvent.click(submitButton()); + + await waitFor(() => expect(screen.getByText(/sign in again to set your pin/i)).toBeTruthy()); + expect(onReauthenticationRequired).toHaveBeenCalledWith({error: 'insufficient_user_authentication', maxAge: 300}); + expect(mockReauthenticate).not.toHaveBeenCalled(); + }); + + describe('when a first value needs a recent sign-in', () => { + const stepUp = async (): Promise => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + + return new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'updateMeCredentials-StepUpRequired-001', + 'react', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); + }; + + const submitPin = (): void => { + setField('newPassword', '1234'); + setField('confirmPassword', '1234'); + fireEvent.click(submitButton()); + }; + + beforeEach(() => { + mockReauthenticate.mockReset(); + }); + + it('signs the user in again with the challenge max_age and sends the same change once more', async () => { + const onSuccess = vi.fn(); + mockUpdateMeCredentials.mockRejectedValueOnce(await stepUp()).mockResolvedValueOnce(undefined); + mockReauthenticate.mockResolvedValue(undefined); + renderChangeCredential({attribute: 'pin', onSuccess, policy: {regex: '^.{4,}$'}}); + + submitPin(); + + await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); + expect(mockReauthenticate).toHaveBeenCalledWith({maxAge: 300}); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(2); + expect((mockUpdateMeCredentials.mock.calls[1][0] as {payload: unknown}).payload).toEqual({ + currentValue: undefined, + name: 'pin', + newValue: '1234', + }); + }); + + it('shows the sign-in-again text when the change is refused again', async () => { + mockUpdateMeCredentials.mockRejectedValue(await stepUp()); + mockReauthenticate.mockResolvedValue(undefined); + renderChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + submitPin(); + + expect(await screen.findByText(/sign in again to set your pin/i)).toBeTruthy(); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(2); + }); + + it('shows a different-account error and keeps the change unsent', async () => { + mockUpdateMeCredentials.mockRejectedValue(await stepUp()); + mockReauthenticate.mockRejectedValue(Object.assign(new Error('other user'), {code: 'JS-AUTH_CORE-CRA-IV03'})); + renderChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + submitPin(); + + expect(await screen.findByText(/you signed in with a different account/i)).toBeTruthy(); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(1); + }); + + it('signs in again first on the next submit when the popup was blocked', async () => { + mockUpdateMeCredentials.mockRejectedValueOnce(await stepUp()).mockResolvedValueOnce(undefined); + mockReauthenticate + .mockRejectedValueOnce(Object.assign(new Error('blocked'), {code: 'BROWSER-REAUTHENTICATION-PB01'})) + .mockResolvedValueOnce(undefined); + renderChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + submitPin(); + expect(await screen.findByText(/allow pop-ups for this site/i)).toBeTruthy(); + + fireEvent.click(submitButton()); + + await waitFor(() => expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(2)); + expect(mockReauthenticate).toHaveBeenCalledTimes(2); + expect(mockReauthenticate.mock.invocationCallOrder[1]).toBeLessThan( + mockUpdateMeCredentials.mock.invocationCallOrder[1], + ); + }); + }); + it('surfaces an unmapped failure as a form-level error', async () => { const {ThunderIDAPIError} = await import('@thunderid/browser'); diff --git a/packages/react/src/components/account/UserProfile/UserProfile.tsx b/packages/react/src/components/account/UserProfile/UserProfile.tsx index d18411d0..81999c43 100644 --- a/packages/react/src/components/account/UserProfile/UserProfile.tsx +++ b/packages/react/src/components/account/UserProfile/UserProfile.tsx @@ -3,12 +3,19 @@ import { AttributeVerificationConstants, + AuthenticationChallenge, + PendingStepUp, + REAUTHENTICATION_FAILED, + StepUpRequiredError, ThunderIDError, + ThunderIDRuntimeError, User, deepMerge, + mapReauthenticationError, resolveResourceEndpoint, + runWithStepUp, } from '@thunderid/browser'; -import {FC, ReactElement, ReactNode, useState} from 'react'; +import {FC, ReactElement, ReactNode, useEffect, useRef, useState} from 'react'; // eslint-disable-next-line import/no-named-as-default import BaseUserProfile, {BaseUserProfileProps, BaseUserProfileVerificationRenderProps} from './BaseUserProfile'; import updateMeProfile from '../../../api/account/updateMeProfile'; @@ -27,6 +34,12 @@ export type UserProfileProps = Omit void; }; /** @@ -37,6 +50,12 @@ export type UserProfileProps = Omit = ({ preferences, editable = true, verificationFlowHandle = AttributeVerificationConstants.DEFAULT_FLOW_HANDLE, + onReauthenticationRequired = undefined, ...rest }: UserProfileProps): ReactElement => { - const {baseUrl, endpoints, instanceId, preferences: contextPreferences} = useThunderID(); + const {baseUrl, endpoints, instanceId, preferences: contextPreferences, reauthenticate} = useThunderID(); + const pendingStepUp: PendingStepUp = useRef(undefined); + // Whether the component is still on screen, so a change is not sent after it has closed. + const mountedRef = useRef(true); + + useEffect(() => { + mountedRef.current = true; + + return (): void => { + mountedRef.current = false; + }; + }, []); const {profile, flattenedProfile, onUpdateProfile, userSchema} = useUser(); const resolvedPreferences = { ...contextPreferences, @@ -98,17 +129,28 @@ const UserProfile: FC = ({ } }); - const response: User = await updateMeProfile({ - baseUrl, - url: resolveResourceEndpoint('usersMe', {endpoints}), - instanceId, - payload: updatedAttributes, + const response: User = await runWithStepUp({ + onReauthenticationRequired, + isActive: (): boolean => mountedRef.current, + pending: pendingStepUp, + reauthenticate, + send: () => + updateMeProfile({ + baseUrl, + url: resolveResourceEndpoint('usersMe', {endpoints}), + instanceId, + payload: updatedAttributes, + }), }); onUpdateProfile(response); } catch (caughtError: unknown) { let message: string = t('user.profile.update.generic.error'); - if (caughtError instanceof ThunderIDError) { + if (caughtError instanceof ThunderIDRuntimeError && caughtError.code === REAUTHENTICATION_FAILED) { + message = t(mapReauthenticationError((caughtError.details as {cause?: unknown} | undefined)?.cause)); + } else if (caughtError instanceof StepUpRequiredError) { + message = t('user.reauthentication.required.error'); + } else if (caughtError instanceof ThunderIDError) { message = caughtError?.message; } diff --git a/packages/react/src/components/account/UserProfile/__tests__/UserProfile.test.tsx b/packages/react/src/components/account/UserProfile/__tests__/UserProfile.test.tsx index b7cb2784..dc275061 100644 --- a/packages/react/src/components/account/UserProfile/__tests__/UserProfile.test.tsx +++ b/packages/react/src/components/account/UserProfile/__tests__/UserProfile.test.tsx @@ -12,6 +12,13 @@ import UserProfile, {UserProfileProps} from '../UserProfile'; const mockExecute = vi.fn() as Mock; const mockRevalidateProfile = vi.fn() as Mock; +const mockUpdateMeProfile = vi.fn() as Mock; +const mockReauthenticate = vi.fn() as Mock; +const mockOnUpdateProfile = vi.fn() as Mock; + +vi.mock('../../../../api/account/updateMeProfile', () => ({ + default: (...args: unknown[]): unknown => mockUpdateMeProfile(...args) as unknown, +})); vi.mock('../../../../api/auth/executeEmbeddedSelfFlow', () => ({ default: (...args: unknown[]): unknown => mockExecute(...args) as unknown, @@ -23,6 +30,7 @@ const thunderIDContext: ThunderIDContextProps = { isInitialized: true, isLoading: false, meta: null, + reauthenticate: (...args: unknown[]): unknown => mockReauthenticate(...args) as unknown, vendor: 'thunderid', } as unknown as ThunderIDContextProps; @@ -41,7 +49,7 @@ const renderUserProfile = (props: UserProfileProps = {}): ReturnType { expect(screen.queryByText('Verify')).toBeNull(); }); }); + +const editAndSave = (label: string, value: string): void => { + fireEvent.click(within(row(label)).getByTitle('Edit')); + fireEvent.change(within(row(label)).getByRole('textbox'), {target: {value}}); + fireEvent.click(within(row(label)).getByText('Save')); +}; + +const stepUp = async (): Promise => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + + return new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'updateMeProfile-StepUpRequired-001', + 'react', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); +}; + +describe('UserProfile recent sign-in', () => { + beforeEach(() => { + mockUpdateMeProfile.mockReset(); + mockReauthenticate.mockReset(); + mockOnUpdateProfile.mockReset(); + }); + + afterEach(() => { + cleanup(); + }); + + it('signs the user in again with the challenge max_age and saves the change once more', async () => { + const updated: User = {...profile, email: 'new@example.com'}; + mockUpdateMeProfile.mockRejectedValueOnce(await stepUp()).mockResolvedValueOnce(updated); + mockReauthenticate.mockResolvedValue(undefined); + renderUserProfile(); + + editAndSave('Email', 'new@example.com'); + + await waitFor(() => expect(mockOnUpdateProfile).toHaveBeenCalledWith(updated)); + expect(mockReauthenticate).toHaveBeenCalledWith({maxAge: 300}); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(2); + expect(mockUpdateMeProfile.mock.calls[1][0]).toEqual(mockUpdateMeProfile.mock.calls[0][0]); + }); + + it('shows an error when the change is refused again after signing in', async () => { + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + mockReauthenticate.mockResolvedValue(undefined); + renderUserProfile(); + + editAndSave('Email', 'new@example.com'); + + expect(await screen.findByText(/sign in again to save this change/i)).toBeTruthy(); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(2); + expect(mockReauthenticate).toHaveBeenCalledTimes(1); + }); + + it('shows why signing in again failed and does not retry', async () => { + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + mockReauthenticate.mockRejectedValue(Object.assign(new Error('blocked'), {code: 'BROWSER-REAUTHENTICATION-PB01'})); + renderUserProfile(); + + editAndSave('Email', 'new@example.com'); + + expect(await screen.findByText(/allow pop-ups for this site/i)).toBeTruthy(); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(1); + }); + + it('hands the challenge to the app instead of signing in again', async () => { + const onReauthenticationRequired = vi.fn(); + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + renderUserProfile({onReauthenticationRequired}); + + editAndSave('Email', 'new@example.com'); + + await waitFor(() => + expect(onReauthenticationRequired).toHaveBeenCalledWith({error: 'insufficient_user_authentication', maxAge: 300}), + ); + expect(mockReauthenticate).not.toHaveBeenCalled(); + expect(await screen.findByText(/sign in again to save this change/i)).toBeTruthy(); + }); +}); diff --git a/packages/react/src/components/auth/Reauthentication/ReauthenticationDialog.tsx b/packages/react/src/components/auth/Reauthentication/ReauthenticationDialog.tsx new file mode 100644 index 00000000..6928374b --- /dev/null +++ b/packages/react/src/components/auth/Reauthentication/ReauthenticationDialog.tsx @@ -0,0 +1,270 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + EmbeddedFlowComponent, + EmbeddedSignInFlowRequest, + EmbeddedSignInFlowResponse, + EmbeddedSignInFlowStatus, + EmbeddedSignInFlowType, + FieldError, + ReauthenticationOptions, + ThunderIDRuntimeError, + bem, + withVendorCSSClassPrefix, +} from '@thunderid/browser'; +import {FC, ReactElement, useEffect, useRef, useState} from 'react'; +import useTheme from '../../../contexts/Theme/useTheme'; +import useThunderID from '../../../contexts/ThunderID/useThunderID'; +import useTranslation from '../../../hooks/useTranslation'; +import {css, cx} from '../../../styles/emotion'; +import {extractErrorMessage, normalizeFlowResponse} from '../../../utils/flowTransformer'; +import {handlePasskeyAuthentication} from '../../../utils/passkey'; +import DialogPrimitive from '../../primitives/Dialog/Dialog'; +import BaseSignIn from '../SignIn/BaseSignIn'; + +export interface ReauthenticationDialogProps { + /** + * Runs a step of the re-sign-in flow, as the client's `executeReauthenticationFlow` does. + */ + execute: ( + payload: EmbeddedSignInFlowRequest, + options: ReauthenticationOptions, + ) => Promise; + /** + * How recent, in seconds, the sign-in must be. + */ + maxAge?: number; + /** + * Called when the user closes the dialog. + */ + onCancel: () => void; + /** + * Called once the flow has completed and the session holds its tokens. + */ + onComplete: () => void; + /** + * Called when the flow cannot go on, such as when a different user signed in. + */ + onError: (error: unknown) => void; +} + +interface FlowStep { + additionalData: Record; + challengeToken?: string; + components: EmbeddedFlowComponent[]; + executionId: string; +} + +/** + * Signs the signed-in user in again in a dialog, by running the sign-in flow with `maxAge`, for a + * session from an embedded sign-in flow. The provider shows it from `reauthenticate`. Each step is + * drawn with `BaseSignIn`; a passkey step asks the browser for the passkey. A sign-in option that + * leaves the page, such as a federated sign-in, is not offered here: the user is told to choose + * another one; a flow that offers nothing else fails with `REACT-REAUTHENTICATION-UO01`. A flow that cannot + * go on starts again once with its message shown; when the new one cannot go on either, the re-sign-in + * fails with `REACT-REAUTHENTICATION-FE01`. + * + * @internal + */ +const ReauthenticationDialog: FC = ({ + execute, + maxAge = undefined, + onCancel, + onComplete, + onError, +}: ReauthenticationDialogProps): ReactElement => { + const {meta} = useThunderID(); + const {t} = useTranslation(); + const {theme} = useTheme(); + const bodyClass: string = css` + display: flex; + flex-direction: column; + gap: calc(${theme.vars.spacing.unit} * 2); + padding: 0 calc(${theme.vars.spacing.unit} * 4.5) calc(${theme.vars.spacing.unit} * 3); + `; + const [step, setStep] = useState(null); + const [error, setError] = useState(null); + const [serverFieldErrors, setServerFieldErrors] = useState(null); + // Set once, so a second effect run in development does not start a second flow. + const startedRef = useRef(false); + + const start = async (): Promise => { + await apply(await execute({}, {maxAge}), true); + }; + + const submit = async (payload: EmbeddedSignInFlowRequest): Promise => { + if (!step) { + return; + } + + setError(null); + setServerFieldErrors(null); + + await apply( + await execute( + { + ...payload, + executionId: step.executionId, + ...(step.challengeToken ? {challengeToken: step.challengeToken} : {}), + }, + {maxAge}, + ), + false, + ); + }; + + // Starts the flow again after one that cannot go on, keeping the message on screen. A new flow that + // cannot go on either ends the re-sign-in, so the dialog never loops. + const restart = async (message: string, isStart: boolean): Promise => { + if (isStart) { + onError(new ThunderIDRuntimeError(message, 'REACT-REAUTHENTICATION-FE01', 'react')); + + return; + } + + await start(); + setError(new Error(message)); + }; + + const apply = async (response: EmbeddedSignInFlowResponse, isStart: boolean): Promise => { + if (response.flowStatus === EmbeddedSignInFlowStatus.Complete) { + onComplete(); + + return; + } + + if (response.type === EmbeddedSignInFlowType.Redirection) { + if (isStart) { + onError( + new ThunderIDRuntimeError( + 'The sign-in flow offers only a sign-in option that leaves the page.', + 'REACT-REAUTHENTICATION-UO01', + 'react', + ), + ); + + return; + } + + // The redirect would lose the change waiting to be saved, so the flow starts again. + await restart(t('user.reauthentication.unsupported_option.error'), false); + + return; + } + + const additionalData: Record = + (response.data?.additionalData as Record | undefined) ?? {}; + const passkeyChallenge: unknown = additionalData['passkeyChallenge']; + + if (typeof passkeyChallenge === 'string' && response.executionId) { + let credential: { + id: string; + response: {authenticatorData: string; clientDataJSON: string; signature: string; userHandle: string}; + }; + + try { + credential = JSON.parse(await handlePasskeyAuthentication(passkeyChallenge)) as typeof credential; + } catch { + // The user cancelled the passkey prompt, or the browser refused it. + await restart(t('user.reauthentication.failed.error'), isStart); + + return; + } + + setStep({ + additionalData, + challengeToken: response.challengeToken, + components: [], + executionId: response.executionId, + }); + await apply( + await execute( + { + executionId: response.executionId, + inputs: { + authenticatorData: credential.response.authenticatorData, + clientDataJSON: credential.response.clientDataJSON, + credentialId: credential.id, + signature: credential.response.signature, + userHandle: credential.response.userHandle, + }, + ...(response.challengeToken ? {challengeToken: response.challengeToken} : {}), + }, + {maxAge}, + ), + false, + ); + + return; + } + + // A flow that ended, or an error with no step left to show, such as a failed passkey, starts again. + if (response.flowStatus === EmbeddedSignInFlowStatus.Error && (!response.executionId || !step?.components.length)) { + await restart(extractErrorMessage(response, t), isStart); + + return; + } + + const normalized: {additionalData: Record; components: EmbeddedFlowComponent[]} = + response.flowStatus === EmbeddedSignInFlowStatus.Error + ? {additionalData: step?.additionalData ?? {}, components: step?.components ?? []} + : normalizeFlowResponse(response, t, {resolveTranslations: false}, meta); + + setStep({ + additionalData: normalized.additionalData, + challengeToken: response.challengeToken, + components: normalized.components, + executionId: response.executionId, + }); + + const fieldErrors: FieldError[] | undefined = (response.data as {fieldErrors?: FieldError[]} | undefined) + ?.fieldErrors; + + if (fieldErrors && fieldErrors.length > 0) { + setServerFieldErrors(fieldErrors); + } + + if (response.error || response.flowStatus === EmbeddedSignInFlowStatus.Error) { + setError(new Error(extractErrorMessage(response, t))); + } + }; + + useEffect(() => { + if (startedRef.current) { + return; + } + + startedRef.current = true; + start().catch(onError); + // Runs once on mount: the dialog is mounted for one re-sign-in. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( + { + if (!isOpen) onCancel(); + }} + > + + {t('user.reauthentication.heading')} +
+ {t('user.reauthentication.description')} + => submit(payload).catch(onError)} + /> +
+
+
+ ); +}; + +export default ReauthenticationDialog; diff --git a/packages/react/src/components/auth/Reauthentication/__tests__/ReauthenticationDialog.test.tsx b/packages/react/src/components/auth/Reauthentication/__tests__/ReauthenticationDialog.test.tsx new file mode 100644 index 00000000..dff6018f --- /dev/null +++ b/packages/react/src/components/auth/Reauthentication/__tests__/ReauthenticationDialog.test.tsx @@ -0,0 +1,140 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {EmbeddedSignInFlowResponse, ThunderIDRuntimeError} from '@thunderid/browser'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import I18nProvider from '../../../../contexts/I18n/I18nProvider'; +import ThemeProvider from '../../../../contexts/Theme/ThemeProvider'; +import ThunderIDContext, {ThunderIDContextProps} from '../../../../contexts/ThunderID/ThunderIDContext'; +import ReauthenticationDialog from '../ReauthenticationDialog'; + +const thunderIDContext: ThunderIDContextProps = {meta: null, vendor: 'thunderid'} as unknown as ThunderIDContextProps; + +const step = (executionId = 'e-1'): EmbeddedSignInFlowResponse => + ({ + data: { + meta: {components: [{eventType: 'TRIGGER', id: 'action_continue', label: 'Continue', type: 'ACTION'}]}, + }, + executionId, + flowStatus: 'INCOMPLETE', + type: 'VIEW', + }) as unknown as EmbeddedSignInFlowResponse; + +const complete = {assertion: 'a', flowStatus: 'COMPLETE'} as unknown as EmbeddedSignInFlowResponse; + +const renderDialog = (execute: ReturnType) => { + const handlers = {onCancel: vi.fn(), onComplete: vi.fn(), onError: vi.fn()}; + + render( + + + + + + + , + ); + + return handlers; +}; + +describe('ReauthenticationDialog', () => { + afterEach(() => { + cleanup(); + }); + + it('starts the flow once with maxAge and completes after the step is submitted', async () => { + const execute = vi.fn().mockResolvedValueOnce(step()).mockResolvedValueOnce(complete); + const {onComplete, onError} = renderDialog(execute); + + fireEvent.click(await screen.findByRole('button', {name: 'Continue'})); + + await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1)); + expect(execute).toHaveBeenNthCalledWith(1, {}, {maxAge: 30}); + expect(execute).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({action: 'action_continue', executionId: 'e-1'}), + {maxAge: 30}, + ); + expect(onError).not.toHaveBeenCalled(); + }); + + it('completes at once when the server reuses a recent enough sign-in', async () => { + const execute = vi.fn().mockResolvedValueOnce(complete); + const {onComplete} = renderDialog(execute); + + await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1)); + expect(execute).toHaveBeenCalledTimes(1); + }); + + it('reports a sign-in by a different user', async () => { + const differentUser = new ThunderIDRuntimeError('x', 'BROWSER-REAUTHENTICATION-DU01', 'browser'); + const execute = vi.fn().mockResolvedValueOnce(step()).mockRejectedValueOnce(differentUser); + const {onComplete, onError} = renderDialog(execute); + + fireEvent.click(await screen.findByRole('button', {name: 'Continue'})); + + await waitFor(() => expect(onError).toHaveBeenCalledWith(differentUser)); + expect(onComplete).not.toHaveBeenCalled(); + }); + + it('starts again and tells the user when they pick an option that leaves the page', async () => { + const redirection = {executionId: 'e-1', flowStatus: 'INCOMPLETE', type: 'REDIRECTION'}; + const execute = vi + .fn() + .mockResolvedValueOnce(step()) + .mockResolvedValueOnce(redirection) + .mockResolvedValueOnce(step('e-2')); + const {onError} = renderDialog(execute); + + fireEvent.click(await screen.findByRole('button', {name: 'Continue'})); + + expect(await screen.findByText('This sign-in option is not available here. Choose another one.')).toBeTruthy(); + expect(execute).toHaveBeenNthCalledWith(3, {}, {maxAge: 30}); + expect(onError).not.toHaveBeenCalled(); + }); + + it('fails when the flow offers only an option that leaves the page', async () => { + const execute = vi.fn().mockResolvedValueOnce({executionId: 'e-1', flowStatus: 'INCOMPLETE', type: 'REDIRECTION'}); + const {onError} = renderDialog(execute); + + await waitFor(() => + expect(onError).toHaveBeenCalledWith(expect.objectContaining({code: 'REACT-REAUTHENTICATION-UO01'})), + ); + }); + + it('cancels when the user closes the dialog', async () => { + const execute = vi.fn().mockResolvedValueOnce(step()); + const {onCancel} = renderDialog(execute); + + await screen.findByRole('button', {name: 'Continue'}); + fireEvent.click(screen.getByRole('button', {name: 'Close'})); + + expect(onCancel).toHaveBeenCalledTimes(1); + }); + + it('ends the re-sign-in instead of starting again when a new flow cannot go on', async () => { + const ended = {flowStatus: 'ERROR'} as unknown as EmbeddedSignInFlowResponse; + const execute = vi.fn().mockResolvedValueOnce(ended).mockResolvedValue(ended); + const {onError} = renderDialog(execute); + + await waitFor(() => + expect(onError).toHaveBeenCalledWith(expect.objectContaining({code: 'REACT-REAUTHENTICATION-FE01'})), + ); + expect(execute).toHaveBeenCalledTimes(1); + }); + + it('starts again once when the flow ends after a step, then ends the re-sign-in', async () => { + const ended = {flowStatus: 'ERROR'} as unknown as EmbeddedSignInFlowResponse; + const execute = vi.fn().mockResolvedValueOnce(step()).mockResolvedValueOnce(ended).mockResolvedValue(ended); + const {onError} = renderDialog(execute); + + fireEvent.click(await screen.findByRole('button', {name: 'Continue'})); + + await waitFor(() => + expect(onError).toHaveBeenCalledWith(expect.objectContaining({code: 'REACT-REAUTHENTICATION-FE01'})), + ); + expect(execute).toHaveBeenCalledTimes(3); + }); +}); diff --git a/packages/react/src/contexts/ThunderID/ThunderIDContext.ts b/packages/react/src/contexts/ThunderID/ThunderIDContext.ts index bf348537..6057cf7f 100644 --- a/packages/react/src/contexts/ThunderID/ThunderIDContext.ts +++ b/packages/react/src/contexts/ThunderID/ThunderIDContext.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { @@ -20,6 +20,7 @@ import { AttributeSchema, CurrentOrganizationUnit, Project, + ReauthenticationOptions, SwitchOrganizationUnitOptions, User, } from '@thunderid/browser'; @@ -58,6 +59,15 @@ export type ThunderIDContextProps = { * Reads the current organization unit from the session's claims. For display only. */ getCurrentOrganizationUnit: () => Promise; + /** + * Signs the signed-in user in again, for a change that needs a recent sign-in, and replaces the + * session's tokens only when the same user signed in. Pass the `maxAge` of the `StepUpRequiredError` + * the change failed with, then retry the change once. A session from a redirect sign-in signs in again + * in a popup, so call it from a user action. A session from an embedded sign-in flow runs the sign-in + * flow again in a dialog the provider shows. It rejects when the user cancels, the sign-in fails, or a + * different user signs in, and the session is then left as it was. + */ + reauthenticate: (options?: ReauthenticationOptions) => Promise; /** * Signs in again bounded to the organization unit `organizationUnitId`, replacing the session on * success and refreshing the user. A failed switch keeps the previous session and rejects with an @@ -305,6 +315,7 @@ const ThunderIDContext: Context = createContext Promise.resolve(null), preferences: undefined, switchOrganizationUnit: () => Promise.resolve(undefined), + reauthenticate: () => Promise.resolve(), scopes: undefined, setCurrentProject: () => undefined, discovery: { diff --git a/packages/react/src/contexts/ThunderID/ThunderIDProvider.tsx b/packages/react/src/contexts/ThunderID/ThunderIDProvider.tsx index a4e64f5a..12cf0f2a 100644 --- a/packages/react/src/contexts/ThunderID/ThunderIDProvider.tsx +++ b/packages/react/src/contexts/ThunderID/ThunderIDProvider.tsx @@ -6,6 +6,8 @@ import { createResourceInvalidator, ThunderIDAPIError, ThunderIDRuntimeError, + ReauthenticationMethod, + ReauthenticationOptions, generateFlattenedUserProfile, OIDCDiscoveryApiResponse, SignInOptions, @@ -13,6 +15,7 @@ import { UserProfile, IdToken, extractUserClaimsFromIdToken, + EmbeddedSignInFlowRequest, EmbeddedSignInFlowResponse, EmbeddedRecoveryFlowRequest, EmbeddedRecoveryFlowResponse, @@ -32,6 +35,7 @@ import ThunderIDContext, {ThunderIDContextProps} from './ThunderIDContext'; import useCurrentProjectState, {CurrentProjectState} from './useCurrentProjectState'; import getUsersMe from '../../api/account/getUsersMe'; import getUsersMeMeta from '../../api/account/getUsersMeMeta'; +import ReauthenticationDialog from '../../components/auth/Reauthentication/ReauthenticationDialog'; import useBrowserUrl from '../../hooks/useBrowserUrl'; import {ThunderIDReactConfig} from '../../models/config'; import {configureEmotionNonce} from '../../styles/emotion'; @@ -48,6 +52,16 @@ const logger: ReturnType = createPackageCom 'ThunderIDProvider', ); +/** + * A re-sign-in the provider's dialog runs for `reauthenticate`. + */ +interface ReauthenticationRequestState { + id: number; + options: ReauthenticationOptions; + reject: (reason: unknown) => void; + resolve: () => void; +} + /** * Props interface of {@link ThunderIDProvider} */ @@ -117,6 +131,42 @@ const ThunderIDProvider: FC> = ({ const [isUpdatingSession, setIsUpdatingSession] = useState(false); const [wellKnown, setWellKnown] = useState(null); + // How the user signs in again, kept current with the session so `reauthenticate` can open a popup at once. + const reauthenticationMethodRef: RefObject = useRef( + null, + ); + // A re-sign-in the provider's dialog is running for `reauthenticate`. The ref settles it from outside + // React's render, when another call replaces it or the provider unmounts. + const [reauthenticationRequest, setReauthenticationRequest] = useState(null); + const reauthenticationRequestRef: RefObject = + useRef(null); + + const settleReauthentication = (request: ReauthenticationRequestState, error?: unknown): void => { + if (reauthenticationRequestRef.current === request) { + reauthenticationRequestRef.current = null; + setReauthenticationRequest(null); + } + + if (error === undefined) { + request.resolve(); + } else { + request.reject(error); + } + }; + + useEffect( + () => (): void => { + const open: ReauthenticationRequestState | null = reauthenticationRequestRef.current; + + if (open) { + reauthenticationRequestRef.current = null; + open.reject( + new ThunderIDRuntimeError('The sign-in ended before it completed.', 'REACT-REAUTHENTICATION-CN01', 'react'), + ); + } + }, + [], + ); // Holds the in-flight `updateSession()` promise so concurrent callers coalesce onto a single // `/users/me` request instead of issuing one each. @@ -143,6 +193,7 @@ const ThunderIDProvider: FC> = ({ let resolvedBaseUrl: string = baseUrl; const decodedToken: IdToken = await client.getDecodedIdToken(); + reauthenticationMethodRef.current = await client.getReauthenticationMethod(); // If there's a `user_org` claim in the ID token, // Treat this login as a organization login. @@ -470,7 +521,47 @@ const ThunderIDProvider: FC> = ({ await updateSession(); } - return (result as User | undefined) ?? undefined; + return result ?? undefined; + }; + + /** + * Signs the user in again, in a popup for a redirect session or in the provider's dialog for a session + * from an embedded sign-in flow, and refreshes the session state from the new tokens. A failed + * re-sign-in leaves the session as it was and rejects with the error. + */ + const reauthenticate: ThunderIDContextProps['reauthenticate'] = async (options?: ReauthenticationOptions) => { + // Read without an await first, so the popup still opens inside the user action. + if (reauthenticationMethodRef.current !== 'flow') { + try { + await client.reauthenticate(options); + await updateSession(); + + return; + } catch (error) { + if ((error as {code?: string})?.code !== 'BROWSER-REAUTHENTICATION-UM02') { + throw error; + } + } + } + + await new Promise((resolve: () => void, reject: (reason: unknown) => void): void => { + const previous: ReauthenticationRequestState | null = reauthenticationRequestRef.current; + const request: ReauthenticationRequestState = { + id: (previous?.id ?? 0) + 1, + options: options ?? {}, + reject, + resolve, + }; + + reauthenticationRequestRef.current = request; + setReauthenticationRequest(request); + + // One re-sign-in at a time: a new one replaces the one still open. + previous?.reject( + new ThunderIDRuntimeError('Another sign-in replaced this one.', 'REACT-REAUTHENTICATION-SU01', 'react'), + ); + }); + await updateSession(); }; const getCurrentOrganizationUnit: ThunderIDContextProps['getCurrentOrganizationUnit'] = useCallback( @@ -603,6 +694,7 @@ const ThunderIDProvider: FC> = ({ getCurrentOrganizationUnit, setCurrentProject, switchOrganizationUnit, + reauthenticate, discovery: { wellKnown, }, @@ -684,6 +776,7 @@ const ThunderIDProvider: FC> = ({ getCurrentOrganizationUnit, setCurrentProject, switchOrganizationUnit, + reauthenticate, telemetry, ], ); @@ -707,6 +800,27 @@ const ThunderIDProvider: FC> = ({ > {children} + {reauthenticationRequest && ( + + client.executeReauthenticationFlow(payload, options) + } + maxAge={reauthenticationRequest.options.maxAge} + onCancel={(): void => + settleReauthentication( + reauthenticationRequest, + new ThunderIDRuntimeError( + 'The user closed the sign-in.', + 'REACT-REAUTHENTICATION-CN01', + 'react', + ), + ) + } + onComplete={(): void => settleReauthentication(reauthenticationRequest)} + onError={(error: unknown): void => settleReauthentication(reauthenticationRequest, error)} + /> + )} diff --git a/packages/react/src/contexts/ThunderID/__tests__/ThunderIDProvider.test.tsx b/packages/react/src/contexts/ThunderID/__tests__/ThunderIDProvider.test.tsx index d97a2d5d..9373baee 100644 --- a/packages/react/src/contexts/ThunderID/__tests__/ThunderIDProvider.test.tsx +++ b/packages/react/src/contexts/ThunderID/__tests__/ThunderIDProvider.test.tsx @@ -1,7 +1,7 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {cleanup, render, screen, waitFor} from '@testing-library/react'; +import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react'; import {ThunderIDAPIError, ThunderIDRuntimeError} from '@thunderid/browser'; import {ReactElement, useEffect} from 'react'; import {Mock, afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; @@ -21,11 +21,13 @@ type UserProfileResponse = Record; interface MockClient { clearSession: Noop; exchangeToken: Noop; + executeReauthenticationFlow: Mock<() => Promise>>; getAccessToken: Noop; getConfiguration: Mock<() => Promise<{afterSignInUrl: string; baseUrl: string}>>; getDecodedIdToken: Mock<() => Promise>>; getDiscoveryResponse: Mock<() => Promise>; getIdToken: Noop; + getReauthenticationMethod: Mock<() => Promise>; getStorageManager: Noop; /** Callbacks registered through `client.on(...)`, keyed by event name. */ handlers: Record; @@ -35,6 +37,7 @@ interface MockClient { isSignedIn: Mock<() => Promise>; on: Mock<(event: string, callback: SignInHookHandler) => Promise>; reInitialize: Noop; + reauthenticate: Mock<() => Promise>; recover: Noop; request: Noop; requestAll: Noop; @@ -65,7 +68,8 @@ vi.mock('../../../api/account/getUsersMe', () => ({ default: (): Promise => mocks.getUsersMe(), })); -vi.mock('../../../styles/emotion', () => ({ +vi.mock('../../../styles/emotion', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), configureEmotionNonce: (nonce?: string): void => mocks.configureEmotionNonce(nonce), })); @@ -90,6 +94,7 @@ function createMockClient(): MockClient { const client: MockClient = { clearSession: vi.fn(), exchangeToken: vi.fn(), + executeReauthenticationFlow: vi.fn(() => Promise.resolve({assertion: 'a', flowStatus: 'COMPLETE'})), getAccessToken: vi.fn(), getConfiguration: vi.fn(() => Promise.resolve({afterSignInUrl: window.location.origin, baseUrl: 'https://localhost:8090'}), @@ -97,6 +102,7 @@ function createMockClient(): MockClient { getDecodedIdToken: vi.fn(() => Promise.resolve({sub: 'user-1'})), getDiscoveryResponse: vi.fn(() => Promise.resolve(null)), getIdToken: vi.fn(), + getReauthenticationMethod: vi.fn(() => Promise.resolve('popup')), getStorageManager: vi.fn(), handlers, initialize: vi.fn(() => Promise.resolve(true)), @@ -109,6 +115,7 @@ function createMockClient(): MockClient { return Promise.resolve(); }), reInitialize: vi.fn(), + reauthenticate: vi.fn(() => Promise.resolve()), recover: vi.fn(), request: vi.fn(), requestAll: vi.fn(), @@ -330,6 +337,83 @@ describe('ThunderIDProvider revalidateProfile', () => { }); }); +describe('ThunderIDProvider reauthenticate', () => { + let reauthenticate: ((options?: {maxAge?: number}) => Promise) | null = null; + + const Probe = (): ReactElement => { + const context = useThunderID(); + + useEffect(() => { + reauthenticate = context.reauthenticate; + }); + + return
; + }; + + const renderWithProbe = async (): Promise => { + mocks.client.signedIn = true; + render( + + + , + ); + await waitFor(() => expect(mocks.client.getReauthenticationMethod).toHaveBeenCalled()); + await settle(); + }; + + afterEach(() => { + reauthenticate = null; + }); + + it('signs in again in a popup for a session from a redirect sign-in', async () => { + await renderWithProbe(); + + await reauthenticate!({maxAge: 30}); + + expect(mocks.client.reauthenticate).toHaveBeenCalledWith({maxAge: 30}); + expect(mocks.client.executeReauthenticationFlow).not.toHaveBeenCalled(); + }); + + it('runs the sign-in flow in a dialog for a session from a sign-in flow', async () => { + mocks.client.getReauthenticationMethod = vi.fn(() => Promise.resolve('flow')); + await renderWithProbe(); + + await reauthenticate!({maxAge: 30}); + + expect(mocks.client.reauthenticate).not.toHaveBeenCalled(); + expect(mocks.client.executeReauthenticationFlow).toHaveBeenCalledWith({}, {maxAge: 30}); + }); + + it('falls back to the dialog when the popup reports a session from a sign-in flow', async () => { + mocks.client.reauthenticate = vi.fn(() => + Promise.reject(new ThunderIDRuntimeError('x', 'BROWSER-REAUTHENTICATION-UM02', 'browser')), + ); + await renderWithProbe(); + + await reauthenticate!({maxAge: 30}); + + expect(mocks.client.executeReauthenticationFlow).toHaveBeenCalledWith({}, {maxAge: 30}); + }); + + it('rejects when the user closes the dialog', async () => { + mocks.client.getReauthenticationMethod = vi.fn(() => Promise.resolve('flow')); + mocks.client.executeReauthenticationFlow = vi.fn(() => + Promise.resolve({ + data: {meta: {components: [{eventType: 'TRIGGER', id: 'go', label: 'Continue', type: 'ACTION'}]}}, + executionId: 'e-1', + flowStatus: 'INCOMPLETE', + type: 'VIEW', + } as unknown as Record), + ); + await renderWithProbe(); + + const pending: Promise = reauthenticate!({maxAge: 30}); + fireEvent.click(await screen.findByRole('button', {name: 'Close'})); + + await expect(pending).rejects.toMatchObject({code: 'REACT-REAUTHENTICATION-CN01'}); + }); +}); + describe('ThunderIDProvider signIn errors', () => { let signIn: ((...args: unknown[]) => Promise) | null = null; diff --git a/packages/tanstack-router/CHANGELOG.md b/packages/tanstack-router/CHANGELOG.md index 1b297b22..93c2c3cf 100644 --- a/packages/tanstack-router/CHANGELOG.md +++ b/packages/tanstack-router/CHANGELOG.md @@ -2,10 +2,12 @@ No changes to this SDK since sdk/tanstack-router/v1.23.0. -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/tanstack-router/v1.23.0...sdk/tanstack-router/v1.23.1 +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/tanstack-router/v1.23.0...sdk/tanstack-router/v1.23.1 ## 1.23.0 No changes to this SDK since sdk/tanstack-router/v1.22.0. -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/tanstack-router/v1.22.0...sdk/tanstack-router/v1.23.0 +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/tanstack-router/v1.22.0...sdk/tanstack-router/v1.23.0 diff --git a/packages/vue/CHANGELOG.md b/packages/vue/CHANGELOG.md index 2ab062d3..d5a07549 100644 --- a/packages/vue/CHANGELOG.md +++ b/packages/vue/CHANGELOG.md @@ -1,7 +1,9 @@ ## 1.25.1 ### 🐛 Bug Fixes -* Report a failed passkey prompt to the flow by @KaveeshaPiumini in https://github.com/thunder-id/javascript-sdks/pull/189 + +- Report a failed passkey prompt to the flow by @KaveeshaPiumini in + https://github.com/thunder-id/javascript-sdks/pull/189 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/vue/v1.25.0...sdk/vue/v1.25.1 diff --git a/packages/vue/src/ThunderIDVueClient.ts b/packages/vue/src/ThunderIDVueClient.ts index ade9b072..66fa44b5 100644 --- a/packages/vue/src/ThunderIDVueClient.ts +++ b/packages/vue/src/ThunderIDVueClient.ts @@ -199,32 +199,16 @@ class ThunderIDVueClient exte response.flowStatus === EmbeddedSignInFlowStatus.Complete && response.assertion ) { - const decodedAssertion: { - [key: string]: unknown; - exp?: number; - iat?: number; - scope?: string; - } = await this.decodeJwtToken<{ - [key: string]: unknown; - exp?: number; - iat?: number; - scope?: string; - }>(response.assertion); - - const createdAt: number = decodedAssertion.iat ? decodedAssertion.iat * 1000 : Date.now(); - const expiresIn: number = - decodedAssertion.exp && decodedAssertion.iat ? decodedAssertion.exp - decodedAssertion.iat : 3600; - - await this.setSession({ - access_token: response.assertion, - created_at: createdAt, - expires_in: expiresIn, - id_token: response.assertion, - scope: decodedAssertion.scope, - token_type: 'Bearer', + const claims: Record = await this.setSessionFromFlowAssertion({ + ...response, + assertion: response.assertion, + }).catch((error: unknown) => { + this.notifySignInFailed((error as {code?: unknown})?.code); + + throw error; }); - this.notifySignIn(extractUserClaimsFromIdToken(decodedAssertion as IdToken) as User); + this.notifySignIn(extractUserClaimsFromIdToken(claims as IdToken) as User); } return response; @@ -264,32 +248,9 @@ class ThunderIDVueClient exte response.flowStatus === EmbeddedSignUpFlowStatus.Complete && response.assertion ) { - const decodedAssertion: { - [key: string]: unknown; - exp?: number; - iat?: number; - scope?: string; - } = await this.decodeJwtToken<{ - [key: string]: unknown; - exp?: number; - iat?: number; - scope?: string; - }>(response.assertion); - - const createdAt: number = decodedAssertion.iat ? decodedAssertion.iat * 1000 : Date.now(); - const expiresIn: number = - decodedAssertion.exp && decodedAssertion.iat ? decodedAssertion.exp - decodedAssertion.iat : 3600; - - await this.setSession({ - access_token: response.assertion, - created_at: createdAt, - expires_in: expiresIn, - id_token: response.assertion, - scope: decodedAssertion.scope, - token_type: 'Bearer', - }); + const claims: Record = await this.setSessionFromFlowAssertion(response); - this.notifySignIn(extractUserClaimsFromIdToken(decodedAssertion as IdToken) as User); + this.notifySignIn(extractUserClaimsFromIdToken(claims as IdToken) as User); } return response; diff --git a/packages/vue/src/__tests__/api/account/update-me-credentials.test.ts b/packages/vue/src/__tests__/api/account/update-me-credentials.test.ts index fa08c77d..7aaf6195 100644 --- a/packages/vue/src/__tests__/api/account/update-me-credentials.test.ts +++ b/packages/vue/src/__tests__/api/account/update-me-credentials.test.ts @@ -35,7 +35,7 @@ describe('updateMeCredentials (vue)', () => { await expect( updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }), ).rejects.toMatchObject({statusCode: 400}); @@ -46,7 +46,7 @@ describe('updateMeCredentials (vue)', () => { await expect( updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }), ).rejects.toMatchObject({code: 'updateMeCredentials-NetworkError-001'}); @@ -62,7 +62,7 @@ describe('updateMeCredentials (vue)', () => { await expect( updateMeCredentials({ - payload: {password: 'n3wP@ssword!'}, + payload: {name: 'password', newValue: 'n3wP@ssword!'}, url: 'https://localhost:8090/users/me/update-credentials', }), ).resolves.toBeUndefined(); diff --git a/packages/vue/src/__tests__/api/account/update-me-profile.test.ts b/packages/vue/src/__tests__/api/account/update-me-profile.test.ts new file mode 100644 index 00000000..82ef0bc5 --- /dev/null +++ b/packages/vue/src/__tests__/api/account/update-me-profile.test.ts @@ -0,0 +1,58 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {StepUpRequiredError} from '@thunderid/browser'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import updateMeProfile from '../../../api/account/updateMeProfile'; + +// The httpClient-to-Response adapter is covered in @thunderid/browser's createHttpClientFetcher tests. +// This checks that the wrapper uses it, so a refused write reaches the core function's error mapping. +const mockFetcher = vi.fn(); + +vi.mock('@thunderid/browser', async () => { + const actual = await vi.importActual('@thunderid/browser'); + return { + ...actual, + createHttpClientFetcher: () => mockFetcher, + }; +}); + +describe('updateMeProfile (vue)', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('turns a step-up challenge into a StepUpRequiredError with its maxAge', async () => { + mockFetcher.mockResolvedValueOnce({ + headers: new Headers({ + 'WWW-Authenticate': 'Bearer error="insufficient_user_authentication", max_age="180"', + }), + ok: false, + status: 401, + statusText: 'Unauthorized', + text: () => + Promise.resolve(JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}})), + } as Response); + + const error: unknown = await updateMeProfile({ + payload: {email: 'new@example.com'}, + url: 'https://localhost:8090/users/me', + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StepUpRequiredError); + expect((error as StepUpRequiredError).maxAge).toBe(180); + }); + + it('resolves with the updated profile', async () => { + mockFetcher.mockResolvedValueOnce({ + json: () => Promise.resolve({email: 'new@example.com', id: 'user-1'}), + ok: true, + status: 200, + statusText: 'OK', + } as Response); + + await expect( + updateMeProfile({payload: {email: 'new@example.com'}, url: 'https://localhost:8090/users/me'}), + ).resolves.toMatchObject({id: 'user-1'}); + }); +}); diff --git a/packages/vue/src/__tests__/client/ThunderIDVueClient.test.ts b/packages/vue/src/__tests__/client/ThunderIDVueClient.test.ts index 1667135e..0ff1112d 100644 --- a/packages/vue/src/__tests__/client/ThunderIDVueClient.test.ts +++ b/packages/vue/src/__tests__/client/ThunderIDVueClient.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return */ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, type Mock, vi} from 'vitest'; import type {ThunderIDVueConfig} from '../../models/config'; import ThunderIDVueClient from '../../ThunderIDVueClient'; @@ -209,3 +209,69 @@ describe('ThunderIDVueClient authId of an authorization request', () => { expect(postedCallbackBody(fetchMock)['authId']).toBe('auth-a'); }); }); + +describe('ThunderIDVueClient embedded session', () => { + const baseUrl = 'https://idp.example.com'; + const assertion = 'h.eyJzdWIiOiJ1MSJ9.s'; + let client: ThunderIDVueClient; + + const json = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), {headers: {'Content-Type': 'application/json'}, status}); + + /** Answers discovery, the flow step and the token request. */ + const serverAnswering = (tokenBody: unknown, tokenStatus = 200): Mock => + vi.fn((url: string) => { + if (url.includes('/.well-known/')) { + return Promise.resolve(json({issuer: baseUrl, token_endpoint: `${baseUrl}/oauth2/token`})); + } + + if (url.endsWith('/oauth2/token')) { + return Promise.resolve(json(tokenBody, tokenStatus)); + } + + return Promise.resolve(json({assertion, flowStatus: 'COMPLETE'})); + }); + + beforeEach(async () => { + sessionStorage.clear(); + client = new ThunderIDVueClient(44); + await client.initialize({ + afterSignInUrl: window.location.origin, + applicationId: 'app-1', + baseUrl, + clientId: 'embedded-session-client', + storage: 'sessionStorage', + } as ThunderIDVueConfig); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + sessionStorage.clear(); + }); + + it.each([ + ['sign-in', (c: ThunderIDVueClient): Promise => c.signIn({executionId: 'e1', inputs: {}} as any)], + ['sign-up', (c: ThunderIDVueClient): Promise => c.signUp({executionId: 'e1', inputs: {}} as any)], + ])('keeps the access token a completed %s exchanges its assertion for', async (_name: string, run: any) => { + const fetchMock = serverAnswering({access_token: 'at', expires_in: 900}); + vi.stubGlobal('fetch', fetchMock); + // The test browser has no Buffer for the default JWT decoder. + vi.spyOn(client, 'decodeJwtToken').mockResolvedValue({sub: 'u1'} as any); + + await run(client); + + const tokenCall: any[] = fetchMock.mock.calls.find(([url]: any[]) => String(url).endsWith('/oauth2/token'))!; + expect(tokenCall[1].body.get('subject_token')).toBe(assertion); + expect(await client.getAccessToken()).toBe('at'); + expect((await client.getStorageManager().getSessionData()).id_token).toBe(assertion); + }); + + it('fails a completed sign-in and keeps no session when the application lacks the grant', async () => { + vi.stubGlobal('fetch', serverAnswering({error: 'unauthorized_client'}, 400)); + + await expect(client.signIn({executionId: 'e1', inputs: {}} as any)).rejects.toMatchObject({ + code: 'JS-AUTH_CORE-EFA-UC04', + }); + expect((await client.getStorageManager().getSessionData())?.access_token).toBeUndefined(); + }); +}); diff --git a/packages/vue/src/__tests__/components/account/change-credential.test.ts b/packages/vue/src/__tests__/components/account/change-credential.test.ts index 8993550d..25c6c1c2 100644 --- a/packages/vue/src/__tests__/components/account/change-credential.test.ts +++ b/packages/vue/src/__tests__/components/account/change-credential.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {getDefaultI18nBundles, substituteTranslationParams} from '@thunderid/browser'; -import {DOMWrapper, mount} from '@vue/test-utils'; +import {DOMWrapper, flushPromises, mount} from '@vue/test-utils'; import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; import {nextTick, ref} from 'vue'; import ChangeCredential from '../../../components/account/change-credential/ChangeCredential'; @@ -10,6 +10,7 @@ import {I18N_KEY, THUNDERID_KEY, USER_KEY} from '../../../keys'; import type {I18nContextValue, ThunderIDContext, UserContextValue} from '../../../models/contexts'; const mockUpdateMeCredentials = vi.fn() as Mock; +const mockReauthenticate = vi.fn() as Mock; vi.mock('../../../api/account/updateMeCredentials', () => ({ default: (...args: unknown[]): unknown => mockUpdateMeCredentials(...args) as unknown, @@ -22,6 +23,7 @@ const createThunderIDContext = (): ThunderIDContext => isInitialized: ref(true), isLoading: ref(false), isSignedIn: ref(true), + reauthenticate: (...args: unknown[]): unknown => mockReauthenticate(...args) as unknown, user: ref(null), vendor: 'thunderid', }) as unknown as ThunderIDContext; @@ -88,17 +90,20 @@ describe('ChangeCredential', () => { vi.clearAllMocks(); }); - it('renders only the two fields, with no current-value field', () => { + it('renders an optional current-value field above the new value and its confirmation', () => { const wrapper = mountChangeCredential(); + expect(inputByName(wrapper, 'currentPassword').exists()).toBe(true); + expect(inputByName(wrapper, 'currentPassword').element.required).toBe(false); expect(inputByName(wrapper, 'newPassword').exists()).toBe(true); expect(inputByName(wrapper, 'confirmPassword').exists()).toBe(true); - expect(wrapper.find('input[name="currentPassword"]').exists()).toBe(false); + expect(wrapper.text()).toMatch(/leave this empty if you have not set one yet/i); }); - it('marks both fields as new-password for password managers', () => { + it('marks the current field as current-password and the new fields as new-password', () => { const wrapper = mountChangeCredential(); + expect(inputByName(wrapper, 'currentPassword').attributes('autocomplete')).toBe('current-password'); expect(inputByName(wrapper, 'newPassword').attributes('autocomplete')).toBe('new-password'); expect(inputByName(wrapper, 'confirmPassword').attributes('autocomplete')).toBe('new-password'); }); @@ -130,7 +135,7 @@ describe('ChangeCredential', () => { expect(submit().attributes('disabled')).toBeUndefined(); }); - it('sends only the new value, keyed by password by default, and emits success', async () => { + it('sends the name and new value without a current value when it is left empty, and emits success', async () => { mockUpdateMeCredentials.mockResolvedValueOnce(undefined); const wrapper = mountChangeCredential({policy: {regex: '^.{8,}$'}}); @@ -142,23 +147,23 @@ describe('ChangeCredential', () => { expect(mockUpdateMeCredentials).toHaveBeenCalledWith( expect.objectContaining({ baseUrl: 'https://localhost:8090', - payload: {password: 'n3wP@ssword'}, + payload: {currentValue: undefined, name: 'password', newValue: 'n3wP@ssword'}, }), ); expect(wrapper.emitted('success')).toBeTruthy(); }); - it('keys the payload by attribute when set to something other than password', async () => { + it('sends the current value and names the attribute when set to something other than password', async () => { mockUpdateMeCredentials.mockResolvedValueOnce(undefined); const wrapper = mountChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); - await fill(wrapper, {confirmPassword: '1234', newPassword: '1234'}); + await fill(wrapper, {confirmPassword: '1234', currentPassword: '0000', newPassword: '1234'}); await wrapper.find('form').trigger('submit'); await nextTick(); expect(mockUpdateMeCredentials).toHaveBeenCalledWith( expect.objectContaining({ - payload: {pin: '1234'}, + payload: {currentValue: '0000', name: 'pin', newValue: '1234'}, }), ); }); @@ -167,11 +172,12 @@ describe('ChangeCredential', () => { mockUpdateMeCredentials.mockResolvedValueOnce(undefined); const wrapper = mountChangeCredential({policy: {regex: '^.{8,}$'}}); - await fill(wrapper, {confirmPassword: 'n3wP@ssword', newPassword: 'n3wP@ssword'}); + await fill(wrapper, {confirmPassword: 'n3wP@ssword', currentPassword: '0ldP@ssword', newPassword: 'n3wP@ssword'}); await wrapper.find('form').trigger('submit'); await nextTick(); await nextTick(); + expect(inputByName(wrapper, 'currentPassword').element.value).toBe(''); expect(inputByName(wrapper, 'newPassword').element.value).toBe(''); expect(inputByName(wrapper, 'confirmPassword').element.value).toBe(''); }); @@ -192,6 +198,118 @@ describe('ChangeCredential', () => { expect(wrapper.text()).toMatch(/password is too common/i); }); + it.each([ + ['USR-1047', 400, /enter your current password/i], + ['USR-1048', 403, /the current password is incorrect/i], + ])('shows %s on the current field with translated text', async (code: string, status: number, text: RegExp) => { + const {ThunderIDAPIError} = await import('@thunderid/browser'); + + mockUpdateMeCredentials.mockRejectedValueOnce( + new ThunderIDAPIError(JSON.stringify({code, message: {defaultValue: 'Server text'}}), 'x-003', 'vue', status), + ); + const wrapper = mountChangeCredential({policy: {regex: '^.{8,}$'}}); + + await fill(wrapper, {confirmPassword: 'n3wP@ssword', currentPassword: 'wr0ng', newPassword: 'n3wP@ssword'}); + await wrapper.find('form').trigger('submit'); + await nextTick(); + await nextTick(); + + const currentField = inputByName(wrapper, 'currentPassword').element.closest('.thunderid-password-field'); + expect(currentField?.textContent).toMatch(text); + expect(wrapper.text()).not.toContain('Server text'); + }); + + it('hands the challenge to a reauthentication-required listener instead of signing in again', async () => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + + mockUpdateMeCredentials.mockRejectedValueOnce( + new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'x-004', + 'vue', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ), + ); + const onReauthenticationRequired = vi.fn(); + const wrapper = mountChangeCredential({attribute: 'pin', onReauthenticationRequired, policy: {regex: '^.{4,}$'}}); + + await fill(wrapper, {confirmPassword: '1234', newPassword: '1234'}); + await wrapper.find('form').trigger('submit'); + await flushPromises(); + + expect(wrapper.text()).toMatch(/sign in again to set your pin/i); + expect(onReauthenticationRequired).toHaveBeenCalledWith({error: 'insufficient_user_authentication', maxAge: 300}); + expect(mockReauthenticate).not.toHaveBeenCalled(); + }); + + describe('when a first value needs a recent sign-in', () => { + const stepUp = async (): Promise => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + + return new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'updateMeCredentials-StepUpRequired-001', + 'vue', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); + }; + + const submitPin = async (wrapper: ReturnType): Promise => { + await fill(wrapper, {confirmPassword: '1234', newPassword: '1234'}); + await wrapper.find('form').trigger('submit'); + await flushPromises(); + }; + + beforeEach(() => { + mockReauthenticate.mockReset(); + }); + + it('signs the user in again with the challenge max_age and sends the same change once more', async () => { + mockUpdateMeCredentials.mockRejectedValueOnce(await stepUp()).mockResolvedValueOnce(undefined); + mockReauthenticate.mockResolvedValue(undefined); + const wrapper = mountChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + await submitPin(wrapper); + + expect(mockReauthenticate).toHaveBeenCalledWith({maxAge: 300}); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(2); + expect((mockUpdateMeCredentials.mock.calls[1][0] as {payload: unknown}).payload).toEqual({ + currentValue: undefined, + name: 'pin', + newValue: '1234', + }); + expect(wrapper.emitted('success')).toBeTruthy(); + }); + + it('shows the sign-in-again text when the change is refused again', async () => { + mockUpdateMeCredentials.mockRejectedValue(await stepUp()); + mockReauthenticate.mockResolvedValue(undefined); + const wrapper = mountChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + await submitPin(wrapper); + + expect(wrapper.text()).toMatch(/sign in again to set your pin/i); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(2); + }); + + it('shows why signing in again failed and does not retry', async () => { + mockUpdateMeCredentials.mockRejectedValue(await stepUp()); + mockReauthenticate.mockRejectedValue(Object.assign(new Error('other user'), {code: 'JS-AUTH_CORE-CRA-IV03'})); + const wrapper = mountChangeCredential({attribute: 'pin', policy: {regex: '^.{4,}$'}}); + + await submitPin(wrapper); + + expect(wrapper.text()).toMatch(/you signed in with a different account/i); + expect(mockUpdateMeCredentials).toHaveBeenCalledTimes(1); + }); + }); + it('derives the policy regex from the user schema', async () => { const wrapper = mountChangeCredential({}, {password: {credential: true, regex: '^[a-z]+$'}}); diff --git a/packages/vue/src/__tests__/components/account/user-profile-step-up.test.ts b/packages/vue/src/__tests__/components/account/user-profile-step-up.test.ts new file mode 100644 index 00000000..f68405c5 --- /dev/null +++ b/packages/vue/src/__tests__/components/account/user-profile-step-up.test.ts @@ -0,0 +1,142 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AttributeSchema, User, getDefaultI18nBundles, substituteTranslationParams} from '@thunderid/browser'; +import {DOMWrapper, VueWrapper, flushPromises, mount} from '@vue/test-utils'; +import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; +import {ref} from 'vue'; +import UserProfile from '../../../components/account/user-profile/UserProfile'; +import {FLOW_META_KEY, I18N_KEY, THUNDERID_KEY, USER_KEY} from '../../../keys'; +import type {I18nContextValue, ThunderIDContext, UserContextValue} from '../../../models/contexts'; + +const mockUpdateMeProfile = vi.fn() as Mock; +const mockReauthenticate = vi.fn() as Mock; +const mockOnUpdateProfile = vi.fn() as Mock; + +vi.mock('../../../api/account/updateMeProfile', () => ({ + default: (...args: unknown[]): unknown => mockUpdateMeProfile(...args) as unknown, +})); + +const userSchema: Record = { + email: {displayName: 'Email', type: 'email'}, + given_name: {displayName: 'First name', type: 'string'}, +} as Record; + +const attributes = {email: 'alex@example.com', given_name: 'Alex'}; +const profile: User = {attributes, id: 'user-1', ...attributes, verifiedAttributes: {}}; + +const t = (key: string, params?: Record): string => { + const translations = getDefaultI18nBundles()['en-US']?.translations as unknown as Record; + const value: string = translations?.[key] ?? key; + return params ? substituteTranslationParams(value, params) : value; +}; + +const mountUserProfile = (props: Record = {}): VueWrapper => + mount(UserProfile, { + global: { + provide: { + [FLOW_META_KEY as symbol]: {meta: ref(null)}, + [I18N_KEY as symbol]: {currentLanguage: ref('en-US'), t} as unknown as I18nContextValue, + [THUNDERID_KEY as symbol]: { + baseUrl: 'https://localhost:8090', + instanceId: 0, + isInitialized: ref(true), + isLoading: ref(false), + reauthenticate: (...args: unknown[]): unknown => mockReauthenticate(...args) as unknown, + vendor: 'thunderid', + } as unknown as ThunderIDContext, + [USER_KEY as symbol]: { + flattenedProfile: ref(profile), + onUpdateProfile: mockOnUpdateProfile, + profile: ref({flattenedProfile: profile, profile}), + revalidateProfile: vi.fn().mockResolvedValue(undefined), + userSchema: ref(userSchema), + } as unknown as UserContextValue, + }, + }, + props, + }) as VueWrapper; + +const row = (wrapper: VueWrapper, label: string): DOMWrapper => + wrapper + .findAll('.thunderid-user-profile__field') + .find((r: DOMWrapper) => r.find('.thunderid-user-profile__field-label').text() === label)!; + +const editAndSave = async (wrapper: VueWrapper, label: string, value: string): Promise => { + await row(wrapper, label).find('button[title="Edit"]').trigger('click'); + await row(wrapper, label).find('input').setValue(value); + await row(wrapper, label) + .findAll('button') + .find((b: DOMWrapper) => b.text() === 'Save')! + .trigger('click'); + await flushPromises(); +}; + +const stepUp = async (): Promise => { + const {StepUpRequiredError} = await import('@thunderid/browser'); + + return new StepUpRequiredError( + JSON.stringify({code: 'AUTH-4011', message: {defaultValue: 'Recent authentication required'}}), + 'updateMeProfile-StepUpRequired-001', + 'vue', + 401, + 'Unauthorized', + undefined, + 'Bearer error="insufficient_user_authentication", max_age="300"', + ); +}; + +describe('UserProfile recent sign-in', () => { + beforeEach(() => { + mockUpdateMeProfile.mockReset(); + mockReauthenticate.mockReset(); + mockOnUpdateProfile.mockReset(); + }); + + it('signs the user in again with the challenge max_age and saves the change once more', async () => { + const updated: User = {...profile, email: 'new@example.com'}; + mockUpdateMeProfile.mockRejectedValueOnce(await stepUp()).mockResolvedValueOnce(updated); + mockReauthenticate.mockResolvedValue(undefined); + const wrapper: VueWrapper = mountUserProfile(); + + await editAndSave(wrapper, 'Email', 'new@example.com'); + + expect(mockReauthenticate).toHaveBeenCalledWith({maxAge: 300}); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(2); + expect(mockUpdateMeProfile.mock.calls[1][0]).toEqual(mockUpdateMeProfile.mock.calls[0][0]); + expect(mockOnUpdateProfile).toHaveBeenCalledWith(updated); + }); + + it('shows an error when the change is refused again after signing in', async () => { + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + mockReauthenticate.mockResolvedValue(undefined); + const wrapper: VueWrapper = mountUserProfile(); + + await editAndSave(wrapper, 'Email', 'new@example.com'); + + expect(wrapper.text()).toMatch(/sign in again to save this change/i); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(2); + }); + + it('shows why signing in again failed and does not retry', async () => { + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + mockReauthenticate.mockRejectedValue(Object.assign(new Error('blocked'), {code: 'BROWSER-REAUTHENTICATION-PB01'})); + const wrapper: VueWrapper = mountUserProfile(); + + await editAndSave(wrapper, 'Email', 'new@example.com'); + + expect(wrapper.text()).toMatch(/allow pop-ups for this site/i); + expect(mockUpdateMeProfile).toHaveBeenCalledTimes(1); + }); + + it('hands the challenge to a reauthentication-required listener instead of signing in again', async () => { + const onReauthenticationRequired = vi.fn(); + mockUpdateMeProfile.mockRejectedValue(await stepUp()); + const wrapper: VueWrapper = mountUserProfile({onReauthenticationRequired}); + + await editAndSave(wrapper, 'Email', 'new@example.com'); + + expect(onReauthenticationRequired).toHaveBeenCalledWith({error: 'insufficient_user_authentication', maxAge: 300}); + expect(mockReauthenticate).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/vue/src/__tests__/providers/ThunderIDProvider.organization-unit.test.ts b/packages/vue/src/__tests__/providers/ThunderIDProvider.organization-unit.test.ts index 4763f376..aceef0ee 100644 --- a/packages/vue/src/__tests__/providers/ThunderIDProvider.organization-unit.test.ts +++ b/packages/vue/src/__tests__/providers/ThunderIDProvider.organization-unit.test.ts @@ -12,6 +12,7 @@ const client = vi.hoisted(() => ({ getConfiguration: vi.fn(), getCurrentOrganizationUnit: vi.fn(), getDecodedIdToken: vi.fn(), + getReauthenticationMethod: vi.fn().mockResolvedValue('popup'), getDiscoveryResponse: vi.fn(), initialize: vi.fn(), isInitialized: vi.fn(), diff --git a/packages/vue/src/__tests__/providers/ThunderIDProvider.reauthentication.test.ts b/packages/vue/src/__tests__/providers/ThunderIDProvider.reauthentication.test.ts new file mode 100644 index 00000000..22caf888 --- /dev/null +++ b/packages/vue/src/__tests__/providers/ThunderIDProvider.reauthentication.test.ts @@ -0,0 +1,229 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDRuntimeError} from '@thunderid/browser'; +import {flushPromises, mount} from '@vue/test-utils'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {defineComponent, h, inject} from 'vue'; +import {THUNDERID_KEY} from '../../keys'; +import type {ThunderIDContext} from '../../models/contexts'; +import ThunderIDProvider from '../../providers/ThunderIDProvider'; + +const client = vi.hoisted(() => ({ + executeReauthenticationFlow: vi.fn(), + getConfiguration: vi.fn().mockResolvedValue({}), + getDecodedIdToken: vi.fn().mockResolvedValue({sub: 'user-1'}), + getDiscoveryResponse: vi.fn().mockResolvedValue({}), + getReauthenticationMethod: vi.fn(), + initialize: vi.fn().mockResolvedValue(true), + isInitialized: vi.fn().mockResolvedValue(true), + isLoading: vi.fn(() => false), + isSignedIn: vi.fn().mockResolvedValue(true), + on: vi.fn(), + reauthenticate: vi.fn(), + signIn: vi.fn(), +})); + +vi.mock('../../ThunderIDVueClient', () => ({ + default: vi.fn().mockImplementation(function MockClient() { + return client; + }), +})); + +const continueStep = { + data: {meta: {components: [{eventType: 'TRIGGER', id: 'go', label: 'Continue', type: 'ACTION'}]}}, + executionId: 'e-1', + flowStatus: 'INCOMPLETE', + type: 'VIEW', +}; + +const mountProvider = async (): Promise => { + let context: ThunderIDContext | undefined; + const Probe = defineComponent({ + setup() { + context = inject(THUNDERID_KEY); + return () => h('div'); + }, + }); + + mount(ThunderIDProvider, { + attachTo: document.body, + props: {baseUrl: 'https://localhost:8090', clientId: 'client', preferences: {user: {fetchUserProfile: false}}}, + slots: {default: () => h(Probe)}, + }); + await flushPromises(); + + return context!; +}; + +describe('ThunderIDProvider reauthenticate', () => { + beforeEach(() => { + client.getReauthenticationMethod.mockResolvedValue('popup'); + client.reauthenticate.mockResolvedValue(undefined); + client.executeReauthenticationFlow.mockResolvedValue({assertion: 'a', flowStatus: 'COMPLETE'}); + }); + + afterEach(() => { + vi.clearAllMocks(); + document.body.innerHTML = ''; + }); + + it('signs in again in a popup for a session from a redirect sign-in', async () => { + const context: ThunderIDContext = await mountProvider(); + + await context.reauthenticate({maxAge: 30}); + + expect(client.reauthenticate).toHaveBeenCalledWith({maxAge: 30}); + expect(client.executeReauthenticationFlow).not.toHaveBeenCalled(); + }); + + it('runs the sign-in flow in a dialog for a session from a sign-in flow', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + const context: ThunderIDContext = await mountProvider(); + + await context.reauthenticate({maxAge: 30}); + + expect(client.reauthenticate).not.toHaveBeenCalled(); + expect(client.executeReauthenticationFlow).toHaveBeenCalledWith({}, {maxAge: 30}); + }); + + it('falls back to the dialog when the popup reports a session from a sign-in flow', async () => { + client.reauthenticate.mockRejectedValue(new ThunderIDRuntimeError('x', 'BROWSER-REAUTHENTICATION-UM02', 'browser')); + const context: ThunderIDContext = await mountProvider(); + + await context.reauthenticate({maxAge: 30}); + + expect(client.executeReauthenticationFlow).toHaveBeenCalledWith({}, {maxAge: 30}); + }); + + it('submits the step and resolves when the flow completes', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow + .mockResolvedValueOnce(continueStep) + .mockResolvedValueOnce({assertion: 'a', flowStatus: 'COMPLETE'}); + const context: ThunderIDContext = await mountProvider(); + + const pending: Promise = context.reauthenticate({maxAge: 30}); + await flushPromises(); + const button = [...document.querySelectorAll('[role="dialog"] button')].find( + (element: Element) => element.textContent === 'Continue', + ) as HTMLButtonElement; + button.click(); + + await expect(pending).resolves.toBeUndefined(); + expect(client.executeReauthenticationFlow).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({action: 'go', executionId: 'e-1'}), + {maxAge: 30}, + ); + await flushPromises(); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + }); + + it('rejects and keeps nothing open when the user closes the dialog', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow.mockResolvedValueOnce(continueStep); + const context: ThunderIDContext = await mountProvider(); + + const pending: Promise = context.reauthenticate({maxAge: 30}); + await flushPromises(); + document.querySelector('[role="dialog"] [aria-label="Close"]')!.click(); + + await expect(pending).rejects.toMatchObject({code: 'VUE-REAUTHENTICATION-CN01'}); + await flushPromises(); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + }); + + it('closes on Escape and keeps focus inside when the focused control leaves the page', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow.mockResolvedValueOnce(continueStep); + const context: ThunderIDContext = await mountProvider(); + const outside: HTMLButtonElement = document.body.appendChild(document.createElement('button')); + + const pending: Promise = context.reauthenticate({maxAge: 30}); + await flushPromises(); + const dialog: HTMLElement = document.querySelector('[role="dialog"]')!; + outside.focus(); + expect(dialog.contains(document.activeElement)).toBe(true); + + document.body.dispatchEvent(new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'})); + + await expect(pending).rejects.toMatchObject({code: 'VUE-REAUTHENTICATION-CN01'}); + outside.remove(); + }); + + it('rejects when a different user signs in', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + const differentUser = new ThunderIDRuntimeError('x', 'BROWSER-REAUTHENTICATION-DU01', 'browser'); + client.executeReauthenticationFlow.mockResolvedValueOnce(continueStep).mockRejectedValueOnce(differentUser); + const context: ThunderIDContext = await mountProvider(); + + const pending: Promise = context.reauthenticate({maxAge: 30}); + await flushPromises(); + const button = [...document.querySelectorAll('[role="dialog"] button')].find( + (element: Element) => element.textContent === 'Continue', + ) as HTMLButtonElement; + button.click(); + + await expect(pending).rejects.toBe(differentUser); + }); + + const clickContinue = (): void => { + const button = [...document.querySelectorAll('[role="dialog"] button')].find( + (element: Element) => element.textContent === 'Continue', + ) as HTMLButtonElement; + button.click(); + }; + + it('ends the re-sign-in instead of starting again when a new flow cannot go on', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow.mockResolvedValue({flowStatus: 'ERROR'}); + const context: ThunderIDContext = await mountProvider(); + + await expect(context.reauthenticate({maxAge: 30})).rejects.toMatchObject({code: 'VUE-REAUTHENTICATION-FE01'}); + expect(client.executeReauthenticationFlow).toHaveBeenCalledTimes(1); + }); + + it('starts again when the user picks an option that leaves the page, and says why', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow + .mockResolvedValueOnce(continueStep) + .mockResolvedValueOnce({executionId: 'e-1', flowStatus: 'INCOMPLETE', type: 'REDIRECTION'}) + .mockResolvedValueOnce(continueStep); + const context: ThunderIDContext = await mountProvider(); + + void context.reauthenticate({maxAge: 30}).catch(() => undefined); + await flushPromises(); + clickContinue(); + await flushPromises(); + + expect(client.executeReauthenticationFlow).toHaveBeenNthCalledWith(3, {}, {maxAge: 30}); + expect(document.querySelector('[role="dialog"]')?.textContent).toContain( + 'This sign-in option is not available here. Choose another one.', + ); + }); + + it('fails when the flow offers only an option that leaves the page', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow.mockResolvedValue({ + executionId: 'e-1', + flowStatus: 'INCOMPLETE', + type: 'REDIRECTION', + }); + const context: ThunderIDContext = await mountProvider(); + + await expect(context.reauthenticate({maxAge: 30})).rejects.toMatchObject({code: 'VUE-REAUTHENTICATION-UO01'}); + }); + + it('rejects an open re-sign-in that a new one replaces', async () => { + client.getReauthenticationMethod.mockResolvedValue('flow'); + client.executeReauthenticationFlow.mockResolvedValue(continueStep); + const context: ThunderIDContext = await mountProvider(); + + const first: Promise = context.reauthenticate({maxAge: 30}); + await flushPromises(); + void context.reauthenticate({maxAge: 30}).catch(() => undefined); + + await expect(first).rejects.toMatchObject({code: 'VUE-REAUTHENTICATION-SU01'}); + }); +}); diff --git a/packages/vue/src/api/account/updateMeProfile.ts b/packages/vue/src/api/account/updateMeProfile.ts index a430d584..e6eb876a 100644 --- a/packages/vue/src/api/account/updateMeProfile.ts +++ b/packages/vue/src/api/account/updateMeProfile.ts @@ -1,13 +1,11 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { - FetchHttpClient, - HttpRequestConfig, - HttpResponse, User, - UpdateMeProfileConfig as BaseUpdateMeProfileConfig, + createHttpClientFetcher, updateMeProfile as baseUpdateMeProfile, + UpdateMeProfileConfig as BaseUpdateMeProfileConfig, } from '@thunderid/browser'; export interface UpdateMeProfileConfig extends Omit { @@ -16,28 +14,10 @@ export interface UpdateMeProfileConfig extends Omit => { - const defaultFetcher = async (url: string, config: RequestInit): Promise => { - const httpClient: FetchHttpClient = FetchHttpClient.getInstance(instanceId); - - const response: HttpResponse = await httpClient.request({ - data: config.body ? JSON.parse(config.body as string) : undefined, - headers: config.headers as Record, - method: config.method || 'PUT', - url, - } as HttpRequestConfig); - - return { - json: () => Promise.resolve(response.data), - ok: response.status >= 200 && response.status < 300, - status: response.status, - statusText: response.statusText || '', - text: () => Promise.resolve(typeof response.data === 'string' ? response.data : JSON.stringify(response.data)), - } as Response; - }; - return baseUpdateMeProfile({ ...requestConfig, - fetcher: fetcher || defaultFetcher, + // Keeps a refused response, so the server's error, such as a step-up challenge, reaches the caller. + fetcher: fetcher ?? createHttpClientFetcher(instanceId), }); }; diff --git a/packages/vue/src/components/account/change-credential/BaseChangeCredential.ts b/packages/vue/src/components/account/change-credential/BaseChangeCredential.ts index b08de20b..fecc12d5 100644 --- a/packages/vue/src/components/account/change-credential/BaseChangeCredential.ts +++ b/packages/vue/src/components/account/change-credential/BaseChangeCredential.ts @@ -30,12 +30,13 @@ import PasswordField from '../../primitives/PasswordField/PasswordField'; /** * The values collected by the form and emitted on `submit`. - * - * There is deliberately no current-value field here. The self-service credential write - * endpoint does not verify the account's existing value today, so a field the server - * ignores would only teach the user a false sense of security. */ export interface ChangePasswordValues { + /** + * The credential's current value, present only when the user filled it in. The server + * needs it when the user holds the credential, and not when the user sets a first one. + */ + currentPassword?: string; newPassword: string; } @@ -58,8 +59,9 @@ type BaseChangeCredentialProps = Readonly<{ const ruleIcon = (passed: boolean): VNode => (passed ? CheckIcon() : XIcon()); /** - * Presentational change-credential form with just the two fields a first-time or - * unverified credential change needs: new value and confirmation. + * Presentational change-credential form: the current value, the new value and its + * confirmation. The current value is optional, so a user who has not set the credential + * yet can set a first one. * * Holds no context and performs no network calls: it renders the fields, evaluates the * policy for the checklist and the submit gate, and emits `submit` with the validated @@ -82,7 +84,7 @@ const BaseChangeCredential: Component = defineComponent({ credentialDisplayName: {default: 'Password', type: String}, /** A form-level error, typically a server failure that maps to no single field. */ error: {default: null, type: String as PropType}, - /** Server-supplied errors keyed by field name (`newPassword`). */ + /** Server-supplied errors keyed by field name (`currentPassword` or `newPassword`). */ fieldErrors: {default: () => ({}), type: Object as PropType>}, /** Whether a submission is in flight. */ loading: {default: false, type: Boolean}, @@ -132,6 +134,7 @@ const BaseChangeCredential: Component = defineComponent({ // `title` overrides the default heading; an explicit empty string omits it entirely. const resolvedTitle: ComputedRef = computed(() => props.title ?? translate('user.change_password.heading')); + const currentPassword: Ref = ref(''); const newPassword: Ref = ref(''); const confirmPassword: Ref = ref(''); const submitted: Ref = ref(false); @@ -143,6 +146,7 @@ const BaseChangeCredential: Component = defineComponent({ (succeeded: boolean): void => { if (!succeeded) return; + currentPassword.value = ''; newPassword.value = ''; confirmPassword.value = ''; submitted.value = false; @@ -171,7 +175,12 @@ const BaseChangeCredential: Component = defineComponent({ if (!canSubmit.value) return; - emit('submit', {newPassword: newPassword.value}); + emit( + 'submit', + currentPassword.value + ? {currentPassword: currentPassword.value, newPassword: newPassword.value} + : {newPassword: newPassword.value}, + ); } return (): VNode => { @@ -187,6 +196,7 @@ const BaseChangeCredential: Component = defineComponent({ // not flag fields the user has not finished filling in. const confirmError: string | undefined = submitted.value && !confirmMatches.value ? translate('user.change_password.mismatch.error') : undefined; + const currentPasswordError: string | undefined = props.fieldErrors['currentPassword']; const newPasswordError: string | undefined = props.fieldErrors['newPassword']; const form: VNode = h('form', {class: rootClass, novalidate: true, onSubmit: handleSubmit}, [ @@ -205,6 +215,20 @@ const BaseChangeCredential: Component = defineComponent({ : null, h('div', {class: withVendorCSSClassPrefix('change-credential__fields')}, [ + h(PasswordField, { + autocomplete: 'current-password', + disabled: interactionDisabled.value, + error: currentPasswordError, + helperText: translate('user.change_password.current.hint'), + label: translate('user.change_password.current.label'), + modelValue: currentPassword.value, + name: 'currentPassword', + 'onUpdate:modelValue': (value: string): void => { + currentPassword.value = value; + }, + placeholder: translate('user.change_password.current.placeholder'), + }), + h(PasswordField, { autocomplete: 'new-password', disabled: interactionDisabled.value, diff --git a/packages/vue/src/components/account/change-credential/ChangeCredential.ts b/packages/vue/src/components/account/change-credential/ChangeCredential.ts index 334ac9f7..c8697fd5 100644 --- a/packages/vue/src/components/account/change-credential/ChangeCredential.ts +++ b/packages/vue/src/components/account/change-credential/ChangeCredential.ts @@ -2,13 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { + AuthenticationChallenge, CredentialConstants, CredentialUpdateErrorResult, PasswordPolicy, + type PendingStepUp, Preferences, mapCredentialUpdateError, resolveChangeCredentialPolicy, resolveResourceEndpoint, + runWithStepUp, supportsCredential, withVendorCSSClassPrefix, } from '@thunderid/browser'; @@ -22,6 +25,7 @@ import { computed, defineComponent, h, + onUnmounted, ref, } from 'vue'; import BaseChangeCredential, {type ChangePasswordValues} from './BaseChangeCredential'; @@ -40,6 +44,7 @@ type ChangeCredentialProps = Readonly<{ attribute: string; cardLayout: boolean; className: string; + onReauthenticationRequired?: (challenge: AuthenticationChallenge) => void; policy?: PasswordPolicy; preferences?: Preferences; showRequirements: boolean; @@ -49,10 +54,16 @@ type ChangeCredentialProps = Readonly<{ /** * ChangeCredential lets the signed-in user set a new value for one of their own credentials. * - * It collects only a new value and its confirmation. The self-service credential write path - * does not verify the account's existing value today, so this component does not ask for one; - * once server-side current-value verification ships, that field returns without a breaking - * change to this component's public props. + * It collects the current value, the new value and its confirmation. The server needs the + * current value when the user holds the credential, and answers a wrong or missing one on the + * current-value field. A user who has not set the credential yet leaves the current value + * empty; that change needs a recent sign-in. When the sign-in is too old, the component signs + * the user in again with the server's `max_age`, checks that the same user signed in, and sends + * the change once more; the values stay in memory only. A session from a redirect sign-in signs in + * again in a popup, and one from an embedded sign-in flow runs the sign-in flow in a dialog. If the + * browser blocks the popup, the next submit opens it first. Listen to `reauthentication-required` to handle the challenge in + * your app instead. Changing a credential the user holds ends the user's sessions, including this + * one. */ const ChangeCredential: Component = defineComponent({ name: 'ChangeCredential', @@ -72,6 +83,15 @@ const ChangeCredential: Component = defineComponent({ cardLayout: {default: false, type: Boolean}, /** Extra CSS class added to the root element. */ className: {default: '', type: String}, + /** + * Bound by `@reauthentication-required`. When set, a change that needs a more recent sign-in + * (`AUTH-4011`) calls it with the server's challenge instead of the component signing the user in + * again by itself. + */ + onReauthenticationRequired: { + default: undefined, + type: Function as PropType<(challenge: AuthenticationChallenge) => void>, + }, /** Explicit rules. When omitted, they are derived from the user schema. */ policy: {default: undefined, type: Object as PropType}, /** Component-level preferences to override global preferences. */ @@ -87,7 +107,14 @@ const ChangeCredential: Component = defineComponent({ }, emits: ['success'], setup(props: ChangeCredentialProps, {emit}: SetupContext): () => VNode { - const {baseUrl, endpoints, instanceId, preferences: contextPreferences} = useThunderID(); + const {baseUrl, endpoints, instanceId, preferences: contextPreferences, reauthenticate} = useThunderID(); + const pendingStepUp: PendingStepUp = {}; + // Whether the component is still on screen, so a change is not sent after it has closed. + let active = true; + + onUnmounted((): void => { + active = false; + }); const {userSchema} = useUser(); const {t} = useI18n(); const resolvedDisplayName: ComputedRef = computed( @@ -112,20 +139,25 @@ const ChangeCredential: Component = defineComponent({ resolveChangeCredentialPolicy(userSchema?.value, props.attribute, props.policy), ); - async function handleSubmit({newPassword}: ChangePasswordValues): Promise { + async function handleSubmit({currentPassword, newPassword}: ChangePasswordValues): Promise { error.value = null; fieldErrors.value = {}; success.value = false; loading.value = true; try { - await updateMeCredentials({ - baseUrl, - instanceId, - payload: { - [props.attribute]: newPassword, - }, - url: resolveResourceEndpoint('usersMeCredentials', {endpoints}), + await runWithStepUp({ + onReauthenticationRequired: props.onReauthenticationRequired, + isActive: (): boolean => active, + pending: pendingStepUp, + reauthenticate, + send: () => + updateMeCredentials({ + baseUrl, + instanceId, + payload: {currentValue: currentPassword, name: props.attribute, newValue: newPassword}, + url: resolveResourceEndpoint('usersMeCredentials', {endpoints}), + }), }); success.value = true; diff --git a/packages/vue/src/components/account/user-profile/UserProfile.ts b/packages/vue/src/components/account/user-profile/UserProfile.ts index 9539b8a7..0b781a8a 100644 --- a/packages/vue/src/components/account/user-profile/UserProfile.ts +++ b/packages/vue/src/components/account/user-profile/UserProfile.ts @@ -1,13 +1,20 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import { AttributeVerificationConstants, + type AuthenticationChallenge, + type PendingStepUp, Preferences, + REAUTHENTICATION_FAILED, + StepUpRequiredError, ThunderIDError, + ThunderIDRuntimeError, User, deepMerge, + mapReauthenticationError, resolveResourceEndpoint, + runWithStepUp, withVendorCSSClassPrefix, } from '@thunderid/browser'; import { @@ -18,6 +25,7 @@ import { computed, defineComponent, h, + onUnmounted, ref, type Ref, } from 'vue'; @@ -36,6 +44,7 @@ type UserProfileProps = Readonly<{ compact: boolean; editable: boolean; hideFields: string[]; + onReauthenticationRequired?: (challenge: AuthenticationChallenge) => void; preferences?: Preferences; showAvatar: boolean; showFields: string[]; @@ -66,6 +75,15 @@ const UserProfile: Component = defineComponent({ editable: {default: true, type: Boolean}, /** Fields to hide by name. */ hideFields: {default: () => [], type: Array as PropType}, + /** + * Bound by `@reauthentication-required`. When set, a change that needs a more recent sign-in + * (`AUTH-4011`), such as a new email address or mobile number, calls it with the server's challenge + * instead of the component signing the user in again by itself. + */ + onReauthenticationRequired: { + default: undefined, + type: Function as PropType<(challenge: AuthenticationChallenge) => void>, + }, /** Component-level preferences to override global preferences. */ preferences: { default: undefined, @@ -81,7 +99,14 @@ const UserProfile: Component = defineComponent({ verificationFlowHandle: {default: AttributeVerificationConstants.DEFAULT_FLOW_HANDLE, type: String}, }, setup(props: UserProfileProps, {slots}: SetupContext): () => VNode { - const {baseUrl, endpoints, instanceId, preferences: contextPreferences} = useThunderID(); + const {baseUrl, endpoints, instanceId, preferences: contextPreferences, reauthenticate} = useThunderID(); + const pendingStepUp: PendingStepUp = {}; + // Whether the component is still on screen, so a change is not sent after it has closed. + let active = true; + + onUnmounted((): void => { + active = false; + }); const {flattenedProfile, profile, onUpdateProfile, updateProfile, userSchema} = useUser(); const {t} = useI18n(); @@ -126,17 +151,28 @@ const UserProfile: Component = defineComponent({ if (!baseUrl) return; - const response: User = await updateMeProfile({ - baseUrl, - url: resolveResourceEndpoint('usersMe', {endpoints}), - instanceId, - payload: updatedAttributes, + const response: User = await runWithStepUp({ + onReauthenticationRequired: props.onReauthenticationRequired, + isActive: (): boolean => active, + pending: pendingStepUp, + reauthenticate, + send: () => + updateMeProfile({ + baseUrl, + url: resolveResourceEndpoint('usersMe', {endpoints}), + instanceId, + payload: updatedAttributes, + }), }); onUpdateProfile(response); } catch (caughtError: unknown) { let message: string = t('user.profile.update.generic.error') || 'Failed to update profile. Please try again.'; - if (caughtError instanceof ThunderIDError) { + if (caughtError instanceof ThunderIDRuntimeError && caughtError.code === REAUTHENTICATION_FAILED) { + message = t(mapReauthenticationError((caughtError.details as {cause?: unknown} | undefined)?.cause)); + } else if (caughtError instanceof StepUpRequiredError) { + message = t('user.reauthentication.required.error'); + } else if (caughtError instanceof ThunderIDError) { message = caughtError.message; } diff --git a/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.css.ts b/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.css.ts new file mode 100644 index 00000000..8783ca20 --- /dev/null +++ b/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.css.ts @@ -0,0 +1,47 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/** + * Styles for the dialog that signs the user in again. + * + * BEM block: `.thunderid-reauthentication` + */ +const REAUTHENTICATION_CSS = ` +.thunderid-reauthentication__overlay { + position: fixed; + inset: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + background-color: rgba(0, 0, 0, 0.45); +} + +.thunderid-reauthentication__dialog { + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: var(--thunderid-spacing-unit); + width: min(480px, calc(100vw - calc(var(--thunderid-spacing-unit) * 4))); + max-height: 90vh; + overflow-y: auto; + padding: calc(var(--thunderid-spacing-unit) * 2); + background: var(--thunderid-color-background-surface); + border-radius: var(--thunderid-border-radius-large); + box-shadow: var(--thunderid-shadow-large); + font-family: var(--thunderid-typography-fontFamily); + outline: none; +} + +.thunderid-reauthentication__header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.thunderid-reauthentication__dialog .thunderid-signin { + min-width: 0; +} +`; + +export default REAUTHENTICATION_CSS; diff --git a/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.ts b/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.ts new file mode 100644 index 00000000..e1709634 --- /dev/null +++ b/packages/vue/src/components/auth/reauthentication/ReauthenticationDialog.ts @@ -0,0 +1,349 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + EmbeddedFlowComponent, + EmbeddedSignInFlowRequest, + EmbeddedSignInFlowResponse, + EmbeddedSignInFlowStatus, + EmbeddedSignInFlowType, + FieldError, + ReauthenticationOptions, + ThunderIDRuntimeError, + withVendorCSSClassPrefix, +} from '@thunderid/browser'; +import { + type Component, + type PropType, + type Ref, + type VNode, + Teleport, + defineComponent, + h, + nextTick, + onMounted, + onUnmounted, + ref, +} from 'vue'; +import useFlowMeta from '../../../composables/useFlowMeta'; +import useI18n from '../../../composables/useI18n'; +import {extractErrorMessage, normalizeFlowResponse} from '../../../utils/flowTransformer'; +import {handlePasskeyAuthentication} from '../../../utils/passkey'; +import Button from '../../primitives/Button/Button'; +import Typography from '../../primitives/Typography/Typography'; +import BaseSignIn from '../sign-in/BaseSignIn'; + +interface FlowStep { + additionalData: Record; + challengeToken?: string; + components: EmbeddedFlowComponent[]; + executionId: string; +} + +type Execute = ( + payload: EmbeddedSignInFlowRequest, + options: ReauthenticationOptions, +) => Promise; + +/** + * Signs the signed-in user in again in a dialog, by running the sign-in flow with `maxAge`, for a + * session from an embedded sign-in flow. The provider shows it from `reauthenticate`. Each step is + * drawn with `BaseSignIn`; a passkey step asks the browser for the passkey. A sign-in option that + * leaves the page, such as a federated sign-in, is not offered here: the user is told to choose + * another one; a flow that offers nothing else fails with `VUE-REAUTHENTICATION-UO01`. A flow that cannot + * go on starts again once with its message shown; when the new one cannot go on either, the re-sign-in + * fails with `VUE-REAUTHENTICATION-FE01`. + * + * @internal + */ +const ReauthenticationDialog: Component = defineComponent({ + name: 'ReauthenticationDialog', + props: { + /** Runs a step of the re-sign-in flow, as the client's `executeReauthenticationFlow` does. */ + execute: {required: true, type: Function as PropType}, + /** How recent, in seconds, the sign-in must be. */ + maxAge: {default: undefined, type: Number}, + /** Called when the user closes the dialog. */ + onCancel: {required: true, type: Function as PropType<() => void>}, + /** Called once the flow has completed and the session holds its tokens. */ + onComplete: {required: true, type: Function as PropType<() => void>}, + /** Called when the flow cannot go on, such as when a different user signed in. */ + onError: {required: true, type: Function as PropType<(error: unknown) => void>}, + }, + setup(props: { + execute: Execute; + maxAge?: number; + onCancel: () => void; + onComplete: () => void; + onError: (error: unknown) => void; + }) { + const {t} = useI18n(); + const {meta} = useFlowMeta(); + const px: typeof withVendorCSSClassPrefix = withVendorCSSClassPrefix; + const step: Ref = ref(null); + const error: Ref = ref(null); + const serverFieldErrors: Ref = ref(null); + const dialogRef: Ref = ref(null); + + const run = (payload: EmbeddedSignInFlowRequest): Promise => + props.execute(payload, {maxAge: props.maxAge}); + + const start = async (): Promise => { + await apply(await run({}), true); + }; + + // Starts the flow again after one that cannot go on, keeping the message on screen. A new flow that + // cannot go on either ends the re-sign-in, so the dialog never loops. + const restart = async (message: string, isStart: boolean): Promise => { + if (isStart) { + props.onError(new ThunderIDRuntimeError(message, 'VUE-REAUTHENTICATION-FE01', 'vue')); + + return; + } + + await start(); + error.value = new Error(message); + }; + + const apply = async (response: EmbeddedSignInFlowResponse, isStart: boolean): Promise => { + if (response.flowStatus === EmbeddedSignInFlowStatus.Complete) { + props.onComplete(); + + return; + } + + if (response.type === EmbeddedSignInFlowType.Redirection) { + if (isStart) { + props.onError( + new ThunderIDRuntimeError( + 'The sign-in flow offers only a sign-in option that leaves the page.', + 'VUE-REAUTHENTICATION-UO01', + 'vue', + ), + ); + + return; + } + + // The redirect would lose the change waiting to be saved, so the flow starts again. + await restart(t('user.reauthentication.unsupported_option.error'), false); + + return; + } + + const additionalData: Record = + (response.data?.additionalData as Record | undefined) ?? {}; + const passkeyChallenge: unknown = additionalData['passkeyChallenge']; + + if (typeof passkeyChallenge === 'string' && response.executionId) { + let credential: { + id: string; + response: {authenticatorData: string; clientDataJSON: string; signature: string; userHandle: string}; + }; + + try { + credential = JSON.parse(await handlePasskeyAuthentication(passkeyChallenge)) as typeof credential; + } catch { + // The user cancelled the passkey prompt, or the browser refused it. + await restart(t('user.reauthentication.failed.error'), isStart); + + return; + } + + step.value = null; + + await apply( + await run({ + executionId: response.executionId, + inputs: { + authenticatorData: credential.response.authenticatorData, + clientDataJSON: credential.response.clientDataJSON, + credentialId: credential.id, + signature: credential.response.signature, + userHandle: credential.response.userHandle, + }, + ...(response.challengeToken ? {challengeToken: response.challengeToken} : {}), + }), + false, + ); + + return; + } + + // A flow that ended, or an error with no step left to show, such as a failed passkey, starts again. + if ( + response.flowStatus === EmbeddedSignInFlowStatus.Error && + (!response.executionId || !step.value?.components.length) + ) { + await restart(extractErrorMessage(response, t), isStart); + + return; + } + + const normalized: {additionalData: Record; components: EmbeddedFlowComponent[]} = + response.flowStatus === EmbeddedSignInFlowStatus.Error + ? {additionalData: step.value?.additionalData ?? {}, components: step.value?.components ?? []} + : normalizeFlowResponse(response, t, {resolveTranslations: false}, meta.value); + + step.value = { + additionalData: normalized.additionalData, + challengeToken: response.challengeToken, + components: normalized.components, + executionId: response.executionId, + }; + + const fieldErrors: FieldError[] | undefined = (response.data as {fieldErrors?: FieldError[]} | undefined) + ?.fieldErrors; + + if (fieldErrors && fieldErrors.length > 0) { + serverFieldErrors.value = fieldErrors; + } + + if (response.error || response.flowStatus === EmbeddedSignInFlowStatus.Error) { + error.value = new Error(extractErrorMessage(response, t)); + } + }; + + const submit = async (payload: EmbeddedSignInFlowRequest): Promise => { + const current: FlowStep | null = step.value; + + if (!current) { + return; + } + + error.value = null; + serverFieldErrors.value = null; + + try { + await apply( + await run({ + ...payload, + executionId: current.executionId, + ...(current.challengeToken ? {challengeToken: current.challengeToken} : {}), + }), + false, + ); + } catch (caughtError: unknown) { + props.onError(caughtError); + } + }; + + // Each dialog gets its own heading and description ids, and focus goes back where it was when the + // dialog closes. + const idSuffix: string = Math.random().toString(36).slice(2, 10); + const headingId = `${px('reauthentication')}-heading-${idSuffix}`; + const descriptionId = `${px('reauthentication')}-description-${idSuffix}`; + let previousFocus: HTMLElement | null = null; + + // Listens on the document, since a new flow step can remove the focused control: Escape closes the + // dialog, and Tab and Shift+Tab stay inside it. + const handleKeydown = (event: KeyboardEvent): void => { + if (event.key === 'Escape') { + event.stopPropagation(); + props.onCancel(); + + return; + } + + if (event.key !== 'Tab' || !dialogRef.value) return; + + const focusables: HTMLElement[] = Array.from( + dialogRef.value.querySelectorAll( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', + ), + ); + + if (focusables.length === 0) return; + + const first: HTMLElement = focusables[0]; + const last: HTMLElement = focusables[focusables.length - 1]; + const inside: boolean = dialogRef.value.contains(document.activeElement); + + if ( + event.shiftKey && + (!inside || document.activeElement === first || document.activeElement === dialogRef.value) + ) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && (!inside || document.activeElement === last)) { + event.preventDefault(); + first.focus(); + } + }; + + // Brings focus back into the dialog when it moves to the page behind it. + const handleFocusIn = (event: FocusEvent): void => { + if (dialogRef.value && event.target instanceof Node && !dialogRef.value.contains(event.target)) { + dialogRef.value.focus(); + } + }; + + onUnmounted((): void => { + document.removeEventListener('keydown', handleKeydown, true); + document.removeEventListener('focusin', handleFocusIn); + previousFocus?.focus(); + }); + + onMounted((): void => { + previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + document.addEventListener('keydown', handleKeydown, true); + document.addEventListener('focusin', handleFocusIn); + void nextTick((): void => dialogRef.value?.focus()); + start().catch(props.onError); + }); + + return (): VNode => + h(Teleport, {to: 'body'}, [ + h( + 'div', + { + class: px('reauthentication__overlay'), + onClick: (event: MouseEvent): void => { + if (event.target === event.currentTarget) props.onCancel(); + }, + }, + [ + h( + 'div', + { + 'aria-describedby': descriptionId, + 'aria-labelledby': headingId, + 'aria-modal': 'true', + class: px('reauthentication__dialog'), + ref: dialogRef, + role: 'dialog', + tabindex: -1, + }, + [ + h('div', {class: px('reauthentication__header')}, [ + h(Typography, {id: headingId, variant: 'h6'}, () => t('user.reauthentication.heading')), + h( + Button, + { + 'aria-label': t('user.reauthentication.buttons.close.text'), + onClick: (): void => props.onCancel(), + size: 'small', + variant: 'text', + }, + () => '×', + ), + ]), + h(Typography, {id: descriptionId, variant: 'body2'}, () => t('user.reauthentication.description')), + h(BaseSignIn, { + additionalData: step.value?.additionalData ?? {}, + components: step.value?.components ?? [], + error: error.value, + isLoading: !step.value, + onSubmit: submit, + serverFieldErrors: serverFieldErrors.value, + variant: 'flat', + }), + ], + ), + ], + ), + ]); + }, +}); + +export default ReauthenticationDialog; diff --git a/packages/vue/src/components/primitives/PasswordField/PasswordField.css.ts b/packages/vue/src/components/primitives/PasswordField/PasswordField.css.ts index 0d095eb1..cc981152 100644 --- a/packages/vue/src/components/primitives/PasswordField/PasswordField.css.ts +++ b/packages/vue/src/components/primitives/PasswordField/PasswordField.css.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 /** @@ -107,6 +107,12 @@ const PASSWORD_FIELD_CSS = ` color: var(--thunderid-color-error-contrastText); line-height: var(--thunderid-typography-lineHeight-normal); } + +.thunderid-password-field__helper { + font-size: var(--thunderid-typography-fontSize-xs); + color: var(--thunderid-color-text-secondary); + line-height: var(--thunderid-typography-lineHeight-normal); +} `; export default PASSWORD_FIELD_CSS; diff --git a/packages/vue/src/components/primitives/PasswordField/PasswordField.ts b/packages/vue/src/components/primitives/PasswordField/PasswordField.ts index 6a09d0b5..b9a7bf78 100644 --- a/packages/vue/src/components/primitives/PasswordField/PasswordField.ts +++ b/packages/vue/src/components/primitives/PasswordField/PasswordField.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {withVendorCSSClassPrefix} from '@thunderid/browser'; @@ -10,6 +10,7 @@ type PasswordFieldProps = Readonly<{ autocomplete: string; disabled: boolean; error: string | undefined; + helperText: string | undefined; hideLabel: string; label: string | undefined; modelValue: string; @@ -37,6 +38,8 @@ const PasswordField: Component = defineComponent({ autocomplete: {default: 'current-password', type: String}, disabled: {default: false, type: Boolean}, error: {default: undefined, type: String}, + /** Text shown under the field while it has no error. */ + helperText: {default: undefined, type: String}, /** Accessible name of the toggle button while the password is visible. */ hideLabel: {default: 'Hide password', type: String}, label: {default: undefined, type: String}, @@ -55,6 +58,9 @@ const PasswordField: Component = defineComponent({ return (): VNode => { const hasError = !!props.error; + // The error or hint below the input describes it, for assistive technology. + const describedById: string | undefined = + props.name && (hasError || props.helperText) ? `${props.name}-description` : undefined; const wrapperClass: string = [ withVendorCSSClassPrefix('password-field'), hasError ? withVendorCSSClassPrefix('password-field--error') : '', @@ -79,6 +85,8 @@ const PasswordField: Component = defineComponent({ : null, h('div', {class: withVendorCSSClassPrefix('password-field__wrapper')}, [ h('input', { + 'aria-describedby': describedById, + 'aria-invalid': hasError || undefined, 'aria-label': props.ariaLabel, autocomplete: props.autocomplete, class: withVendorCSSClassPrefix('password-field__input'), @@ -109,7 +117,12 @@ const PasswordField: Component = defineComponent({ ), slots['append']?.(), ]), - hasError ? h('span', {class: withVendorCSSClassPrefix('password-field__error')}, props.error) : null, + hasError + ? h('span', {class: withVendorCSSClassPrefix('password-field__error'), id: describedById}, props.error) + : null, + !hasError && props.helperText + ? h('span', {class: withVendorCSSClassPrefix('password-field__helper'), id: describedById}, props.helperText) + : null, ]); }; }, diff --git a/packages/vue/src/models/contexts.ts b/packages/vue/src/models/contexts.ts index ec5586d9..a15a52b5 100644 --- a/packages/vue/src/models/contexts.ts +++ b/packages/vue/src/models/contexts.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import type { @@ -7,6 +7,7 @@ import type { AttributeSchema, CurrentOrganizationUnit, Project, + ReauthenticationOptions, SwitchOrganizationUnitOptions, FlowMetadataResponse, HttpRequestConfig, @@ -90,6 +91,15 @@ export interface ThunderIDContext { organizationUnitId: string, options?: SwitchOrganizationUnitOptions, ) => Promise; + /** + * Signs the signed-in user in again, for a change that needs a recent sign-in, and replaces the + * session's tokens only when the same user signed in. Pass the `maxAge` of the `StepUpRequiredError` + * the change failed with, then retry the change once. A session from a redirect sign-in signs in again + * in a popup, so call it from a user action. A session from an embedded sign-in flow runs the sign-in + * flow again in a dialog the provider shows. It rejects when the user cancels, the sign-in fails, or a + * different user signs in, and the session is then left as it was. + */ + reauthenticate: (options?: ReauthenticationOptions) => Promise; // ── HTTP ── http: { /** diff --git a/packages/vue/src/providers/ThunderIDProvider.ts b/packages/vue/src/providers/ThunderIDProvider.ts index cfa0bd82..c7af46bd 100644 --- a/packages/vue/src/providers/ThunderIDProvider.ts +++ b/packages/vue/src/providers/ThunderIDProvider.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 import {createResourceInvalidator} from '@thunderid/browser'; @@ -6,6 +6,9 @@ import { type ApiFetcher, AttributeSchema, type CurrentOrganizationUnit, + type EmbeddedSignInFlowRequest, + type ReauthenticationMethod, + type ReauthenticationOptions, type SwitchOrganizationUnitOptions, ThunderIDAPIError, ThunderIDRuntimeError, @@ -50,6 +53,7 @@ import ThemeProvider from './ThemeProvider'; import UserProvider from './UserProvider'; import getUsersMe from '../api/account/getUsersMe'; import getUsersMeMeta from '../api/account/getUsersMeMeta'; +import ReauthenticationDialog from '../components/auth/reauthentication/ReauthenticationDialog'; import useCurrentProjectState, {type CurrentProjectState} from '../composables/useCurrentProjectState'; import {THUNDERID_KEY} from '../keys'; import type {ThunderIDVueConfig} from '../models/config'; @@ -220,6 +224,15 @@ const ThunderIDProvider: Component = defineComponent({ const isLoading: Ref = ref(true); const user: ShallowRef = shallowRef(null); const userProfile: ShallowRef = shallowRef(null); + // How the user signs in again, kept current with the session so `reauthenticate` can open a popup at once. + let reauthenticationMethod: ReauthenticationMethod | null = null; + // A re-sign-in the provider's dialog is running for `reauthenticate`. + const reauthenticationRequest: ShallowRef<{ + id: number; + options: ReauthenticationOptions; + reject: (reason: unknown) => void; + resolve: () => void; + } | null> = shallowRef(null); const userSchema: Ref | null> = ref | null>(null); const currentOrganizationUnit: ShallowRef = shallowRef(null); @@ -262,6 +275,7 @@ const ThunderIDProvider: Component = defineComponent({ let baseUrl: string = resolvedBaseUrl.value; const decodedToken: IdToken = await client.getDecodedIdToken(); + reauthenticationMethod = await client.getReauthenticationMethod(); if (decodedToken?.['user_org']) { baseUrl = `${resolveRequestBaseUrl(await client.getConfiguration()) ?? ''}/o`; @@ -397,6 +411,68 @@ const ThunderIDProvider: Component = defineComponent({ return switched; } + // ── Sign In Again ── + // The client leaves the session as it was when the re-sign-in fails, so the state is only refreshed on success. + async function reauthenticate(options?: ReauthenticationOptions): Promise { + // Read without an await first, so the popup still opens inside the user action. + if (reauthenticationMethod !== 'flow') { + try { + await client.reauthenticate(options); + await updateSession(); + + return; + } catch (error) { + if ((error as {code?: string})?.code !== 'BROWSER-REAUTHENTICATION-UM02') { + throw error; + } + } + } + + await new Promise((resolve: () => void, reject: (reason: unknown) => void): void => { + const previous: typeof reauthenticationRequest.value = reauthenticationRequest.value; + + reauthenticationRequest.value = {id: (previous?.id ?? 0) + 1, options: options ?? {}, reject, resolve}; + // One re-sign-in at a time: a new one replaces the one still open. + previous?.reject( + new ThunderIDRuntimeError('Another sign-in replaced this one.', 'VUE-REAUTHENTICATION-SU01', 'vue'), + ); + }); + await updateSession(); + } + + function renderReauthenticationDialog(): VNode | null { + const request: typeof reauthenticationRequest.value = reauthenticationRequest.value; + + if (!request) { + return null; + } + + const settle = (): void => { + if (reauthenticationRequest.value === request) { + reauthenticationRequest.value = null; + } + }; + + return h(ReauthenticationDialog, { + key: request.id, + execute: (payload: EmbeddedSignInFlowRequest, flowOptions: ReauthenticationOptions) => + client.executeReauthenticationFlow(payload, flowOptions), + maxAge: request.options.maxAge, + onCancel: (): void => { + settle(); + request.reject(new ThunderIDRuntimeError('The user closed the sign-in.', 'VUE-REAUTHENTICATION-CN01', 'vue')); + }, + onComplete: (): void => { + settle(); + request.resolve(); + }, + onError: (error: unknown): void => { + settle(); + request.reject(error); + }, + }); + } + // ── Provide Context ── const context: ThunderIDContext = { afterSignInUrl: props.afterSignInUrl, @@ -419,6 +495,7 @@ const ThunderIDProvider: Component = defineComponent({ setCurrentProject: projectState.setCurrentProject, getCurrentOrganizationUnit: (): Promise => client.getCurrentOrganizationUnit(), switchOrganizationUnit, + reauthenticate, http: { fetcher: props.http?.fetcher, request: (requestConfig?: any): Promise> => client.request(requestConfig), @@ -587,6 +664,10 @@ const ThunderIDProvider: Component = defineComponent({ }); onUnmounted((): void => { + reauthenticationRequest.value?.reject( + new ThunderIDRuntimeError('The sign-in ended before it completed.', 'VUE-REAUTHENTICATION-CN01', 'vue'), + ); + reauthenticationRequest.value = null; if (appContext && providesAtAppLevel && appContext.provides[THUNDERID_KEY as symbol] === context) { delete appContext.provides[THUNDERID_KEY as symbol]; } @@ -631,7 +712,7 @@ const ThunderIDProvider: Component = defineComponent({ userSchema: userSchema.value, }, { - default: (): any => slots['default']?.(), + default: (): any => [slots['default']?.(), renderReauthenticationDialog()], }, ), }), diff --git a/packages/vue/src/styles/injectStyles.ts b/packages/vue/src/styles/injectStyles.ts index 3d9d2318..168933fe 100644 --- a/packages/vue/src/styles/injectStyles.ts +++ b/packages/vue/src/styles/injectStyles.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 /** @@ -33,6 +33,7 @@ import ADMIN_CSS from '../components/management/shared/Admin.css'; import BASE_DEVICE_GRANT_CSS from '../components/auth/device-grant/BaseDeviceGrant.css'; import CONSENT_CSS from '../components/auth/flow/Consent.css'; import FLOW_EXPIRED_CSS from '../components/auth/flow/FlowExpired.css'; +import REAUTHENTICATION_CSS from '../components/auth/reauthentication/ReauthenticationDialog.css'; import BASE_SIGN_IN_CSS from '../components/auth/sign-in/BaseSignIn.css'; import ATTRIBUTION_CSS from '../components/common/attribution/Attribution.css'; import LANGUAGE_SWITCHER_CSS from '../components/common/language-switcher/LanguageSwitcher.css'; @@ -83,6 +84,7 @@ const STYLES: string = [ DATA_TABLE_CSS, // Auth BASE_SIGN_IN_CSS, + REAUTHENTICATION_CSS, CONSENT_CSS, FLOW_EXPIRED_CSS, BASE_DEVICE_GRANT_CSS, diff --git a/playgrounds/node/src/catalog.ts b/playgrounds/node/src/catalog.ts index 4440a69e..ba66d99d 100644 --- a/playgrounds/node/src/catalog.ts +++ b/playgrounds/node/src/catalog.ts @@ -454,10 +454,10 @@ const operations: OperationSpec[] = [ summary: 'Run a SELF flow step.', }, { - args: json({password: ''}), + args: json({currentValue: '', name: 'password', newValue: ''}), call: 'client.updateUserCredentials(payload, sessionId)', description: - 'Updates credentials of the signed-in user, such as password, through the /users/me credentials endpoint. Running it changes your real credentials.', + 'Sets one credential of the signed-in user, such as password, through the /users/me credentials endpoint. Give currentValue when the user holds the credential. Running it changes your real credentials.', group: 'Management API', id: 'updateUserCredentials', network: true, @@ -465,7 +465,7 @@ const operations: OperationSpec[] = [ regions: ['updateUserCredentials'], returns: 'Promise', session: true, - summary: 'Update own credentials.', + summary: 'Update an own credential.', }, management( 'listGroups', diff --git a/playgrounds/node/src/operations.ts b/playgrounds/node/src/operations.ts index e94f5b52..920d8a69 100644 --- a/playgrounds/node/src/operations.ts +++ b/playgrounds/node/src/operations.ts @@ -13,6 +13,7 @@ import { type ExtendedAuthorizeRequestUrlParams, type ManagementListOptions, type RoleAssigneeType, + type UpdateMeCredentialsPayload, type ThunderIDNodeClient, type TokenExchangeRequestConfig, } from '@thunderid/node'; @@ -200,8 +201,9 @@ const executeEmbeddedSelfFlow: Runner = ({args, client, sessionId}) => // #region updateUserCredentials const updateUserCredentials: Runner = async ({args, client, sessionId}) => { - await client.updateUserCredentials(args as Record, sessionId); - return {updated: Object.keys(args as Record)}; + const payload = args as UpdateMeCredentialsPayload; + await client.updateUserCredentials(payload, sessionId); + return {updated: payload.name}; }; // #endregion diff --git a/playgrounds/vue/src/pages/explorer/stories.ts b/playgrounds/vue/src/pages/explorer/stories.ts index 5e98155f..9e877fab 100644 --- a/playgrounds/vue/src/pages/explorer/stories.ts +++ b/playgrounds/vue/src/pages/explorer/stories.ts @@ -939,7 +939,9 @@ export const COMPONENTS: ComponentDef[] = [ } : { imports: ['BaseChangeCredential'], - script: ['const handleSubmit = ({newPassword}: {newPassword: string}): void => {};'], + script: [ + 'const handleSubmit = ({currentPassword, newPassword}: {currentPassword: string; newPassword: string}): void => {};', + ], template: tpl('BaseChangeCredential', omit(args, 'source'), { defaults: {showRequirements: true}, extra: ['@submit="handleSubmit"'], diff --git a/tests/e2e/pages/thunderid-web-sample.page.ts b/tests/e2e/pages/thunderid-web-sample.page.ts index c63bc9cb..05db23e4 100644 --- a/tests/e2e/pages/thunderid-web-sample.page.ts +++ b/tests/e2e/pages/thunderid-web-sample.page.ts @@ -1,4 +1,4 @@ -// Copyright 2025 The ThunderID Authors +// Copyright 2025-2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 /** @@ -219,9 +219,12 @@ export class ThunderIDAccountPageSamplePage extends ThunderIDWebSamplePage { await this.page.getByRole('button', {name: cta}).click(); } - /** Fills the currently-open credential form's new-value and confirmation fields, without - * submitting. */ - async fillCredentialFields(newValue: string, confirmValue: string): Promise { + /** Fills the currently-open credential form's new-value and confirmation fields, and the + * current value when one is given, without submitting. */ + async fillCredentialFields(newValue: string, confirmValue: string, currentValue?: string): Promise { + if (currentValue !== undefined) { + await this.page.locator('input[name="currentPassword"]').fill(currentValue); + } await this.page.locator('input[name="newPassword"]').fill(newValue); await this.page.locator('input[name="confirmPassword"]').fill(confirmValue); } @@ -231,12 +234,12 @@ export class ThunderIDAccountPageSamplePage extends ThunderIDWebSamplePage { return this.page.getByRole('button', {name: /^Update /}).isDisabled(); } - /** Expands the named credential's row, fills the new value and its confirmation, and - * submits. Waits for the row to collapse back afterward — `ChangeCredential`'s `onSuccess` + /** Expands the named credential's row, fills the current value, the new value and its + * confirmation, and submits. Waits for the row to collapse back afterward — `ChangeCredential`'s `onSuccess` * closes it in this sample, so that collapse is this method's proof the write actually * succeeded server-side rather than just that the button was clicked. Call * {@link openSecurityTab} first. */ - async changeCredential(cta: string, newValue: string): Promise { + async changeCredential(cta: string, currentValue: string, newValue: string): Promise { const toggle = this.page.getByRole('button', {name: cta}); // Bounded wait before the click: if the caller's page state doesn't actually have this row // (e.g. the Security tab isn't open), fail fast with a clear "not visible" error instead of @@ -245,7 +248,7 @@ export class ThunderIDAccountPageSamplePage extends ThunderIDWebSamplePage { await expect(toggle).toBeVisible({timeout: Timeouts.ELEMENT_VISIBILITY}); await toggle.click(); - await this.fillCredentialFields(newValue, newValue); + await this.fillCredentialFields(newValue, newValue, currentValue); await this.page.getByRole('button', {name: /^Update /}).click(); await expect(toggle).toHaveAttribute('aria-expanded', 'false', {timeout: Timeouts.ELEMENT_VISIBILITY}); diff --git a/tests/e2e/tests/nextjs-quickstart/change-credential.spec.ts b/tests/e2e/tests/nextjs-quickstart/change-credential.spec.ts index 1db45531..b0bb20a9 100644 --- a/tests/e2e/tests/nextjs-quickstart/change-credential.spec.ts +++ b/tests/e2e/tests/nextjs-quickstart/change-credential.spec.ts @@ -50,7 +50,7 @@ test.describe('nextjs/quickstart - Change credential', () => { await nextjsQuickstartPage.openSecurityTab(); try { - await nextjsQuickstartPage.changeCredential('Change password', tempPassword); + await nextjsQuickstartPage.changeCredential('Change password', password, tempPassword); // Prove the change landed server-side, not just that the UI collapsed the form: sign // out and back in using the new password. @@ -78,7 +78,7 @@ test.describe('nextjs/quickstart - Change credential', () => { await nextjsQuickstartPage.verifyLoggedIn(); } await nextjsQuickstartPage.openSecurityTab(); - await nextjsQuickstartPage.changeCredential('Change password', password); + await nextjsQuickstartPage.changeCredential('Change password', tempPassword, password); } // The restore itself also has to have actually worked, or the next test to sign in with diff --git a/tests/e2e/tests/nuxt-quickstart/change-credential.spec.ts b/tests/e2e/tests/nuxt-quickstart/change-credential.spec.ts index 7a421a8e..a567a1d3 100644 --- a/tests/e2e/tests/nuxt-quickstart/change-credential.spec.ts +++ b/tests/e2e/tests/nuxt-quickstart/change-credential.spec.ts @@ -49,7 +49,7 @@ test.describe('nuxt/quickstart - Change credential', () => { await nuxtQuickstartPage.openSecurityTab(); try { - await nuxtQuickstartPage.changeCredential('Change password', tempPassword); + await nuxtQuickstartPage.changeCredential('Change password', password, tempPassword); // Prove the change landed server-side, not just that the UI collapsed the form: sign // out and back in using the new password. @@ -77,7 +77,7 @@ test.describe('nuxt/quickstart - Change credential', () => { await nuxtQuickstartPage.verifyLoggedIn(); } await nuxtQuickstartPage.openSecurityTab(); - await nuxtQuickstartPage.changeCredential('Change password', password); + await nuxtQuickstartPage.changeCredential('Change password', tempPassword, password); } // The restore itself also has to have actually worked, or the next test to sign in with diff --git a/tests/e2e/tests/react-quickstart/change-credential.spec.ts b/tests/e2e/tests/react-quickstart/change-credential.spec.ts index 9694477f..de1d7c4c 100644 --- a/tests/e2e/tests/react-quickstart/change-credential.spec.ts +++ b/tests/e2e/tests/react-quickstart/change-credential.spec.ts @@ -42,7 +42,7 @@ test.describe('react/quickstart - Change credential', () => { await reactQuickstartPage.openSecurityTab(); try { - await reactQuickstartPage.changeCredential('Change password', tempPassword); + await reactQuickstartPage.changeCredential('Change password', password, tempPassword); // Prove the change landed server-side, not just that the UI collapsed the form: sign // out and back in using the new password. @@ -58,7 +58,7 @@ test.describe('react/quickstart - Change credential', () => { } finally { // Always attempt to restore the shared test user's original password, even if an // assertion above failed. - await reactQuickstartPage.changeCredential('Change password', password); + await reactQuickstartPage.changeCredential('Change password', tempPassword, password); } // The restore itself also has to have actually worked, or the next test to sign in with diff --git a/tests/e2e/tests/vue-quickstart/change-credential.spec.ts b/tests/e2e/tests/vue-quickstart/change-credential.spec.ts index 79bb9108..8f8931c7 100644 --- a/tests/e2e/tests/vue-quickstart/change-credential.spec.ts +++ b/tests/e2e/tests/vue-quickstart/change-credential.spec.ts @@ -42,7 +42,7 @@ test.describe('vue/quickstart - Change credential', () => { await vueQuickstartPage.openSecurityTab(); try { - await vueQuickstartPage.changeCredential('Change password', tempPassword); + await vueQuickstartPage.changeCredential('Change password', password, tempPassword); // Prove the change landed server-side, not just that the UI collapsed the form: sign // out and back in using the new password. @@ -58,7 +58,7 @@ test.describe('vue/quickstart - Change credential', () => { } finally { // Always attempt to restore the shared test user's original password, even if an // assertion above failed. - await vueQuickstartPage.changeCredential('Change password', password); + await vueQuickstartPage.changeCredential('Change password', tempPassword, password); } // The restore itself also has to have actually worked, or the next test to sign in with