refactor: extract api token hash and equality checks

As we need these functions for the seeding it makes sense to extract them into the password.ts and test them accordingly.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2025-03-13 22:49:56 +01:00 committed by Erik Michelson
parent b696c1e661
commit 539ea7e33b
No known key found for this signature in database
GPG key ID: DB99ADDDC5C0AF82
3 changed files with 78 additions and 18 deletions

View file

@ -17,7 +17,7 @@ import {
TooManyTokensError,
} from '../errors/errors';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { bufferToBase64Url } from '../utils/password';
import { bufferToBase64Url, checkTokenEquality } from '../utils/password';
import { ApiToken } from './api-token.entity';
export const AUTH_TOKEN_PREFIX = 'hd2';
@ -47,7 +47,7 @@ export class ApiTokenService {
const token = await this.getToken(keyId);
this.checkToken(secret, token);
await this.setLastUsedToken(keyId);
return await token.user;
return token.user;
}
createToken(
@ -126,16 +126,7 @@ export class ApiTokenService {
}
checkToken(secret: string, token: ApiToken): void {
const userHash = Buffer.from(
createHash('sha512').update(secret).digest('hex'),
);
const dbHash = Buffer.from(token.hash);
if (
// Normally, both hashes have the same length, as they are both SHA512
// This is only defense-in-depth, as timingSafeEqual throws if the buffers are not of the same length
userHash.length !== dbHash.length ||
!timingSafeEqual(userHash, dbHash)
) {
if (!checkTokenEquality(secret, token.hash)) {
// hashes are not the same
throw new TokenNotValidError(
`Secret does not match Token ${token.label}.`,