0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-02-03 21:48:55 -05:00
logto/packages/core/src/oidc/utils.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

import {
ApplicationType,
CustomClientMetadata,
customClientMetadataGuard,
2022-09-21 13:06:56 +08:00
GrantType,
OidcClientMetadata,
} from '@logto/schemas';
2022-09-21 13:06:56 +08:00
import { conditional } from '@silverhand/essentials';
import { AllClientMetadata, ClientAuthMethod, errors } from 'oidc-provider';
2021-08-18 00:24:00 +08:00
2022-09-21 13:06:56 +08:00
export const getConstantClientMetadata = (
type: ApplicationType
): Pick<
AllClientMetadata,
'application_type' | 'grant_types' | 'token_endpoint_auth_method' | 'response_types'
> => {
const getTokenEndpointAuthMethod = (): ClientAuthMethod => {
switch (type) {
case ApplicationType.Native:
case ApplicationType.SPA:
return 'none';
default:
return 'client_secret_basic';
}
};
return {
application_type: type === ApplicationType.Native ? 'native' : 'web',
grant_types:
type === ApplicationType.MachineToMachine
? [GrantType.ClientCredentials]
: [GrantType.AuthorizationCode, GrantType.RefreshToken],
token_endpoint_auth_method: getTokenEndpointAuthMethod(),
response_types: conditional(type === ApplicationType.MachineToMachine && []),
};
};
export const buildOidcClientMetadata = (metadata?: OidcClientMetadata): OidcClientMetadata => ({
redirectUris: [],
postLogoutRedirectUris: [],
...metadata,
2021-08-18 00:24:00 +08:00
});
export const validateCustomClientMetadata = (key: string, value: unknown) => {
const result = customClientMetadataGuard.pick({ [key]: true }).safeParse({ [key]: value });
if (!result.success) {
throw new errors.InvalidClientMetadata(key);
}
};
export const isOriginAllowed = (
origin: string,
{ corsAllowedOrigins = [] }: CustomClientMetadata,
redirectUris: string[] = []
) => {
const redirectUriOrigins = redirectUris.map((uri) => new URL(uri).origin);
return [...corsAllowedOrigins, ...redirectUriOrigins].includes(origin);
};