Skip to content

Commit

Permalink
fix: stable public and private key generation
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jul 15, 2024
1 parent 7fb613f commit 182bce7
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 32 deletions.
20 changes: 5 additions & 15 deletions server/api/private/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import assert from 'assert';
import type { UserEntity } from 'common/types/user';
import { userQuery } from 'domain/user/repository/userQuery';
import type { JWT_PROP_NAME } from 'service/constants';
import { prismaClient } from 'service/prismaClient';
import type { IdTokenJwt } from 'service/types';
import { defineHooks } from './$relay';

export type AdditionalRequest = {
[Key in typeof JWT_PROP_NAME]: IdTokenJwt;
} & { user: UserEntity };
export type AdditionalRequest = { user: UserEntity };

export default defineHooks(() => ({
onRequest: async (req, res) => {
try {
await req.jwtVerify({ onlyCookie: true });
} catch (e) {
res.status(401).send((e as Error).message);
return;
}

assert(req.idToken);

req.user = await userQuery.findById(prismaClient, req.idToken.sub);
req.user = await req
.jwtVerify<IdTokenJwt>({ onlyCookie: true })
.then((idToken) => userQuery.findById(prismaClient, idToken.sub))
.catch((e) => res.status(401).send((e as Error).message));
},
}));
18 changes: 11 additions & 7 deletions server/domain/userPool/useCase/userPoolUseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ import { userPoolQuery } from '../repository/userPoolQuery';

export const userPoolUseCase = {
initDefaults: async (): Promise<void> => {
const pool = userPoolMethod.create({ id: DEFAULT_USER_POOL_ID });
const poolClient = userPoolMethod.createClient({
id: DEFAULT_USER_POOL_CLIENT_ID,
userPoolId: DEFAULT_USER_POOL_ID,
});
await userPoolQuery
.findById(prismaClient, DEFAULT_USER_POOL_ID)
.catch(() => userPoolCommand.save(userPoolMethod.create({ id: DEFAULT_USER_POOL_ID })));

await userPoolCommand.save(pool);
await userPoolCommand.saveClient(poolClient);
await userPoolQuery.findClientById(prismaClient, DEFAULT_USER_POOL_CLIENT_ID).catch(() =>
userPoolCommand.saveClient(
userPoolMethod.createClient({
id: DEFAULT_USER_POOL_CLIENT_ID,
userPoolId: DEFAULT_USER_POOL_ID,
}),
),
);
},
listUserPools: async (
req: ListUserPoolsTarget['reqBody'],
Expand Down
3 changes: 1 addition & 2 deletions server/service/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Fastify from 'fastify';
import buildGetJwks from 'get-jwks';
import { join } from 'path';
import server from '../$server';
import { COOKIE_NAME, JWT_PROP_NAME } from './constants';
import { COOKIE_NAME } from './constants';

export const init = (): FastifyInstance => {
const fastify = Fastify();
Expand All @@ -27,7 +27,6 @@ export const init = (): FastifyInstance => {
},
);
fastify.register(fastifyJwt, {
decoratorName: JWT_PROP_NAME,
cookie: { cookieName: COOKIE_NAME, signed: false },
decode: { complete: true },
secret: (_: FastifyRequest, token: TokenOrHeader) => {
Expand Down
2 changes: 0 additions & 2 deletions server/service/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const COOKIE_NAME = 'session';

export const JWT_PROP_NAME = 'idToken';

export const EXPIRES_SEC = 3600;
12 changes: 6 additions & 6 deletions server/service/privateKey.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Jwks } from 'common/types/userPool';
import { createPublicKey, generateKeyPairSync } from 'crypto';
import { createHash, createPublicKey, generateKeyPairSync } from 'crypto';
import { JWK } from 'node-jose';

export const genPrivatekey = (): string => {
Expand All @@ -15,10 +15,10 @@ export const genPrivatekey = (): string => {
export const genJwks = async (privateKey: string): Promise<Jwks> => {
const keystore = JWK.createKeyStore();
const publicKey = createPublicKey(privateKey);
await keystore.add(publicKey.export({ type: 'spki', format: 'pem' }), 'pem', {
alg: 'RS256',
use: 'sig',
});
const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' });
const kid = createHash('sha256').update(publicKeyPem).digest('base64url');

await keystore.add(publicKeyPem, 'pem', { alg: 'RS256', use: 'sig', kid });

return keystore.toJSON(true) as Jwks;
return keystore.toJSON() as Jwks;
};

0 comments on commit 182bce7

Please sign in to comment.