diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.ts index 07e059ff..76960246 100644 --- a/packages/browser/src/index.ts +++ b/packages/browser/src/index.ts @@ -36,6 +36,7 @@ export {default as AuthenticationHelper} from './utils/AuthenticationHelper'; export {default as hasAuthParamsInUrl} from './utils/hasAuthParamsInUrl'; export {default as hasCalledForThisInstanceInUrl} from './utils/hasCalledForThisInstanceInUrl'; export {default as navigate} from './utils/navigate'; +export {default as replaceLocation} from './utils/replaceLocation'; export {default as http} from './utils/http'; export {default as createHttpClientFetcher} from './utils/createHttpClientFetcher'; export {default as copyTextToClipboard} from './utils/copyTextToClipboard'; diff --git a/packages/browser/src/utils/replaceLocation.ts b/packages/browser/src/utils/replaceLocation.ts new file mode 100644 index 00000000..4a1b0de1 --- /dev/null +++ b/packages/browser/src/utils/replaceLocation.ts @@ -0,0 +1,14 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/** + * Loads the given URL in place of the current page, without leaving the current page in the history. Unlike + * {@link navigate}, it always loads the page, even on the same origin. + * + * @param url - The URL to load. + */ +const replaceLocation = (url: string): void => { + window.location.replace(url); +}; + +export default replaceLocation; diff --git a/packages/javascript/src/api/auth/__tests__/getFlowMeta.test.ts b/packages/javascript/src/api/auth/__tests__/getFlowMeta.test.ts index ecf6d1e8..668acfec 100644 --- a/packages/javascript/src/api/auth/__tests__/getFlowMeta.test.ts +++ b/packages/javascript/src/api/auth/__tests__/getFlowMeta.test.ts @@ -3,6 +3,7 @@ import {afterEach, describe, expect, it, vi} from 'vitest'; import ThunderIDAPIError from '../../../errors/ThunderIDAPIError'; +import {FlowMetaType} from '../../../models/flow-meta'; import isFlowMetaUnavailableError from '../../../utils/isFlowMetaUnavailableError'; import getFlowMeta from '../getFlowMeta'; @@ -24,6 +25,17 @@ describe('getFlowMeta', () => { ); }); + it('passes a reference as the id of a REF request', async () => { + global.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), {status: 200})); + + await getFlowMeta({baseUrl: 'https://localhost:8090', id: '~bXktYXBw', type: FlowMetaType.Ref}); + + expect(global.fetch).toHaveBeenCalledWith( + 'https://localhost:8090/flow/meta?id=%7EbXktYXBw&type=REF', + expect.objectContaining({method: 'GET'}), + ); + }); + it('rejects with an API error carrying the status when the server answers with an error', async () => { global.fetch = vi.fn().mockResolvedValue(new Response('Not Found', {status: 404})); diff --git a/packages/javascript/src/api/auth/__tests__/resolveFlowReturnUrl.test.ts b/packages/javascript/src/api/auth/__tests__/resolveFlowReturnUrl.test.ts new file mode 100644 index 00000000..5718d9ec --- /dev/null +++ b/packages/javascript/src/api/auth/__tests__/resolveFlowReturnUrl.test.ts @@ -0,0 +1,115 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it, vi} from 'vitest'; +import {FlowMetadataResponse, FlowMetaType} from '../../../models/flow-meta'; +import resolveFlowReturnUrl from '../resolveFlowReturnUrl'; + +const PAGE = 'https://idp.example.com/gate/signin?ref=abc'; +const metaWith = (overrides: Partial): FlowMetadataResponse => + ({design: {}, i18n: {}, isRegistrationFlowEnabled: false, ...overrides}) as FlowMetadataResponse; + +describe('resolveFlowReturnUrl', () => { + it('uses the application URL from the loaded metadata without fetching', async () => { + const fetchMeta = vi.fn(); + + const target = await resolveFlowReturnUrl({ + currentUrl: PAGE, + fetchMeta, + meta: metaWith({application: {id: 'a1', name: 'Acme', url: 'https://acme.example.com'} as never}), + ref: 'abc', + }); + + expect(target).toEqual({applicationName: 'Acme', url: 'https://acme.example.com'}); + expect(fetchMeta).not.toHaveBeenCalled(); + }); + + it('looks the application up by ref', async () => { + const fetchMeta = vi + .fn() + .mockResolvedValue(metaWith({application: {id: 'a1', name: 'Acme', url: 'https://acme.example.com'} as never})); + + const target = await resolveFlowReturnUrl({currentUrl: PAGE, fetchMeta, ref: 'abc'}); + + expect(fetchMeta).toHaveBeenCalledWith({id: 'abc', type: FlowMetaType.Ref}); + expect(target.url).toBe('https://acme.example.com'); + }); + + it('falls back to the default return URL when the ref names no application', async () => { + const fetchMeta = vi + .fn() + .mockRejectedValueOnce(new Error('not found')) + .mockResolvedValueOnce(metaWith({defaultReturnUrl: 'https://home.example.com'})); + + const target = await resolveFlowReturnUrl({currentUrl: PAGE, fetchMeta, ref: 'bad'}); + + expect(fetchMeta).toHaveBeenLastCalledWith({}); + expect(target).toEqual({applicationName: undefined, url: 'https://home.example.com'}); + }); + + it('uses the default return URL from the loaded metadata without fetching', async () => { + const fetchMeta = vi.fn(); + + const target = await resolveFlowReturnUrl({ + currentUrl: PAGE, + fetchMeta, + meta: metaWith({defaultReturnUrl: 'https://home.example.com'}), + }); + + expect(target.url).toBe('https://home.example.com'); + expect(fetchMeta).not.toHaveBeenCalled(); + }); + + it('drops a return URL that points back to the sign-in page', async () => { + const fetchMeta = vi.fn().mockResolvedValue(metaWith({defaultReturnUrl: '/gate/signin'})); + + const target = await resolveFlowReturnUrl({currentUrl: PAGE, fetchMeta}); + + expect(target.url).toBeUndefined(); + }); + + it('does not fetch when the loaded metadata has neither URL', async () => { + const fetchMeta = vi.fn(); + + const target = await resolveFlowReturnUrl({ + currentUrl: PAGE, + fetchMeta, + meta: metaWith({application: {id: 'a1', name: 'Acme'} as never}), + }); + + expect(target).toEqual({applicationName: 'Acme', url: undefined}); + expect(fetchMeta).not.toHaveBeenCalled(); + }); + + it('falls back to the default when the application URL points back to the sign-in page', async () => { + const target = await resolveFlowReturnUrl({ + currentUrl: PAGE, + fetchMeta: vi.fn(), + meta: metaWith({ + application: {id: 'a1', name: 'Acme', url: 'https://idp.example.com/gate/signin'} as never, + defaultReturnUrl: 'https://home.example.com', + }), + }); + + expect(target.url).toBe('https://home.example.com'); + }); + + it('drops a return URL that is not http or https', async () => { + const target = await resolveFlowReturnUrl({ + currentUrl: PAGE, + fetchMeta: vi.fn(), + meta: metaWith({application: {id: 'a1', name: 'Acme', url: 'javascript:alert(1)'} as never}), + }); + + expect(target.url).toBeUndefined(); + }); + + it('resolves to no URL when every lookup fails', async () => { + const fetchMeta = vi.fn().mockRejectedValue(new Error('down')); + + await expect(resolveFlowReturnUrl({currentUrl: PAGE, fetchMeta, ref: 'abc'})).resolves.toEqual({ + applicationName: undefined, + url: undefined, + }); + }); +}); diff --git a/packages/javascript/src/api/auth/resolveFlowReturnUrl.ts b/packages/javascript/src/api/auth/resolveFlowReturnUrl.ts new file mode 100644 index 00000000..f233c25c --- /dev/null +++ b/packages/javascript/src/api/auth/resolveFlowReturnUrl.ts @@ -0,0 +1,100 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {FlowMetadataResponse, FlowMetaType} from '../../models/flow-meta'; +import logger from '../../utils/logger'; + +/** + * Where a sign-in page sends the user when its flow can't continue. + * + * @experimental This API may change in future versions + */ +export interface FlowReturnTarget { + /** Name of the application the user came from, when known. */ + applicationName?: string; + /** The application URL, else the server's default return URL. Undefined when there is neither. */ + url?: string; +} + +/** + * Configuration for {@link resolveFlowReturnUrl}. + * + * @experimental This API may change in future versions + */ +export interface ResolveFlowReturnUrlConfig { + /** URL of the sign-in page, so a return URL pointing back to it is dropped. */ + currentUrl: string; + /** Fetches flow metadata for a query. Resolves to `null` when there is none. */ + fetchMeta: (query: {id?: string; type?: FlowMetaType}) => Promise; + /** Flow metadata already loaded for the page, if any. */ + meta?: FlowMetadataResponse | null; + /** The `ref` query parameter of the sign-in page URL, if any. */ + ref?: string | null; +} + +/** + * Keeps a candidate return URL when it is an `http` or `https` URL that does not point back to the sign-in page + * itself, which would redirect in a loop. + */ +const toReturnUrl = (candidate: string | undefined, currentUrl: string): string | undefined => { + if (!candidate) { + return undefined; + } + try { + const target: URL = new URL(candidate, currentUrl); + const current: URL = new URL(currentUrl); + if (target.protocol !== 'http:' && target.protocol !== 'https:') { + return undefined; + } + return target.origin === current.origin && target.pathname === current.pathname ? undefined : candidate; + } catch { + return undefined; + } +}; + +/** + * Resolves where a sign-in page sends the user when its flow can't continue, such as a bookmarked or shared URL + * opened later. The application URL comes first, from the loaded metadata or from the `ref` URL parameter, then + * the server's default return URL. A lookup that fails counts as no answer, so this never rejects. + * + * @param config - The page URL, a metadata fetcher, the metadata already loaded and the `ref` parameter. + * @returns The return target, with `url` undefined when there is nowhere to go. + * + * @experimental This API may change in future versions + */ +const resolveFlowReturnUrl = async ({ + currentUrl, + fetchMeta, + meta = null, + ref = null, +}: ResolveFlowReturnUrlConfig): Promise => { + const load = async (query: {id?: string; type?: FlowMetaType}): Promise => { + try { + return await fetchMeta(query); + } catch (error) { + logger.warn('Could not load flow metadata to find where to send the user back to.', error); + return null; + } + }; + + let application: FlowMetadataResponse['application'] = meta?.application; + let defaultReturnUrl: string | undefined = meta?.defaultReturnUrl; + + if (!application?.url && ref) { + const refMeta: FlowMetadataResponse | null = await load({id: ref, type: FlowMetaType.Ref}); + application = refMeta?.application ?? application; + defaultReturnUrl = defaultReturnUrl ?? refMeta?.defaultReturnUrl; + } + + // Loaded metadata carries the default return URL whenever the server sets one, so only fetch it when none was given. + if (!application?.url && !defaultReturnUrl && !meta) { + defaultReturnUrl = (await load({}))?.defaultReturnUrl; + } + + return { + applicationName: application?.name, + url: toReturnUrl(application?.url, currentUrl) ?? toReturnUrl(defaultReturnUrl, currentUrl), + }; +}; + +export default resolveFlowReturnUrl; diff --git a/packages/javascript/src/index.ts b/packages/javascript/src/index.ts index 2bc74636..4f0af2e3 100644 --- a/packages/javascript/src/index.ts +++ b/packages/javascript/src/index.ts @@ -19,6 +19,8 @@ export type {EmbeddedUserOnboardingFlowResponse} from './api/auth/executeEmbedde export {default as executeEmbeddedSelfFlow} from './api/auth/executeEmbeddedSelfFlow'; export type {ExecuteEmbeddedSelfFlowConfig} from './api/auth/executeEmbeddedSelfFlow'; export {default as getFlowMeta} from './api/auth/getFlowMeta'; +export {default as resolveFlowReturnUrl} from './api/auth/resolveFlowReturnUrl'; +export type {FlowReturnTarget, ResolveFlowReturnUrlConfig} from './api/auth/resolveFlowReturnUrl'; export {default as getOrganizationUnitChildren} from './api/management/organization-units/getOrganizationUnitChildren'; export type {GetOrganizationUnitChildrenConfig} from './api/management/organization-units/getOrganizationUnitChildren'; export {default as getUserInfo} from './api/auth/getUserInfo'; diff --git a/packages/javascript/src/models/flow-meta.ts b/packages/javascript/src/models/flow-meta.ts index 1d2c4ffa..e4829e97 100644 --- a/packages/javascript/src/models/flow-meta.ts +++ b/packages/javascript/src/models/flow-meta.ts @@ -19,6 +19,12 @@ export enum FlowMetaType { /** Retrieve metadata scoped to a specific application */ App = 'APP', + /** + * Retrieve metadata by the opaque `ref` query parameter the authorize endpoint adds to the sign-in + * page URL. The value is passed as `id` unchanged. + */ + Ref = 'REF', + /** Retrieve metadata scoped to a specific organization unit */ Ou = 'OU', } @@ -278,6 +284,12 @@ export interface FlowMetadataResponse { */ application?: ApplicationMetadata; + /** + * Where a sign-in page sends the user when it has no flow to continue and no application URL to + * return to. Omitted when the server does not set one. + */ + defaultReturnUrl?: string; + /** Resolved design configuration */ design: DesignMetadata; diff --git a/packages/nuxt/src/runtime/components/auth/SignIn.ts b/packages/nuxt/src/runtime/components/auth/SignIn.ts index 5fe37108..53315325 100644 --- a/packages/nuxt/src/runtime/components/auth/SignIn.ts +++ b/packages/nuxt/src/runtime/components/auth/SignIn.ts @@ -21,6 +21,7 @@ import { EmbeddedSignInFlowType, type FlowMetadataResponse, isFlowExpiredError, + replaceLocation, } from '@thunderid/browser'; import { BaseSignIn, @@ -52,6 +53,7 @@ import { shallowRef, watch, } from 'vue'; +import NuxtAPIRoutes from '../../constants/NuxtAPIRoutes'; import {useThunderID} from '#imports'; /** Builds an SDK-raised error with the current translator, so it follows a language change. */ @@ -132,9 +134,11 @@ const SignIn: Component = defineComponent({ name: 'SignIn', props: { /** - * Where to send the user once the flow expires, e.g. the application's URL. With it, an expired flow counts - * down and redirects there. Without it, the flow is started again in place. Set it when the sign-in runs on - * a page of its own, such as a login portal, rather than inside the application. + * Where to send the user back to, e.g. the application's URL. With it, an expired flow counts down and redirects + * there, and a page with no flow to continue, such as a bookmarked URL, goes there straight away. Without it, the + * flow is started again in place when the application is known. Otherwise the URL comes from the page's `ref` + * parameter, else the server's default return URL. Set it when the sign-in runs on a page of its own, such as a + * login portal, rather than inside the application. */ afterFlowExpiredUrl: {default: undefined, type: String}, className: {default: '', type: String}, @@ -206,6 +210,13 @@ const SignIn: Component = defineComponent({ // A flow an authorize request started cannot be started again here: the server refuses to start a sign-in // directly for such an application, so the user has to go back to it. const isStartedByAuthorizeRequest: Ref = ref(false); + // The `ref` the page URL carried when it loaded. It names the application to go back to. + const initialRef: string | null = + typeof window === 'undefined' ? null : new URLSearchParams(window.location.search).get('ref'); + // Set when the page loaded with no flow to resume and no application to start one, as a bookmarked URL does. + const hasNoFlow: Ref = ref(false); + const canRestart = (): boolean => + Boolean(applicationId || startedApplicationId.value) && !isStartedByAuthorizeRequest.value; const { clearFlowRestarted, expireFlow, @@ -214,9 +225,18 @@ const SignIn: Component = defineComponent({ isFlowRestarted, restartFlow, restartsInPlace, + returnTarget, } = useFlowExpiryHandling({ afterFlowExpiredUrl: () => props.afterFlowExpiredUrl, - canRestart: () => Boolean(applicationId || startedApplicationId.value) && !isStartedByAuthorizeRequest.value, + canRestart, + // Metadata goes through the same-origin route, as everywhere in this module. + returnUrlLookup: { + enabled: isInitialized, + fetchMeta: async (query: {id?: string; type?: string}): Promise => + (await $fetch(NuxtAPIRoutes.META, {query})) ?? null, + meta: flowMeta, + ref: initialRef, + }, // Deferred, since the restart is defined further down. restart: (): void => { void startFlowAgain(); @@ -341,6 +361,27 @@ const SignIn: Component = defineComponent({ }, ); + // A page with no flow, such as a bookmarked or shared URL, goes back straight away once the return URL is + // known. Nothing expired from the user's side, so there is no expired notice or countdown. With nowhere to go it + // reports why through `error` (state, event and render props) only, since a thrown error would go unhandled. + watch([hasNoFlow, returnTarget], () => { + if (!hasNoFlow.value) { + return; + } + const returnUrl: string | undefined = props.afterFlowExpiredUrl ?? returnTarget.value?.url; + if (returnUrl) { + replaceLocation(returnUrl); + } else if (returnTarget.value) { + setError( + new ThunderIDRuntimeError( + 'Either executionId or applicationId is required for authentication', + 'SIGN_IN_ERROR', + 'nuxt', + ), + ); + } + }); + /** * Updates challengeTokenRef immediately and persists via the provider's * StorageManager so the token survives OAuth redirects. @@ -424,16 +465,9 @@ const SignIn: Component = defineComponent({ isStartedByAuthorizeRequest.value = true; } - // Reported through `error` (state, event and render props) only: the flow is started from a watcher, where a - // thrown error would go unhandled. + // Nothing to resume and nothing to start: the watcher below sends the user back, or reports the error. if (!urlParams.executionId && !effectiveApplicationId) { - setError( - new ThunderIDRuntimeError( - 'Either executionId or applicationId is required for authentication', - 'SIGN_IN_ERROR', - 'nuxt', - ), - ); + hasNoFlow.value = true; return; } diff --git a/packages/nuxt/src/runtime/server/routes/auth/session/meta.get.ts b/packages/nuxt/src/runtime/server/routes/auth/session/meta.get.ts index 9637eabd..3e1867f7 100644 --- a/packages/nuxt/src/runtime/server/routes/auth/session/meta.get.ts +++ b/packages/nuxt/src/runtime/server/routes/auth/session/meta.get.ts @@ -1,6 +1,7 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 +import {FlowMetaType} from '@thunderid/node'; import type {AuthClientConfig, FlowMetadataResponse} from '@thunderid/node'; import {createError, defineEventHandler, getQuery} from 'h3'; import type {H3Event} from 'h3'; @@ -32,9 +33,12 @@ export default defineEventHandler(async (event: H3Event): Promise = getQuery(event); const language: string | undefined = typeof query.language === 'string' ? query.language : undefined; + // Only a `REF` lookup is passed through: the sign-in page asks which application its URL names. + const ref: string | undefined = + query.type === FlowMetaType.Ref && typeof query.id === 'string' ? query.id : undefined; try { - return await loadFlowMeta(configData, language); + return await loadFlowMeta(configData, language, ref); } catch (error) { log.error('Failed to fetch flow metadata:', error instanceof Error ? error.message : String(error)); diff --git a/packages/nuxt/src/runtime/server/utils/loadFlowMeta.ts b/packages/nuxt/src/runtime/server/utils/loadFlowMeta.ts index 9cbf9b09..baebc6af 100644 --- a/packages/nuxt/src/runtime/server/utils/loadFlowMeta.ts +++ b/packages/nuxt/src/runtime/server/utils/loadFlowMeta.ts @@ -1,7 +1,13 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {FlowMetaType, getFlowMeta, isFlowMetaUnavailableError, resolveResourceEndpoint} from '@thunderid/node'; +import { + FlowMetaType, + getFlowMeta, + isFlowMetaUnavailableError, + resolveResourceEndpoint, + ThunderIDAPIError, +} from '@thunderid/node'; import type {FlowMetadataResponse, ResourceEndpointConfig} from '@thunderid/node'; import {createLogger} from '../../utils/log'; @@ -23,7 +29,27 @@ let hasWarnedUnavailable = false; const loadFlowMeta = async ( config: (ResourceEndpointConfig & {applicationId?: string; baseUrl?: string}) | undefined, language?: string, + ref?: string, ): Promise => { + // A `ref` from a sign-in page URL names the application in place of the configured one. A 404, which ThunderID + // answers for a ref that names no application, resolves to null without the warning below. Other failures reject. + if (ref) { + try { + return await getFlowMeta({ + baseUrl: config?.baseUrl, + id: ref, + type: FlowMetaType.Ref, + url: resolveResourceEndpoint('flowMeta', config), + ...(language ? {language} : {}), + }); + } catch (error) { + if (isFlowMetaUnavailableError(error) || (error instanceof ThunderIDAPIError && error.statusCode === 404)) { + return null; + } + throw error; + } + } + try { return await getFlowMeta({ baseUrl: config?.baseUrl, diff --git a/packages/nuxt/tests/unit/meta-get.test.ts b/packages/nuxt/tests/unit/meta-get.test.ts index f81e9794..b5c82089 100644 --- a/packages/nuxt/tests/unit/meta-get.test.ts +++ b/packages/nuxt/tests/unit/meta-get.test.ts @@ -111,4 +111,56 @@ describe('GET /api/auth/meta', () => { await expect((metaHandler as any)(mockEvent)).rejects.toMatchObject({statusCode: 502}); expect(mocks.log.error).toHaveBeenCalledWith('Failed to fetch flow metadata:', 'fetch failed'); }); + + it('looks the application up by the ref a sign-in page passes', async () => { + const meta = {application: {url: 'https://acme.example.com'}, design: {}, i18n: {}}; + vi.mocked(getQuery).mockReturnValue({id: 'AZqMXi9Bez2p5lwNH3s-KA', type: 'REF'}); + vi.mocked(getFlowMeta).mockResolvedValue(meta as any); + + await expect((metaHandler as any)(mockEvent)).resolves.toBe(meta); + expect(getFlowMeta).toHaveBeenCalledWith({ + baseUrl: 'https://localhost:8090', + id: 'AZqMXi9Bez2p5lwNH3s-KA', + type: 'REF', + url: undefined, + }); + }); + + it('returns null without a warning when the ref names no application', async () => { + vi.mocked(getQuery).mockReturnValue({id: 'unknown', type: 'REF'}); + vi.mocked(getFlowMeta).mockRejectedValue(notFound()); + + await expect((metaHandler as any)(mockEvent)).resolves.toBeNull(); + expect(mocks.log.warn).not.toHaveBeenCalled(); + }); + + it('returns null when ThunderID answers that the ref names no application', async () => { + vi.mocked(getQuery).mockReturnValue({id: 'AZqMXi9Bez2p5lwNH3s-KA', type: 'REF'}); + vi.mocked(getFlowMeta).mockRejectedValue( + new ThunderIDAPIError( + JSON.stringify({code: 'FM-1002', message: 'Application not found'}), + 'getFlowMeta-ResponseError-001', + 'javascript', + 404, + ), + ); + + await expect((metaHandler as any)(mockEvent)).resolves.toBeNull(); + expect(mocks.log.warn).not.toHaveBeenCalled(); + }); + + it('answers 502 when a ref lookup fails for another reason', async () => { + vi.mocked(getQuery).mockReturnValue({id: 'AZqMXi9Bez2p5lwNH3s-KA', type: 'REF'}); + vi.mocked(getFlowMeta).mockRejectedValue(new TypeError('fetch failed')); + + await expect((metaHandler as any)(mockEvent)).rejects.toMatchObject({statusCode: 502}); + }); + + it('ignores a lookup other than REF and uses the configured application', async () => { + vi.mocked(getQuery).mockReturnValue({id: 'other-app', type: 'APP'}); + vi.mocked(getFlowMeta).mockResolvedValue({design: {}, i18n: {}} as any); + + await (metaHandler as any)(mockEvent); + expect(getFlowMeta).toHaveBeenCalledWith(expect.objectContaining({id: 'app-1', type: 'APP'})); + }); }); diff --git a/packages/nuxt/tests/unit/sign-in.test.ts b/packages/nuxt/tests/unit/sign-in.test.ts index 029b9e5f..20dce4fc 100644 --- a/packages/nuxt/tests/unit/sign-in.test.ts +++ b/packages/nuxt/tests/unit/sign-in.test.ts @@ -4,9 +4,15 @@ /* eslint-disable @typescript-eslint/typedef, @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-function-return-type */ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {effectScope, nextTick, ref} from 'vue'; +import {effectScope, nextTick, ref, shallowRef} from 'vue'; const signIn = vi.fn(); +const flowMocks = vi.hoisted(() => ({ + expireFlow: vi.fn(), + expiryOptions: undefined as any, + replaceLocation: vi.fn(), + returnTarget: undefined as any, +})); vi.mock('@thunderid/browser', () => ({ ConsentConstants: {}, @@ -22,6 +28,7 @@ vi.mock('@thunderid/browser', () => ({ super(message); } }, + replaceLocation: flowMocks.replaceLocation, })); vi.mock('@thunderid/vue', () => ({ @@ -31,15 +38,19 @@ vi.mock('@thunderid/vue', () => ({ handlePasskeyRegistration: vi.fn(), initiateOAuthRedirect: vi.fn(), normalizeFlowResponse: vi.fn(() => ({})), - useFlowExpiryHandling: () => ({ - clearFlowRestarted: vi.fn(), - expireFlow: vi.fn(), - flowExpiryRedirect: ref(null), - isFlowExpired: ref(false), - isFlowRestarted: ref(false), - restartFlow: vi.fn(), - restartsInPlace: ref(true), - }), + useFlowExpiryHandling: (options: any) => { + flowMocks.expiryOptions = options; + return { + clearFlowRestarted: vi.fn(), + expireFlow: flowMocks.expireFlow, + flowExpiryRedirect: ref(null), + isFlowExpired: ref(false), + isFlowRestarted: ref(false), + restartFlow: vi.fn(), + restartsInPlace: ref(true), + returnTarget: flowMocks.returnTarget, + }; + }, useFlowMeta: () => ({meta: ref(null)}), useI18n: () => ({t: (key: string) => key}), useOAuthCallback: vi.fn(), @@ -67,6 +78,10 @@ const onUnhandledRejection = (reason: unknown) => { beforeEach(() => { unhandled.length = 0; + flowMocks.expireFlow.mockClear(); + flowMocks.replaceLocation.mockClear(); + // The lookup found nowhere to go back to, unless a test says otherwise. + flowMocks.returnTarget = shallowRef({}); process.on('unhandledRejection', onUnhandledRejection); }); @@ -99,4 +114,67 @@ describe('SignIn', () => { scope.stop(); }); + + const setUp = (props: Record = {}) => { + const emit = vi.fn(); + const scope = effectScope(); + scope.run(() => + (SignIn as any).setup({className: '', size: 'medium', variant: 'outlined', ...props}, { + attrs: {}, + emit, + slots: {}, + } as any), + ); + return {emit, scope}; + }; + + const settle = async () => { + await nextTick(); + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + }; + + it('goes straight back instead of reporting an error when the page has no flow and a return URL is known', async () => { + flowMocks.returnTarget = shallowRef({url: 'https://home.example.com'}); + const {emit, scope} = setUp(); + + await settle(); + + expect(flowMocks.replaceLocation).toHaveBeenCalledWith('https://home.example.com'); + expect(flowMocks.expireFlow).not.toHaveBeenCalled(); + expect(emit).not.toHaveBeenCalledWith('error', expect.anything()); + expect(signIn).not.toHaveBeenCalled(); + + scope.stop(); + }); + + it('goes straight to afterFlowExpiredUrl when the page has no flow', async () => { + flowMocks.returnTarget = shallowRef(undefined); + const {emit, scope} = setUp({afterFlowExpiredUrl: 'https://app.example.com'}); + + await settle(); + + expect(flowMocks.replaceLocation).toHaveBeenCalledWith('https://app.example.com'); + expect(emit).not.toHaveBeenCalledWith('error', expect.anything()); + + scope.stop(); + }); + + it('looks the ref from the page URL up through the same-origin meta route', async () => { + const $fetch = vi.fn().mockResolvedValue({application: {url: 'https://acme.example.com'}}); + vi.stubGlobal('$fetch', $fetch); + vi.stubGlobal('window', {location: {href: 'https://idp.example.com/gate/signin?ref=r1', search: '?ref=r1'}}); + const {scope} = setUp(); + + const lookup = flowMocks.expiryOptions.returnUrlLookup; + expect(lookup.ref).toBe('r1'); + await expect(lookup.fetchMeta({id: 'r1', type: 'REF'})).resolves.toEqual({ + application: {url: 'https://acme.example.com'}, + }); + expect($fetch).toHaveBeenCalledWith('/api/auth/meta', {query: {id: 'r1', type: 'REF'}}); + + scope.stop(); + vi.unstubAllGlobals(); + }); }); diff --git a/packages/react/src/components/auth/SignIn/SignIn.tsx b/packages/react/src/components/auth/SignIn/SignIn.tsx index da582928..ffa55027 100644 --- a/packages/react/src/components/auth/SignIn/SignIn.tsx +++ b/packages/react/src/components/auth/SignIn/SignIn.tsx @@ -13,12 +13,16 @@ import { EmbeddedSignInFlowType, FieldError, FlowMetadataResponse, + FlowMetaType, Preferences, logger, compileConsentDecisions, + getFlowMeta, isFlowExpiredError, + replaceLocation, + resolveResourceEndpoint, } from '@thunderid/browser'; -import {FC, ReactElement, useState, useEffect, useMemo, useRef, ReactNode} from 'react'; +import {FC, ReactElement, useCallback, useState, useEffect, useMemo, useRef, ReactNode} from 'react'; // eslint-disable-next-line import/no-named-as-default import BaseSignIn, {BaseSignInProps} from './BaseSignIn'; import useThunderID from '../../../contexts/ThunderID/useThunderID'; @@ -123,9 +127,11 @@ export interface SignInRenderProps { */ export interface SignInProps { /** - * Where to send the user once the flow expires, e.g. the application's URL. With it, an expired flow counts - * down and redirects there. Without it, the flow is started again in place. Set it when the sign-in runs - * on a page of its own, such as a login portal, rather than inside the application. + * Where to send the user back to, e.g. the application's URL. With it, an expired flow counts down and redirects + * there, and a page with no flow to continue, such as a bookmarked URL, goes there straight away. Without it, the + * flow is started again in place when the application is known. Otherwise the URL comes from the page's `ref` + * parameter, else the server's default return URL. Set it when the sign-in runs on a page of its own, such as a + * login portal, rather than inside the application. */ afterFlowExpiredUrl?: string; @@ -294,8 +300,19 @@ const SignIn: FC = ({ organizationUnitId, afterFlowExpiredUrl = undefined, }: SignInProps): ReactElement => { - const {applicationId, afterSignInUrl, signIn, isInitialized, isLoading, meta, getStorageManager, scopes, vendor} = - useThunderID(); + const { + applicationId, + afterSignInUrl, + baseUrl, + endpoints, + signIn, + isInitialized, + isLoading, + meta, + getStorageManager, + scopes, + vendor, + } = useThunderID(); const {t} = useTranslation(preferences?.i18n); // State management for the flow @@ -323,6 +340,19 @@ const SignIn: FC = ({ // A flow an authorize request started cannot be started again here: the server refuses to start a sign-in // directly for such an application, so the user has to go back to it. const [isStartedByAuthorizeRequest, setIsStartedByAuthorizeRequest] = useState(false); + // The `ref` the page URL carried when it loaded. It names the application to go back to. + const [initialRef] = useState(() => + typeof window === 'undefined' ? null : new URL(window.location.href).searchParams.get('ref'), + ); + // Why the page has no flow to continue, with no application to start one: nothing to resume, as a bookmarked URL + // opened in a new tab, or an execution left in this tab that the server no longer accepts. + const [noFlowReason, setNoFlowReason] = useState<'missing' | 'stale' | null>(null); + const canRestart: boolean = Boolean(applicationId || startedApplicationId) && !isStartedByAuthorizeRequest; + const fetchFlowMeta: (query: {id?: string; type?: FlowMetaType}) => Promise = useCallback( + (query: {id?: string; type?: FlowMetaType}): Promise => + getFlowMeta({baseUrl, url: resolveResourceEndpoint('flowMeta', {endpoints}), ...query}), + [baseUrl, endpoints], + ); const { clearFlowRestarted, expireFlow, @@ -331,9 +361,11 @@ const SignIn: FC = ({ isFlowRestarted, restartFlow, restartsInPlace, + returnTarget, } = useFlowExpiryHandling({ afterFlowExpiredUrl, - canRestart: Boolean(applicationId || startedApplicationId) && !isStartedByAuthorizeRequest, + canRestart, + returnUrlLookup: {enabled: isInitialized, fetchMeta: fetchFlowMeta, meta, ref: initialRef}, // Deferred, since the restart is defined further down. restart: (): void => { void startFlowAgain(); @@ -544,6 +576,29 @@ const SignIn: FC = ({ } }, [isFlowExpired, restartsInPlace]); + // A page with no flow, such as a bookmarked or shared URL, goes back straight away once the return URL is known. + // Nothing expired from the user's side, so there is no expired notice or countdown. With nowhere to go, a left + // over execution reads as an expired session, and a page that never had one reports why it can't sign in. + useEffect(() => { + if (!noFlowReason) { + return; + } + const returnUrl: string | undefined = afterFlowExpiredUrl ?? returnTarget?.url; + if (returnUrl) { + replaceLocation(returnUrl); + } else if (returnTarget && noFlowReason === 'stale') { + handleFlowExpired(); + } else if (returnTarget) { + setError( + new ThunderIDRuntimeError( + 'Either executionId or applicationId is required for authentication', + 'SIGN_IN_ERROR', + 'react', + ), + ); + } + }, [noFlowReason, afterFlowExpiredUrl, returnTarget]); + /** * Handle OAuth error from URL parameters. * Clears flow state, creates error, and cleans up URL. @@ -679,13 +734,9 @@ const SignIn: FC = ({ const storedExecutionId: any = !urlParams.executionId ? sessionStorage.getItem(`${vendor}_execution_id`) : null; const resumeExecutionId: any = urlParams.executionId || storedExecutionId; + // Nothing to resume and nothing to start: the effect below sends the user back, or reports the error. if (!resumeExecutionId && !effectiveApplicationId) { - const error: any = new ThunderIDRuntimeError( - 'Either executionId or applicationId is required for authentication', - 'SIGN_IN_ERROR', - 'react', - ); - setError(error); + setNoFlowReason('missing'); return; } @@ -702,10 +753,6 @@ const SignIn: FC = ({ ...(challengeTokenRef.current ? {challengeToken: challengeTokenRef.current} : {}), })) as EmbeddedSignInFlowResponse; } catch (resumeError) { - // An execution the server refused as expired takes the same path as any other expiry. - if (isFlowExpiredError(resumeError)) { - throw resumeError; - } // Only treat a stale/expired session (HTTP 400 from the server, meaning the stored // executionId is no longer valid) as a recoverable condition. Transient failures // such as 5xx server errors or network errors are rethrown so they surface correctly. @@ -715,13 +762,22 @@ const SignIn: FC = ({ resumeError instanceof ThunderIDAPIError && resumeError.statusCode === 400; + // An execution left in this tab that the server no longer accepts is not this page's flow. With no + // application to start one, the page has no flow, as a bookmarked URL opened in a new tab does. + if (isStaleSession && !effectiveApplicationId) { + setExecutionId(null); + await clearAuthId(resumeExecutionId); + setNoFlowReason('stale'); + return; + } + // An execution the server refused as expired takes the same path as any other expiry. + if (isFlowExpiredError(resumeError)) { + throw resumeError; + } + if (isStaleSession) { setExecutionId(null); await clearAuthId(resumeExecutionId); - if (!effectiveApplicationId) { - handleFlowExpired(); - return; - } response = (await signIn({ applicationId: effectiveApplicationId, flowType: EmbeddedFlowType.Authentication, diff --git a/packages/react/src/components/auth/SignIn/__tests__/SignIn.test.tsx b/packages/react/src/components/auth/SignIn/__tests__/SignIn.test.tsx index de9fd969..97535355 100644 --- a/packages/react/src/components/auth/SignIn/__tests__/SignIn.test.tsx +++ b/packages/react/src/components/auth/SignIn/__tests__/SignIn.test.tsx @@ -19,6 +19,14 @@ import Consent from '../../flow/Consent'; import SignIn, {type SignInRenderProps} from '../SignIn'; const mockSignIn = vi.fn() as Mock; +const mockGetFlowMeta = vi.fn() as Mock; +const mockReplaceLocation = vi.fn() as Mock; + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + getFlowMeta: (...args: unknown[]): unknown => mockGetFlowMeta(...args), + replaceLocation: (...args: unknown[]): unknown => mockReplaceLocation(...args), +})); const thunderIDContext: ThunderIDContextProps = { applicationId: undefined, @@ -37,6 +45,12 @@ const thunderIDContext: ThunderIDContextProps = { vendor: 'thunderid', } as unknown as ThunderIDContextProps; +// Without a stubbed answer, a return URL lookup fails as it would against a server with no metadata. +beforeEach(() => { + mockGetFlowMeta.mockReset().mockRejectedValue(new Error('no metadata')); + mockReplaceLocation.mockReset(); +}); + describe('SignIn without an application', () => { const unhandled: unknown[] = []; const onUnhandledRejection = (event: PromiseRejectionEvent): void => { @@ -105,6 +119,90 @@ describe('SignIn without an application', () => { expect((error as ThunderIDRuntimeError).code).toBe('SIGN_IN_ERROR'); expect(error).toBe(onError.mock.calls[0][0]); }); + + const renderWithoutApplication = (renderChild: Mock<(props: SignInRenderProps) => ReactNode>): void => { + render( + + + + {renderChild} + + + , + ); + }; + + it('goes straight back to the application the ref parameter names', async () => { + window.history.replaceState({}, '', '/signin?ref=AZqMXi9Bez2p5lwNH3s-KA'); + mockGetFlowMeta.mockResolvedValue({application: {name: 'Acme', url: 'https://acme.example.com'}}); + const renderChild: Mock<(props: SignInRenderProps) => null> = vi.fn(() => null); + + renderWithoutApplication(renderChild); + + await waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://acme.example.com'); + }); + expect(renderChild.mock.lastCall?.[0].isFlowExpired).toBe(false); + expect(renderChild.mock.lastCall?.[0].error).toBeNull(); + expect(mockGetFlowMeta).toHaveBeenCalledWith(expect.objectContaining({id: 'AZqMXi9Bez2p5lwNH3s-KA', type: 'REF'})); + expect(mockSignIn).not.toHaveBeenCalled(); + }); + + it('goes straight back when an execution left in the tab is refused as expired', async () => { + window.history.replaceState({}, '', '/signin?ref=AZqMXi9Bez2p5lwNH3s-KA'); + sessionStorage.setItem('thunderid_execution_id', 'old-exec'); + mockSignIn.mockRejectedValueOnce( + new ThunderIDAPIError( + JSON.stringify({code: 'FES-1004', message: {defaultValue: 'Invalid request', key: 'error.invalid_request'}}), + 'executeEmbeddedSignInFlow-ResponseError-100', + 'javascript', + 400, + 'Bad Request', + ), + ); + mockGetFlowMeta.mockResolvedValue({application: {name: 'Acme', url: 'https://acme.example.com'}}); + const renderChild: Mock<(props: SignInRenderProps) => null> = vi.fn(() => null); + + renderWithoutApplication(renderChild); + + await waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://acme.example.com'); + }); + expect(mockSignIn).toHaveBeenCalledWith(expect.objectContaining({executionId: 'old-exec'})); + expect(renderChild.mock.lastCall?.[0].isFlowExpired).toBe(false); + expect(sessionStorage.getItem('thunderid_execution_id')).toBeNull(); + }); + + it('goes straight to afterFlowExpiredUrl without a lookup when the page has no flow', async () => { + window.history.replaceState({}, '', '/signin?ref=AZqMXi9Bez2p5lwNH3s-KA'); + + render( + + + + {vi.fn(() => null)} + + + , + ); + + await waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://app.example.com'); + }); + expect(mockGetFlowMeta).not.toHaveBeenCalled(); + }); + + it('goes straight to the default return URL when the URL has no parameters', async () => { + mockGetFlowMeta.mockResolvedValue({defaultReturnUrl: 'https://home.example.com'}); + const renderChild: Mock<(props: SignInRenderProps) => null> = vi.fn(() => null); + + renderWithoutApplication(renderChild); + + await waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://home.example.com'); + }); + expect(renderChild.mock.lastCall?.[0].isFlowExpired).toBe(false); + }); }); describe('SignIn error banner on a language change', () => { @@ -335,6 +433,22 @@ describe('SignIn flow expiry', () => { }); expect(lastProps(renderChild)?.isFlowExpired).toBe(false); expect(onError).not.toHaveBeenCalled(); + expect(mockGetFlowMeta).not.toHaveBeenCalled(); + }); + + it('counts down to the default return URL when an authorize request started the expired flow', async () => { + setUserPresent(false); + window.history.replaceState({}, '', '/signin?executionId=exec-1&authId=auth-1&applicationId=app-1'); + mockGetFlowMeta.mockResolvedValue({defaultReturnUrl: 'https://home.example.com'}); + mockSignIn.mockResolvedValueOnce(step(0.1)); + const renderChild: Mock<(props: SignInRenderProps) => ReactNode> = vi.fn(() => null); + renderSignIn(renderChild, {}, {applicationId: undefined}); + + await waitFor(() => { + expect(lastProps(renderChild)?.flowExpiryRedirect?.url).toBe('https://home.example.com'); + }); + expect(lastProps(renderChild)?.isFlowExpired).toBe(true); + expect(mockSignIn).toHaveBeenCalledTimes(1); }); it('waits for the user before starting an expired flow again', async () => { diff --git a/packages/react/src/hooks/auth/useFlowExpiryHandling.ts b/packages/react/src/hooks/auth/useFlowExpiryHandling.ts index 05c77f16..df711ef2 100644 --- a/packages/react/src/hooks/auth/useFlowExpiryHandling.ts +++ b/packages/react/src/hooks/auth/useFlowExpiryHandling.ts @@ -1,18 +1,38 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {useCallback, useState} from 'react'; +import {FlowMetadataResponse, FlowMetaType, FlowReturnTarget, resolveFlowReturnUrl} from '@thunderid/browser'; +import {useCallback, useEffect, useState} from 'react'; import useFlowExpiry, {FlowExpiryStep} from './useFlowExpiry'; import useFlowExpiryRedirect, {FlowExpiryRedirect} from './useFlowExpiryRedirect'; import useWhenUserPresent from './useWhenUserPresent'; +/** + * How to find where to send the user back to when the flow can't be started again in place. + */ +export interface FlowReturnUrlLookup { + /** Whether the lookup may run yet, e.g. once the SDK has initialized. */ + enabled: boolean; + /** Fetches flow metadata for a query. Keep it stable across renders. */ + fetchMeta: (query: {id?: string; type?: FlowMetaType}) => Promise; + /** Flow metadata already loaded for the page, if any. */ + meta: FlowMetadataResponse | null; + /** The `ref` query parameter the page URL carried when it loaded. */ + ref: string | null; +} + export interface FlowExpiryHandlingOptions { - /** Where to send the user once the flow expires. With it, the flow counts down there instead of restarting. */ + /** + * Where to send the user once the flow expires. With it, the flow counts down there instead of restarting. + * Without it, a flow that can't be started again in place goes back to the URL `returnUrlLookup` finds. + */ afterFlowExpiredUrl?: string; /** Whether the component can start its flow again, e.g. it knows the application to start it for. */ canRestart: boolean; /** Starts the flow again: clears it and starts a new execution. */ restart: () => void; + /** Finds where to send the user back to when the flow can't be started again in place. */ + returnUrlLookup?: FlowReturnUrlLookup; /** The latest step response, a new object for each response. */ step?: FlowExpiryStep | null; } @@ -32,6 +52,8 @@ export interface FlowExpiryHandling { restartFlow: () => void; /** Whether an expired flow is started again in place, rather than sent back to the application. */ restartsInPlace: boolean; + /** Where `returnUrlLookup` found to send the user back to. Undefined until it has looked. */ + returnTarget: FlowReturnTarget | undefined; } /** @@ -43,10 +65,15 @@ const useFlowExpiryHandling = ({ afterFlowExpiredUrl = undefined, canRestart, restart, + returnUrlLookup = undefined, step = undefined, }: FlowExpiryHandlingOptions): FlowExpiryHandling => { const {expireFlow, expiry, isFlowExpired, resetFlowExpiry} = useFlowExpiry(step); - const flowExpiryRedirect: FlowExpiryRedirect | null = useFlowExpiryRedirect(expiry, afterFlowExpiredUrl); + const [returnTarget, setReturnTarget] = useState(undefined); + const flowExpiryRedirect: FlowExpiryRedirect | null = useFlowExpiryRedirect( + expiry, + afterFlowExpiredUrl ?? (canRestart ? undefined : returnTarget?.url), + ); const [isFlowRestarted, setIsFlowRestarted] = useState(false); const restartsInPlace: boolean = !afterFlowExpiredUrl && canRestart; @@ -59,6 +86,29 @@ const useFlowExpiryHandling = ({ useWhenUserPresent(isFlowExpired && restartsInPlace, restartFlow); + // A flow that can't be started again here goes back to the application, so find out where that is, unless the + // caller named the URL itself. + const lookupEnabled: boolean = Boolean(returnUrlLookup?.enabled) && !afterFlowExpiredUrl && !canRestart; + const {fetchMeta, meta = null, ref = null} = returnUrlLookup ?? {}; + useEffect(() => { + if (!lookupEnabled || !fetchMeta) { + return undefined; + } + + let active = true; + void resolveFlowReturnUrl({currentUrl: window.location.href, fetchMeta, meta, ref}).then( + (target: FlowReturnTarget) => { + if (active) { + setReturnTarget(target); + } + }, + ); + + return () => { + active = false; + }; + }, [lookupEnabled, fetchMeta, meta, ref]); + return { clearFlowRestarted, expireFlow, @@ -67,6 +117,7 @@ const useFlowExpiryHandling = ({ isFlowRestarted, restartFlow, restartsInPlace, + returnTarget, }; }; diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 7b54d52b..1be76740 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -28,6 +28,14 @@ export type {FlowProviderProps} from './contexts/Flow/FlowProvider'; export {default as FlowMetaProvider} from './contexts/FlowMeta/FlowMetaProvider'; export type {FlowMetaProviderProps} from './contexts/FlowMeta/FlowMetaProvider'; +export { + FlowMetaType, + getFlowMeta, + resolveFlowReturnUrl, + type ApplicationMetadata, + type FlowMetadataResponse, + type FlowReturnTarget, +} from '@thunderid/browser'; export {default as useFlow} from './contexts/Flow/useFlow'; diff --git a/packages/vue/src/__tests__/components/auth/flow-expiry.test.ts b/packages/vue/src/__tests__/components/auth/flow-expiry.test.ts index 5a2b8a3f..58206879 100644 --- a/packages/vue/src/__tests__/components/auth/flow-expiry.test.ts +++ b/packages/vue/src/__tests__/components/auth/flow-expiry.test.ts @@ -13,6 +13,15 @@ import useFlowExpiry, {type FlowExpiry, type FlowExpiryStep} from '../../../comp import useFlowExpiryRedirect from '../../../composables/auth/useFlowExpiryRedirect'; import {FLOW_KEY, FLOW_META_KEY, I18N_KEY, THUNDERID_KEY} from '../../../keys'; +const mockGetFlowMeta: Mock = vi.fn(); +const mockReplaceLocation: Mock = vi.fn(); + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + getFlowMeta: (...args: unknown[]): unknown => mockGetFlowMeta(...args), + replaceLocation: (...args: unknown[]): unknown => mockReplaceLocation(...args), +})); + const translations: Record = { 'flow.expired.application': 'the application', 'flow.expired.redirect.now': 'Back to {application} now', @@ -58,6 +67,9 @@ describe('flow expiry', () => { beforeEach(() => { scope = effectScope(); vi.spyOn(document, 'hasFocus').mockReturnValue(true); + mockGetFlowMeta.mockReset().mockRejectedValue(new Error('no metadata')); + mockReplaceLocation.mockReset(); + window.history.replaceState({}, '', '/signin'); }); afterEach(() => { @@ -194,6 +206,87 @@ describe('flow expiry', () => { expect(slot.mock.lastCall![0].isFlowExpired).toBe(true); expect(slot.mock.lastCall![0].flowExpiryRedirect).toMatchObject({url: 'https://app.example.com'}); }); + + it('goes straight back to the application the ref parameter names when there is no flow', async () => { + window.history.replaceState({}, '', '/signin?ref=AZqMXi9Bez2p5lwNH3s-KA'); + mockGetFlowMeta.mockResolvedValue({application: {name: 'Acme', url: 'https://acme.example.com'}}); + const signIn: Mock = vi.fn(); + const slot: Mock<(props: SignInRenderProps) => never[]> = vi.fn(() => []); + const isInitialized: Ref = ref(false); + mount(SignIn, { + global: {provide: provide({applicationId: undefined, isInitialized, signIn})}, + slots: {default: slot}, + }); + isInitialized.value = true; + await vi.waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://acme.example.com'); + }); + + expect(slot.mock.lastCall![0].isFlowExpired).toBe(false); + expect(mockGetFlowMeta).toHaveBeenCalledWith( + expect.objectContaining({id: 'AZqMXi9Bez2p5lwNH3s-KA', type: 'REF'}), + ); + expect(signIn).not.toHaveBeenCalled(); + }); + + it('goes straight to afterFlowExpiredUrl without a lookup when there is no flow', async () => { + window.history.replaceState({}, '', '/signin?ref=AZqMXi9Bez2p5lwNH3s-KA'); + const isInitialized: Ref = ref(false); + mount(SignIn, { + global: {provide: provide({applicationId: undefined, isInitialized, signIn: vi.fn()})}, + props: {afterFlowExpiredUrl: 'https://app.example.com'}, + slots: {default: vi.fn(() => [])}, + }); + isInitialized.value = true; + await vi.waitFor(() => { + expect(mockReplaceLocation).toHaveBeenCalledWith('https://app.example.com'); + }); + + expect(mockGetFlowMeta).not.toHaveBeenCalled(); + }); + + it('goes back to the default return URL when an authorize request started the expired flow', async () => { + window.history.replaceState({}, '', '/signin?executionId=e-1&authId=a-1'); + mockGetFlowMeta.mockResolvedValue({defaultReturnUrl: 'https://home.example.com'}); + const signIn: Mock = vi.fn().mockResolvedValueOnce(step()).mockRejectedValueOnce(expiredError()); + const slot: Mock<(props: SignInRenderProps) => never[]> = vi.fn(() => []); + const isInitialized: Ref = ref(false); + mount(SignIn, { + global: { + provide: { + ...provide({applicationId: undefined, isInitialized, signIn}), + [FLOW_META_KEY as symbol]: {meta: ref(null)}, + }, + }, + slots: {default: slot}, + }); + isInitialized.value = true; + await flushPromises(); + + await slot.mock.lastCall![0].onSubmit({executionId: 'e-1', inputs: {}}); + await vi.waitFor(() => { + expect(slot.mock.lastCall![0].flowExpiryRedirect).toMatchObject({url: 'https://home.example.com'}); + }); + expect(slot.mock.lastCall![0].isFlowExpired).toBe(true); + }); + + it('starts again in place without looking up a return URL when the app has an application ID', async () => { + const signIn: Mock = vi + .fn() + .mockResolvedValueOnce(step()) + .mockRejectedValueOnce(expiredError()) + .mockResolvedValue(step()); + const slot: Mock<(props: SignInRenderProps) => never[]> = vi.fn(() => []); + const isInitialized: Ref = ref(false); + mount(SignIn, {global: {provide: provide({isInitialized, signIn})}, slots: {default: slot}}); + isInitialized.value = true; + await flushPromises(); + + await slot.mock.lastCall![0].onSubmit({executionId: 'e-1', inputs: {}}); + await flushPromises(); + + expect(mockGetFlowMeta).not.toHaveBeenCalled(); + }); }); describe('SignUp', () => { diff --git a/packages/vue/src/__tests__/components/auth/sign-in.test.ts b/packages/vue/src/__tests__/components/auth/sign-in.test.ts index 84438649..066d1350 100644 --- a/packages/vue/src/__tests__/components/auth/sign-in.test.ts +++ b/packages/vue/src/__tests__/components/auth/sign-in.test.ts @@ -10,6 +10,13 @@ import BaseSignIn from '../../../components/auth/sign-in/BaseSignIn'; import SignIn, {type SignInRenderProps} from '../../../components/auth/sign-in/SignIn'; import {FLOW_KEY, FLOW_META_KEY, I18N_KEY, THUNDERID_KEY} from '../../../keys'; +const mockGetFlowMeta: Mock = vi.fn(() => Promise.reject(new Error('no metadata'))); + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + getFlowMeta: (...args: unknown[]): unknown => mockGetFlowMeta(...args), +})); + describe('BaseSignIn', () => { it('clears only the edited field server error so corrected fields can be submitted', async () => { const wrapper = mount(BaseSignIn, { diff --git a/packages/vue/src/components/auth/sign-in/SignIn.ts b/packages/vue/src/components/auth/sign-in/SignIn.ts index 0dc7ae79..b8a97cb1 100644 --- a/packages/vue/src/components/auth/sign-in/SignIn.ts +++ b/packages/vue/src/components/auth/sign-in/SignIn.ts @@ -13,7 +13,11 @@ import { EmbeddedSignInFlowStatus, EmbeddedSignInFlowType, FlowMetadataResponse, + FlowMetaType, + getFlowMeta, isFlowExpiredError, + replaceLocation, + resolveResourceEndpoint, } from '@thunderid/browser'; import { type Component, @@ -106,9 +110,11 @@ const SignIn: Component = defineComponent({ name: 'SignIn', props: { /** - * Where to send the user once the flow expires, e.g. the application's URL. With it, an expired flow counts - * down and redirects there. Without it, the flow is started again in place. Set it when the sign-in runs on - * a page of its own, such as a login portal, rather than inside the application. + * Where to send the user back to, e.g. the application's URL. With it, an expired flow counts down and redirects + * there, and a page with no flow to continue, such as a bookmarked URL, goes there straight away. Without it, the + * flow is started again in place when the application is known. Otherwise the URL comes from the page's `ref` + * parameter, else the server's default return URL. Set it when the sign-in runs on a page of its own, such as a + * login portal, rather than inside the application. */ afterFlowExpiredUrl: {default: undefined, type: String}, className: {default: '', type: String}, @@ -140,6 +146,8 @@ const SignIn: Component = defineComponent({ const { applicationId, afterSignInUrl, + baseUrl, + endpoints, signIn, isInitialized, isLoading: sdkLoading, @@ -181,6 +189,13 @@ const SignIn: Component = defineComponent({ // A flow an authorize request started cannot be started again here: the server refuses to start a sign-in // directly for such an application, so the user has to go back to it. const isStartedByAuthorizeRequest: Ref = ref(false); + // The `ref` the page URL carried when it loaded. It names the application to go back to. + const initialRef: string | null = + typeof window === 'undefined' ? null : new URLSearchParams(window.location.search).get('ref'); + // Set when the page loaded with no flow to resume and no application to start one, as a bookmarked URL does. + const hasNoFlow: Ref = ref(false); + const canRestart = (): boolean => + Boolean(applicationId || startedApplicationId.value) && !isStartedByAuthorizeRequest.value; const { clearFlowRestarted, expireFlow, @@ -189,9 +204,17 @@ const SignIn: Component = defineComponent({ isFlowRestarted, restartFlow, restartsInPlace, + returnTarget, } = useFlowExpiryHandling({ afterFlowExpiredUrl: () => props.afterFlowExpiredUrl, - canRestart: () => Boolean(applicationId || startedApplicationId.value) && !isStartedByAuthorizeRequest.value, + canRestart, + returnUrlLookup: { + enabled: isInitialized, + fetchMeta: (query: {id?: string; type?: FlowMetaType}): Promise => + getFlowMeta({baseUrl, url: resolveResourceEndpoint('flowMeta', {endpoints}), ...query}), + meta: flowMeta, + ref: initialRef, + }, // Deferred, since the restart is defined further down. restart: (): void => { void startFlowAgain(); @@ -318,6 +341,27 @@ const SignIn: Component = defineComponent({ }, ); + // A page with no flow, such as a bookmarked or shared URL, goes back straight away once the return URL is + // known. Nothing expired from the user's side, so there is no expired notice or countdown. With nowhere to go it + // reports why it can't sign in. + watch([hasNoFlow, returnTarget], () => { + if (!hasNoFlow.value) { + return; + } + const returnUrl: string | undefined = props.afterFlowExpiredUrl ?? returnTarget.value?.url; + if (returnUrl) { + replaceLocation(returnUrl); + } else if (returnTarget.value) { + setError( + new ThunderIDRuntimeError( + 'Either executionId or applicationId is required for authentication', + 'SIGN_IN_ERROR', + 'vue', + ), + ); + } + }); + /** * Updates challengeTokenRef immediately and persists via the provider's * StorageManager so the token survives OAuth redirects. @@ -356,13 +400,9 @@ const SignIn: Component = defineComponent({ isStartedByAuthorizeRequest.value = true; } + // Nothing to resume and nothing to start: the watcher below sends the user back, or reports the error. if (!urlParams.executionId && !effectiveApplicationId) { - const err: ThunderIDRuntimeError = new ThunderIDRuntimeError( - 'Either executionId or applicationId is required for authentication', - 'SIGN_IN_ERROR', - 'vue', - ); - setError(err); + hasNoFlow.value = true; return; } diff --git a/packages/vue/src/composables/auth/useFlowExpiryHandling.ts b/packages/vue/src/composables/auth/useFlowExpiryHandling.ts index 55e7b2a6..a2ba6294 100644 --- a/packages/vue/src/composables/auth/useFlowExpiryHandling.ts +++ b/packages/vue/src/composables/auth/useFlowExpiryHandling.ts @@ -1,18 +1,38 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {ComputedRef, MaybeRefOrGetter, Ref, computed, ref, toValue} from 'vue'; +import {FlowMetadataResponse, FlowMetaType, FlowReturnTarget, resolveFlowReturnUrl} from '@thunderid/browser'; +import {ComputedRef, MaybeRefOrGetter, Ref, computed, ref, shallowRef, toValue, watch} from 'vue'; import useFlowExpiry, {FlowExpiryStep} from './useFlowExpiry'; import useFlowExpiryRedirect, {FlowExpiryRedirect} from './useFlowExpiryRedirect'; import useWhenUserPresent from './useWhenUserPresent'; +/** + * How to find where to send the user back to when the flow can't be started again in place. + */ +export interface FlowReturnUrlLookup { + /** Whether the lookup may run yet, e.g. once the SDK has initialized. */ + enabled: MaybeRefOrGetter; + /** Fetches flow metadata for a query. */ + fetchMeta: (query: {id?: string; type?: FlowMetaType}) => Promise; + /** Flow metadata already loaded for the page, if any. */ + meta: MaybeRefOrGetter; + /** The `ref` query parameter the page URL carried when it loaded. */ + ref: string | null; +} + export interface FlowExpiryHandlingOptions { - /** Where to send the user once the flow expires. With it, the flow counts down there instead of restarting. */ + /** + * Where to send the user once the flow expires. With it, the flow counts down there instead of restarting. + * Without it, a flow that can't be started again in place goes back to the URL `returnUrlLookup` finds. + */ afterFlowExpiredUrl?: MaybeRefOrGetter; /** Whether the component can start its flow again, e.g. it knows the application to start it for. */ canRestart: MaybeRefOrGetter; /** Starts the flow again: clears it and starts a new execution. */ restart: () => void; + /** Finds where to send the user back to when the flow can't be started again in place. */ + returnUrlLookup?: FlowReturnUrlLookup; /** The latest step response, a new object for each response. */ step?: MaybeRefOrGetter; } @@ -32,6 +52,8 @@ export interface FlowExpiryHandling { restartFlow: () => void; /** Whether an expired flow is started again in place, rather than sent back to the application. */ restartsInPlace: ComputedRef; + /** Where `returnUrlLookup` found to send the user back to. Undefined until it has looked. */ + returnTarget: Ref; } /** @@ -43,11 +65,14 @@ const useFlowExpiryHandling = ({ afterFlowExpiredUrl = undefined, canRestart, restart, + returnUrlLookup = undefined, step = undefined, }: FlowExpiryHandlingOptions): FlowExpiryHandling => { const {expireFlow, expiry, isFlowExpired, resetFlowExpiry} = useFlowExpiry(step); - const flowExpiryRedirect: ComputedRef = useFlowExpiryRedirect(expiry, () => - toValue(afterFlowExpiredUrl), + const returnTarget: Ref = shallowRef(undefined); + const flowExpiryRedirect: ComputedRef = useFlowExpiryRedirect( + expiry, + () => toValue(afterFlowExpiredUrl) ?? (toValue(canRestart) ? undefined : returnTarget.value?.url), ); const isFlowRestarted: Ref = ref(false); const restartsInPlace: ComputedRef = computed(() => !toValue(afterFlowExpiredUrl) && toValue(canRestart)); @@ -63,6 +88,47 @@ const useFlowExpiryHandling = ({ useWhenUserPresent(() => isFlowExpired.value && restartsInPlace.value, restartFlow); + // A flow that can't be started again here goes back to the application, so find out where that is, unless the + // caller named the URL itself. + if (returnUrlLookup) { + watch( + [ + (): boolean => toValue(returnUrlLookup.enabled) && !toValue(afterFlowExpiredUrl) && !toValue(canRestart), + (): FlowMetadataResponse | null => toValue(returnUrlLookup.meta), + ], + ( + [shouldLookUp, meta]: [boolean, FlowMetadataResponse | null], + _: unknown, + onCleanup: (cleanup: () => void) => void, + ) => { + if (!shouldLookUp) { + return; + } + // Without a page URL, as when rendering on the server, there is nowhere to go back to. + if (typeof window === 'undefined') { + returnTarget.value = {}; + return; + } + + let active = true; + onCleanup(() => { + active = false; + }); + void resolveFlowReturnUrl({ + currentUrl: window.location.href, + fetchMeta: returnUrlLookup.fetchMeta, + meta, + ref: returnUrlLookup.ref, + }).then((target: FlowReturnTarget) => { + if (active) { + returnTarget.value = target; + } + }); + }, + {immediate: true}, + ); + } + return { clearFlowRestarted, expireFlow, @@ -71,6 +137,7 @@ const useFlowExpiryHandling = ({ isFlowRestarted, restartFlow, restartsInPlace, + returnTarget, }; }; diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 3e2e4143..93ba9017 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -10,6 +10,8 @@ export {default as ThunderIDProvider} from './providers/ThunderIDProvider'; // ── Providers ── export {default as FlowMetaProvider} from './providers/FlowMetaProvider'; +export {FlowMetaType, getFlowMeta, resolveFlowReturnUrl} from '@thunderid/browser'; +export type {ApplicationMetadata, FlowMetadataResponse, FlowReturnTarget} from '@thunderid/browser'; export {default as FlowProvider} from './providers/FlowProvider'; export {default as I18nProvider} from './providers/I18nProvider'; export {default as ThemeProvider} from './providers/ThemeProvider'; diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 63a61aea..4fa85b96 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -149,6 +149,13 @@ auditConfig: - GHSA-g4wm-2vf7-vfgr - GHSA-858h-whjf-mvg5 - GHSA-v5rq-49vh-5v5c + # JUSTIFICATION: GHSA-fc5q-39xc-vjpf: picomatch ReDoS through single-branch repeated extglobs. + # No patched release exists (4.0.7 and below are affected). Transitive via build tooling only: + # `vue-router` > `vite` / `unplugin`, `@nuxt/kit` > `tinyglobby` > `fdir`, and the eslint and + # vitest toolchain. It matches glob patterns from the project's own config and filesystem at + # build or lint time; no untrusted input reaches it at runtime. Added 2026-11-18; revisit once + # picomatch publishes a fix. + - GHSA-fc5q-39xc-vjpf catalog: '@emotion/css': 11.13.5