Files
canina/backend/src/hermes-management/hermes-session-broker.ts
T

36 lines
2.3 KiB
TypeScript

import { HermesError } from './hermes.adapter';
export class HermesSessionBroker {
private cached: {token:string;until:number}|undefined;
private pending: Promise<string>|undefined;
constructor(private readonly credentials:()=>Promise<{username:string;password:string}>,private readonly fetcher:typeof fetch=fetch) {}
token():Promise<string>{
if(this.cached && this.cached.until>Date.now()) return Promise.resolve(this.cached.token);
if(this.pending) return this.pending;
this.pending=this.login().finally(()=>{this.pending=undefined;});
return this.pending;
}
private async login():Promise<string>{
const controller=new AbortController();
const timer=setTimeout(()=>controller.abort(),5000);
try{
const creds=await Promise.race([this.credentials(),new Promise<never>((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new HermesError('UNAVAILABLE')),{once:true}))]);
if(!creds.username || !creds.password) throw new HermesError('AUTH_REQUIRED');
const response=await this.fetcher('http://canina-hermes:9119/auth/password-login',{method:'POST',redirect:'error',signal:controller.signal,headers:{'Content-Type':'application/json'},body:JSON.stringify({provider:'basic',...creds})});
if(!response.ok) throw new HermesError('AUTH_REQUIRED');
const reader=response.body?.getReader();
if(!reader) throw new HermesError('AUTH_REQUIRED');
const chunks:Uint8Array[]=[];let size=0;
try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096)throw new HermesError('AUTH_REQUIRED');chunks.push(value);}}finally{await reader.cancel().catch(()=>undefined);}
const body=JSON.parse(Buffer.concat(chunks).toString('utf8')) as {ok?:unknown};
const cookies=response.headers.getSetCookie();
const cookie=cookies.find(c=>c.startsWith('hermes_session_at='));
const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1];
const age=Number(cookie?.match(/(?:^|;)\s*Max-Age=(\d+)/i)?.[1]);
if(body.ok!==true || !token || !Number.isSafeInteger(age) || age<30)throw new HermesError('AUTH_REQUIRED');
this.cached={token,until:Date.now()+Math.min(age-10,300)*1000};
return token;
}catch(error){if(error instanceof HermesError)throw error;throw new HermesError('UNAVAILABLE');}
finally{clearTimeout(timer);}
}
}