Add 4 files, update 14 files

This commit is contained in:
[dyad] committed 2026-08-02 17:58:35 +02:00
1 parent 278293b397
commit 2913b0332f
18 files changed
+227 -22

No files matched your search

+1
View File
@@ -76,6 +76,7 @@ const sessionUserSelect = Prisma.validator<Prisma.UserSelect>()({
schoolId: true,
locale: true,
isDemo: true,
twoFactorSecret: true,
createdAt: true,
updatedAt: true,
});
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, test } from 'bun:test';
import { createRecoveryCodes, createTotpSecret, hashRecoveryCode, totpUri, verifyTotp } from './two-factor';
describe('two factor authentication', () => {
test('creates TOTP enrollment data', () => {
const secret = createTotpSecret();
expect(secret.length).toBeGreaterThan(10);
expect(totpUri('teacher@school.example', secret)).toStartWith('otpauth://totp/');
});
test('creates unique hashed recovery codes', () => {
const codes = createRecoveryCodes();
expect(codes).toHaveLength(10);
expect(new Set(codes).size).toBe(10);
expect(hashRecoveryCode(codes[0])).not.toBe(codes[0]);
});
test('rejects malformed TOTP values', () => {
expect(verifyTotp(createTotpSecret(), 'invalid')).toBeFalse();
});
});
+26
View File
@@ -0,0 +1,26 @@
import { createHash, randomBytes } from 'node:crypto';
import { TOTP } from 'otpauth';
const RECOVERY_CODE_COUNT = 10;
export function createTotpSecret(): string {
return new TOTP({ issuer: 'SchoolOS', label: 'SchoolOS account' }).secret.base32;
}
export function totpUri(email: string, secret: string): string {
return new TOTP({ issuer: 'SchoolOS', label: email, secret }).toString();
}
export function verifyTotp(secret: string, token: string): boolean {
const normalizedToken = token.replace(/\s/g, '');
if (!/^\d{6}$/.test(normalizedToken)) return false;
return new TOTP({ issuer: 'SchoolOS', label: 'SchoolOS account', secret }).validate({ token: normalizedToken, window: 1 }) !== null;
}
export function hashRecoveryCode(code: string): string {
return createHash('sha256').update(code).digest('hex');
}
export function createRecoveryCodes(): string[] {
return Array.from({ length: RECOVERY_CODE_COUNT }, () => randomBytes(5).toString('hex').toUpperCase());
}