import { AsyncLocalStorage } from 'node:async_hooks'; const requester = new AsyncLocalStorage<{ username: string | null; active: boolean }>(); /** Use only the authenticated session, and stop attribution when the request finishes. */ export async function withRequestUsername( username: string | null, work: () => T | Promise ): Promise { const context = { username, active: true }; return requester.run(context, async () => { try { return await work(); } finally { context.active = false; } }); } export function currentRequestUsername(): string | null { const context = requester.getStore(); return context?.active ? context.username : null; }