ai-chatbot/services/pascal-editor/apps/editor/lib/pascal-agent-access.ts

26 lines
914 B
TypeScript

import { timingSafeEqual } from 'node:crypto'
export const PASCAL_AGENT_PROXY_HEADER = 'x-pascal-agent-proxy-secret'
export type PascalAgentAccessResult = 'allowed' | 'missing_proxy_secret' | 'unauthorized'
function safeEqual(left: string, right: string): boolean {
const leftBuffer = Buffer.from(left)
const rightBuffer = Buffer.from(right)
if (leftBuffer.length !== rightBuffer.length) return false
return timingSafeEqual(leftBuffer, rightBuffer)
}
export function validatePascalAgentAccess(
headers: Headers,
env: NodeJS.ProcessEnv = process.env,
): PascalAgentAccessResult {
const expected = env.PASCAL_AGENT_PROXY_SECRET?.trim() ?? ''
if (!expected) {
return env.NODE_ENV === 'production' ? 'missing_proxy_secret' : 'allowed'
}
const supplied = headers.get(PASCAL_AGENT_PROXY_HEADER)?.trim() ?? ''
return supplied && safeEqual(supplied, expected) ? 'allowed' : 'unauthorized'
}