#!/usr/bin/env node
import{randomBytes as e,timingSafeEqual as t}from"node:crypto";import*as n from"node:fs";import{join as r}from"node:path";import{homedir as i}from"node:os";const a=r(i(),`.aikit`);function o(e){let t=e?.tokenDir??a;return{tokenDir:t,tokenFile:r(t,`token`)}}function s(e,n){let r=Buffer.from(e),i=Buffer.from(n);return r.length===i.length?t(r,i):!1}function c(t){let{tokenDir:r,tokenFile:i}=o(t);if(n.existsSync(i)){let e=n.readFileSync(i,`utf-8`).trim();if(e.length>0)return e}n.existsSync(r)||n.mkdirSync(r,{recursive:!0,mode:448});let a=e(32).toString(`hex`);return n.writeFileSync(i,a,{mode:384}),a}function l(e){return(t,n,r)=>{if(t.path===`/health`||t.path===`/healthz`){r();return}let i=t.headers.authorization;if(!i?.startsWith(`Bearer `)){n.status(401).json({error:`Unauthorized: Bearer token required`});return}if(!s(i.slice(7).trim(),e)){n.status(401).json({error:`Unauthorized: Invalid token`});return}r()}}function u(e){try{let{tokenFile:t}=o(e);return n.readFileSync(t,`utf-8`).trim()}catch{return}}export{l as authMiddleware,c as getOrCreateToken,u as readToken};