// Account rollout is opt-in. Never fall back to the shared passphrase in account mode. export interface AccountConfig { AUTH_MODE?: string; GOOGLE_AUTH_ENABLED?: string; SUPABASE_URL?: string; SUPABASE_PUBLISHABLE_KEY?: string; } export type Access = 'pending' | 'approved' | 'blocked'; export interface Account { id: string; email: string; status: Access; owner: boolean } const COOKIE = '__Host-zs-account'; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export function accountConfig(env: AccountConfig) { if (!env.SUPABASE_URL || !env.SUPABASE_PUBLISHABLE_KEY) throw new Error('Account setup is incomplete'); const url = new URL(env.SUPABASE_URL); if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('Invalid account provider'); return {url: url.origin, key: env.SUPABASE_PUBLISHABLE_KEY}; } export function accountToken(request: Request): string | undefined { const values = (request.headers.get('cookie') || '').split(';').map(x => x.trim()).filter(x => x.startsWith(COOKIE + '=')); if (values.length !== 1) return; const value = values[0].slice(COOKIE.length + 1); return /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value) && value.length <= 8192 ? value : undefined; } async function provider(env: AccountConfig, token: string, path: string, body?: unknown) { const {url,key} = accountConfig(env); return fetch(url + path, { method: body === undefined ? 'GET' : 'POST', redirect: 'manual', headers: {apikey:key, authorization:'Bearer ' + token, 'content-type':'application/json'}, ...(body === undefined ? {} : {body:JSON.stringify(body)}), signal:AbortSignal.timeout(8000), }); } export async function verifiedAccount(env: AccountConfig, token?: string): Promise { if (!token) return null; // Ask Auth to verify the token; neither a decoded JWT nor user-editable metadata grants access. const identity = await provider(env,token,'/auth/v1/user'); if (identity.status === 401 || identity.status === 403) return null; if (!identity.ok) throw new Error('Account provider unavailable'); const user = await identity.json() as {id?:string; email?:string; email_confirmed_at?:string}; if (!user.id || !UUID.test(user.id) || !user.email || !user.email_confirmed_at) return null; const response = await provider(env,token,'/rest/v1/rpc/my_access',{}); if (!response.ok) throw new Error('Access check unavailable'); const rows = await response.json() as Array<{user_id:string; status:Access; owner:boolean}>; const row = Array.isArray(rows) && rows.length === 1 ? rows[0] : undefined; if (!row || row.user_id !== user.id || !['pending','approved','blocked'].includes(row.status) || typeof row.owner !== 'boolean') throw new Error('Invalid access record'); return {id:user.id,email:user.email,status:row.status,owner:row.owner}; } export async function accountSession(request: Request, env: AccountConfig): Promise { const headers = new Headers({'cache-control':'no-store'}); if (request.method === 'DELETE') { headers.set('set-cookie',COOKIE + '=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0'); return new Response(null,{status:204,headers}); } let token = accountToken(request); if (request.method === 'POST') { // The browser completes the provider flow, then exchanges its access token for an HttpOnly cookie. const auth = request.headers.get('authorization') || ''; if (auth.length > 8200 || !/^Bearer [A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(auth)) return Response.json({error:'Sign in first.'},{status:401,headers}); token = auth.slice(7); } else if (request.method !== 'GET') return new Response(null,{status:405,headers:{allow:'GET, POST, DELETE'}}); const account = await verifiedAccount(env,token); if (!account) return Response.json({authenticated:false},{status:request.method === 'POST' ? 401 : 200,headers}); if (request.method === 'POST') headers.set('set-cookie',COOKIE + '=' + token + '; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600'); return Response.json({authenticated:true,allowed:account.status === 'approved',account},{headers}); }