Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
14 changes: 14 additions & 0 deletions packages/browser/src/utils/replaceLocation.ts
Original file line number Diff line number Diff line change
@@ -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 => {
Comment thread
ThaminduDilshan marked this conversation as resolved.
Resolved
window.location.replace(url);
};

export default replaceLocation;
12 changes: 12 additions & 0 deletions packages/javascript/src/api/auth/__tests__/getFlowMeta.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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('<html>Not Found</html>', {status: 404}));

Expand Down
Original file line number Diff line number Diff line change
@@ -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>): 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,
});
});
});
100 changes: 100 additions & 0 deletions packages/javascript/src/api/auth/resolveFlowReturnUrl.ts
Original file line number Diff line number Diff line change
@@ -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<FlowMetadataResponse | null>;
/** 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;
Comment thread
ThaminduDilshan marked this conversation as resolved.
Resolved
} 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<FlowReturnTarget> => {
const load = async (query: {id?: string; type?: FlowMetaType}): Promise<FlowMetadataResponse | null> => {
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) {
Comment thread
ThaminduDilshan marked this conversation as resolved.
Resolved
defaultReturnUrl = (await load({}))?.defaultReturnUrl;
}

return {
applicationName: application?.name,
url: toReturnUrl(application?.url, currentUrl) ?? toReturnUrl(defaultReturnUrl, currentUrl),
};
};

export default resolveFlowReturnUrl;
2 changes: 2 additions & 0 deletions packages/javascript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
12 changes: 12 additions & 0 deletions packages/javascript/src/models/flow-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
}
Expand Down Expand Up @@ -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;

Expand Down
Loading
Loading