refactor(crypto): reorganize token hashing and signing functionality

This commit is contained in:
Danny Avila 2025-05-30 14:38:01 -04:00
parent 6f4c8ef114
commit 494c6d2596
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956
10 changed files with 27 additions and 66 deletions

View file

@ -0,0 +1,17 @@
import jwt from 'jsonwebtoken';
import { webcrypto } from 'node:crypto';
import { SignPayloadParams } from '~/types';
export async function signPayload({
payload,
secret,
expirationTime,
}: SignPayloadParams): Promise<string> {
return jwt.sign(payload, secret!, { expiresIn: expirationTime });
}
export async function hashToken(str: string): Promise<string> {
const data = new TextEncoder().encode(str);
const hashBuffer = await webcrypto.subtle.digest('SHA-256', data);
return Buffer.from(hashBuffer).toString('hex');
}

View file

@ -1,3 +1,4 @@
export * from './crypto';
export { createModels } from './models';
export { createMethods } from './methods';
export type * from './types';

View file

@ -1,5 +1,5 @@
import type * as t from '~/types/session';
import { signPayload, hashToken } from '~/schema/session';
import { signPayload, hashToken } from '~/crypto';
import logger from '~/config/winston';
export class SessionError extends Error {

View file

@ -1,6 +1,6 @@
import mongoose, { FilterQuery } from 'mongoose';
import { IUser, BalanceConfig, UserCreateData, UserUpdateResult } from '~/types';
import { signPayload } from '~/schema/session';
import type { IUser, BalanceConfig, UserCreateData, UserUpdateResult } from '~/types';
import { signPayload } from '~/crypto';
/** Factory function that takes mongoose instance and returns the methods */
export function createUserMethods(mongoose: typeof import('mongoose')) {

View file

@ -1,7 +1,5 @@
import mongoose, { Schema } from 'mongoose';
import jwt from 'jsonwebtoken';
import { webcrypto } from 'node:crypto';
import { ISession, SignPayloadParams } from '~/types';
import { ISession } from '~/types';
const sessionSchema: Schema<ISession> = new Schema({
refreshTokenHash: {
@ -20,18 +18,4 @@ const sessionSchema: Schema<ISession> = new Schema({
},
});
export async function signPayload({
payload,
secret,
expirationTime,
}: SignPayloadParams): Promise<string> {
return jwt.sign(payload, secret!, { expiresIn: expirationTime });
}
export async function hashToken(str: string): Promise<string> {
const data = new TextEncoder().encode(str);
const hashBuffer = await webcrypto.subtle.digest('SHA-256', data);
return Buffer.from(hashBuffer).toString('hex');
}
export default sessionSchema;