2022-04-08 18:16:20 +08:00
|
|
|
import {
|
|
|
|
ApplicationType,
|
|
|
|
CustomClientMetadata,
|
|
|
|
customClientMetadataGuard,
|
2022-09-21 13:06:56 +08:00
|
|
|
GrantType,
|
2022-04-08 18:16:20 +08:00
|
|
|
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 && []),
|
|
|
|
};
|
|
|
|
};
|
2021-10-11 17:55:17 +08:00
|
|
|
|
2022-01-11 11:58:58 +08:00
|
|
|
export const buildOidcClientMetadata = (metadata?: OidcClientMetadata): OidcClientMetadata => ({
|
2021-08-26 13:05:23 +08:00
|
|
|
redirectUris: [],
|
|
|
|
postLogoutRedirectUris: [],
|
2021-10-11 17:55:17 +08:00
|
|
|
...metadata,
|
2021-08-18 00:24:00 +08:00
|
|
|
});
|
2022-04-08 18:16:20 +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);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-07-05 17:36:43 +08:00
|
|
|
export const isOriginAllowed = (
|
|
|
|
origin: string,
|
2022-07-05 21:09:57 +08:00
|
|
|
{ corsAllowedOrigins = [] }: CustomClientMetadata,
|
2022-07-05 17:36:43 +08:00
|
|
|
redirectUris: string[] = []
|
|
|
|
) => {
|
|
|
|
const redirectUriOrigins = redirectUris.map((uri) => new URL(uri).origin);
|
|
|
|
|
|
|
|
return [...corsAllowedOrigins, ...redirectUriOrigins].includes(origin);
|
|
|
|
};
|