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
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 42 additions & 0 deletions packages/clerk-js/src/utils/__tests__/url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import {
appendAsQueryParams,
buildURL,
getAllETLDs,
getETLDPlusOneFromFrontendApi,
getSearchParameterFromHash,
hasBannedProtocol,
hasExternalAccountSignUpError,
isAccountsHostedPages,
isAllowedRedirectOrigin,
isDataUri,
isRedirectForFAPIInitiatedFlow,
isValidUrl,
Expand Down Expand Up @@ -383,3 +385,43 @@ describe('isRedirectForFAPIInitiatedFlow(frontendAp: string, redirectUrl: string
},
);
});

describe('getETLDPlusOneFromFrontendApi(frontendAp: string)', () => {
const testCases: Array<[string, string]> = [
['clerk.foo.bar-53.lcl.dev', 'foo.bar-53.lcl.dev'],
['clerk.clerk.com', 'clerk.com'],
['clerk.foo.bar.co.uk', 'foo.bar.co.uk'],
];

test.each(testCases)('frontendApi=(%s), expected value=(%s)', (frontendApi, expectedValue) => {
expect(getETLDPlusOneFromFrontendApi(frontendApi)).toEqual(expectedValue);
});
});

fdescribe('isAllowedRedirectOrigin', () => {
const cases: [string, string[], boolean][] = [
// base cases
['https://clerk.com', ['https://www.clerk.com'], false],
['https://www.clerk.com', ['https://www.clerk.com'], true],
// glob patterns
['https://clerk.com', ['https://*.clerk.com'], false],
['https://www.clerk.com', ['https://*.clerk.com'], true],
['https://www.clerk.com/test', ['https://www.clerk.com/*'], true],
['https://www.clerk.com/hello/test', ['https://www.clerk.com/*/test'], true],
['https://www.clerk.com/hello/hello', ['https://www.clerk.com/*/test'], false],
// trailing slashes
['https://www.clerk.com/', ['https://www.clerk.com'], true],
['https://www.clerk.com', ['https://www.clerk.com'], true],
['https://www.clerk.com/test', ['https://www.clerk.com'], false],
// multiple origins
['https://www.clerk.com', ['https://www.test.dev', 'https://www.clerk.com'], true],
// relative urls
['/relative', ['https://www.clerk.com'], true],
['/relative/test', ['https://www.clerk.com'], true],
['/', ['https://www.clerk.com'], true],
];

test.each(cases)('isAllowedRedirectOrigin("%s","%s") === %s', (url, allowedOrigins, expected) => {
expect(isAllowedRedirectOrigin(url, allowedOrigins)).toEqual(expected);
});
});
24 changes: 20 additions & 4 deletions packages/clerk-js/src/utils/authPropHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ClerkOptions, DisplayConfigResource } from '@clerk/types';
import type { ParsedQs } from 'qs';
import qs from 'qs';

import { hasBannedProtocol, isValidUrl } from './index';
import { hasBannedProtocol, isAllowedRedirectOrigin, isValidUrl } from './url';

type PickRedirectionUrlKey = 'afterSignUpUrl' | 'afterSignInUrl' | 'signInUrl' | 'signUpUrl';

