import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{randomBytes as t,timingSafeEqual as n}from"node:crypto";import*as r from"node:fs";import{join as i}from"node:path";import{homedir as a}from"node:os";var o=e({authMiddleware:()=>d,getOrCreateToken:()=>u,readToken:()=>f});const s=i(a(),`.aikit`);function c(e){let t=e?.tokenDir??s;return{tokenDir:t,tokenFile:i(t,`token`)}}function l(e,t){let r=Buffer.from(e),i=Buffer.from(t);return r.length===i.length?n(r,i):!1}function u(e){let{tokenDir:n,tokenFile:i}=c(e);if(r.existsSync(i)){let e=r.readFileSync(i,`utf-8`).trim();if(e.length>0)return e}r.existsSync(n)||r.mkdirSync(n,{recursive:!0,mode:448});let a=t(32).toString(`hex`);return r.writeFileSync(i,a,{mode:384}),a}function d(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(!l(i.slice(7).trim(),e)){n.status(401).json({error:`Unauthorized: Invalid token`});return}r()}}function f(e){try{let{tokenFile:t}=c(e);return r.readFileSync(t,`utf-8`).trim()}catch{return}}export{f as n,o as t};