import bcrypt from 'bcryptjs' import { getCodeByCode } from './persistence' export function generateCode(): string { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' let result = '' for (let i = 0; i < 5; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)) } return result } export function validateCodeFormat(code: string): boolean { return /^[A-Z0-9]{5}$/.test(code.toUpperCase()) } export async function hashPin(pin: string): Promise { return bcrypt.hash(pin, 10) } export async function verifyPin(pin: string, hash: string): Promise { return bcrypt.compare(pin, hash) } export function generateSessionHash(code: string, userAgent: string): string { const timestamp = Date.now().toString() const combined = `${code}${timestamp}${userAgent}` return btoa(combined).substring(0, 32) } export async function createCodePair(): Promise<{ code1: string, code2: string }> { const code1 = generateCode() const code2 = generateCode() // Ensure uniqueness by checking persistence (local-first) const [existing1, existing2] = await Promise.all([getCodeByCode(code1), getCodeByCode(code2)]) if (existing1 || existing2) { return createCodePair() } return { code1, code2 } }