import crypto from 'crypto'

export function generatePublicAccessToken() {
  const token = crypto.randomBytes(32).toString('base64url')
  return { token, tokenHash: hashPublicAccessToken(token) }
}

export function hashPublicAccessToken(token: string) {
  return crypto.createHash('sha256').update(token).digest('hex')
}

export function timingSafeEqualTokenHash(a: string, b: string) {
  const left = Buffer.from(a, 'hex')
  const right = Buffer.from(b, 'hex')
  if (left.length !== right.length) return false
  return crypto.timingSafeEqual(left, right)
}
