File size: 1,287 Bytes
9853b20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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<string> {
  return bcrypt.hash(pin, 10)
}

export async function verifyPin(pin: string, hash: string): Promise<boolean> {
  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 }
}