Expand Down Expand Up @@ -35,11 +35,27 @@ export const pickRedirectionProp = (
const snakeCaseField = camelToSnake(key);
const queryParamValue = queryParams?.[snakeCaseField];

const primaryQueryParamRedirectUrl = typeof queryParamValue === 'string' ? queryParamValue : undefined;
const secondaryQueryParamRedirectUrl =
accessRedirectUrl && typeof queryParams?.redirect_url === 'string' ? queryParams.redirect_url : undefined;

let queryParamUrl: string | undefined;
if (
primaryQueryParamRedirectUrl &&
isAllowedRedirectOrigin(primaryQueryParamRedirectUrl, options?.allowedRedirectOrigins)
) {
queryParamUrl = primaryQueryParamRedirectUrl;
} else if (
secondaryQueryParamRedirectUrl &&
isAllowedRedirectOrigin(secondaryQueryParamRedirectUrl, options?.allowedRedirectOrigins)
) {
queryParamUrl = secondaryQueryParamRedirectUrl;
}
Comment thread
nikosdouvlis marked this conversation as resolved.

const url =
(typeof queryParamValue === 'string' ? queryParamValue : null) ||
(accessRedirectUrl && typeof queryParams?.redirect_url === 'string' ? queryParams?.redirect_url : null) ||
queryParamUrl ||
ctx?.[key] ||
(accessRedirectUrl ? ctx?.redirectUrl : null) ||
(accessRedirectUrl ? ctx?.redirectUrl : undefined) ||
options?.[key] ||
displayConfig?.[key];

Expand Down
52 changes: 23 additions & 29 deletions packages/clerk-js/src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { camelToSnake, createDevOrStagingUrlCache, isIPV4Address } from '@clerk/shared';
import { camelToSnake, createDevOrStagingUrlCache, globs } from '@clerk/shared';
import type { SignUpResource } from '@clerk/types';

import { loadScript } from '../utils';
import { joinPaths } from './path';
import { getQueryParams } from './querystring';

Expand Down Expand Up @@ -54,33 +53,8 @@ export function isAccountsHostedPages(url: string | URL = window.location.hostna
return res;
}

export async function getETLDPlusOne(hostname: string = window.location.hostname): Promise<string> {
if (isIPV4Address(hostname)) {
return hostname;
}

const parts = hostname.split('.');

// Reuse dynamic loading of TLDParse library as in useTLDParser
if (parts.length >= 3) {
try {
await loadScript('https://cdn.jsdelivr.net/npm/tldts@5/dist/index.umd.min.js', {
globalObject: window.tldts,
});

return window.tldts.getDomain(hostname, {
allowPrivateDomains: true,
});
} catch (err) {
console.error('Failed to load tldts: ', err);
}

// Poor mans domain splitting if dynamic loading of tldts fails
const [, ...domain] = parts;
return domain.join('.');
}

return hostname;
export function getETLDPlusOneFromFrontendApi(frontendApi: string): string {
return frontendApi.replace('clerk.', '');
}

export function getAllETLDs(hostname: string = window.location.hostname): string[] {
Expand Down Expand Up @@ -375,3 +349,23 @@ export function isRedirectForFAPIInitiatedFlow(frontendApi: string, redirectUrl:

return frontendApi === url.host && frontendApiRedirectPaths.includes(path);
}

export const isAllowedRedirectOrigin = (_url: string, allowedRedirectOrigins: string[] | undefined) => {
if (!allowedRedirectOrigins) {
return true;
}

const url = new URL(_url, DUMMY_URL_BASE);
const isRelativeUrl = url.origin === DUMMY_URL_BASE;
if (isRelativeUrl) {
return true;
}

const isAllowed = allowedRedirectOrigins.some(origin => globs.toRegexp(origin).test(trimTrailingSlash(url.href)));
if (!isAllowed) {
console.warn(
`Clerk: Redirect URL ${url} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`,
);
}
return isAllowed;
};
5 changes: 4 additions & 1 deletion packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"@types/glob-to-regexp": "0.4.1",
"@types/js-cookie": "3.0.2",
"jest": "*",
"jest-environment-jsdom": "*",
Expand All @@ -38,8 +39,10 @@
},
"author": "",
"license": "ISC",
"gitHead": "1b19a43b61f712756ab4d8c9ccbee6e8bddbe4ce",
"publishConfig": {
"access": "public"
},
"dependencies": {
"glob-to-regexp": "0.4.1"
}
}
13 changes: 13 additions & 0 deletions packages/shared/src/utils/globs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import globToRegexp from 'glob-to-regexp';

export const globs = {
toRegexp: (pattern: string) => {
try {
return globToRegexp(pattern) as RegExp;
} catch (e: any) {
throw new Error(
`Invalid pattern: ${pattern}.\nConsult the documentation of glob-to-regexp here: https://www.npmjs.com/package/glob-to-regexp.\n${e.message}`,
);
}
},
};
1 change: 1 addition & 0 deletions packages/shared/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export * from './url';
export * from './workerTimers';
export * from './runWithExponentialBackOff';
export * from './isomorphicAtob';
export * from './globs';
1 change: 1 addition & 0 deletions packages/types/src/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ export interface ClerkOptions {
signUpUrl?: string;
afterSignInUrl?: string;
afterSignUpUrl?: string;
allowedRedirectOrigins?: string[];
/**
* @experimental
*/
Expand Down