import 'server-only'
import { timingSafeEqual } from 'crypto'

// Agent endpoints authenticate with a static bearer token (AGENT_TOKEN),
// never the session cookie. The Mac agent presents it on every request.
export function checkAgentAuth(req: Request): boolean {
  const expected = process.env.AGENT_TOKEN
  if (!expected) return false
  const header = req.headers.get('authorization') || ''
  const m = header.match(/^Bearer\s+(.+)$/i)
  if (!m) return false
  const got = Buffer.from(m[1])
  const want = Buffer.from(expected)
  if (got.length !== want.length) return false
  return timingSafeEqual(got, want)
}

// The agent includes the callback secret when posting results back, as a
// second factor distinct from the read token.
export function checkCallbackSecret(req: Request): boolean {
  const expected = process.env.AGENT_CALLBACK_SECRET
  if (!expected) return true // not configured → skip (dev)
  const got = req.headers.get('x-callback-secret') || ''
  const a = Buffer.from(got)
  const b = Buffer.from(expected)
  if (a.length !== b.length) return false
  return timingSafeEqual(a, b)
}
