0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-06 20:40:08 -05:00
logto/packages/core/src/init/oidc.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-06-27 07:44:05 -05:00
import crypto from 'crypto';
import Koa from 'koa';
import mount from 'koa-mount';
import { Provider } from 'oidc-provider';
2021-07-02 09:55:14 -05:00
import postgresAdapter from '@/oidc/adapter';
2021-06-27 07:44:05 -05:00
import { fromKeyLike } from 'jose/jwk/from_key_like';
import { getEnv } from '@/utils/env';
2021-07-02 09:55:14 -05:00
import { findUserById } from '@/queries/user';
2021-07-04 02:01:02 -05:00
import { routes } from '@/consts';
2021-06-27 07:44:05 -05:00
export default async function initOidc(app: Koa, port: number): Promise<Provider> {
2021-06-27 07:44:05 -05:00
const privateKey = crypto.createPrivateKey(
Buffer.from(getEnv('OIDC_PROVIDER_PRIVATE_KEY_BASE64'), 'base64')
);
const keys = [await fromKeyLike(privateKey)];
2021-07-04 02:01:02 -05:00
const cookieConfig = Object.freeze({
sameSite: 'lax',
path: '/',
signed: true,
} as const);
2021-06-27 07:44:05 -05:00
const oidc = new Provider(`http://localhost:${port}/oidc`, {
adapter: postgresAdapter,
renderError: (ctx, out, error) => {
2021-07-04 02:01:02 -05:00
console.log('OIDC error', error);
2021-06-27 07:44:05 -05:00
},
cookies: {
// V2: Rotate this when necessary
// https://github.com/panva/node-oidc-provider/blob/main/docs/README.md#cookieskeys
keys: ['LOGTOSEKRIT1'],
2021-07-04 02:01:02 -05:00
long: cookieConfig,
short: cookieConfig,
2021-06-27 07:44:05 -05:00
},
jwks: {
keys,
},
features: {
revocation: { enabled: true },
introspection: { enabled: true },
devInteractions: { enabled: false },
},
interactions: {
2021-07-04 02:01:02 -05:00
url: (_, interaction) => {
switch (interaction.prompt.name) {
case 'login':
return routes.signIn.credentials;
case 'consent':
return routes.signIn.consent;
default:
throw new Error(`Prompt not supported: ${interaction.prompt.name}`);
}
},
},
clientBasedCORS: (_, origin) => {
console.log('origin', origin);
2021-06-29 09:58:59 -05:00
return origin.startsWith('http://localhost:3000');
},
findAccount: async (ctx, sub) => {
await findUserById(sub);
2021-06-27 07:44:05 -05:00
return {
accountId: sub,
claims: async (use, scope, claims, rejected) => {
console.log('use:', use);
console.log('scope:', scope);
console.log('claims:', claims);
console.log('rejected:', rejected);
2021-06-27 07:44:05 -05:00
return { sub };
},
};
},
});
app.use(mount('/oidc', oidc.app));
return oidc;
2021-06-27 07:44:05 -05:00
}