Spaces:
Running

WorkPilot-AI / web /src /lib /session.ts
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
4.4 kB
// Token storage for the browser.
//
// - The access token (15 min) lives only in this module's memory: never in localStorage or
// a readable cookie, so a page reload drops it and an XSS payload cannot lift it from storage.
// - The refresh token (14 days) is held by the Next.js server in an httpOnly, SameSite=Strict
// cookie scoped to /api/session (see src/app/api/session/[action]/route.ts). Browser JS never
// sees it; a reload calls /api/session/refresh to get a fresh access token.
// - The step-up token (5 min, from POST /auth/stepup) is memory-only too.
//
// Trade-off: the refresh exchange goes through the Next.js server (a small BFF), so the web
// app needs a Node runtime rather than static hosting, and an XSS can still *use* the session
// while the page is open (it cannot exfiltrate the long-lived token).
let accessToken: string | null = null;
let stepup: { token: string; expiresAt: number } | null = null;
let refreshing: Promise<string | null> | null = null;
const listeners = new Set<() => void>();
export function getAccessToken(): string | null {
return accessToken;
}
export function setAccessToken(token: string | null): void {
accessToken = token;
if (!token) stepup = null;
}
export function getStepupToken(now = Date.now()): string | null {
return stepup && stepup.expiresAt > now ? stepup.token : null;
}
export function setStepupToken(token: string, ttlMs = 4.5 * 60_000): void {
stepup = { token, expiresAt: Date.now() + ttlMs };
}
export function onSessionExpired(fn: () => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
export function notifySessionExpired(): void {
for (const fn of listeners) fn();
}
export class SessionError extends Error {
constructor(
message: string,
public status: number,
) {
super(message);
}
}
async function sessionCall(
action: "login" | "signup" | "refresh" | "logout" | "switch",
body?: unknown,
): Promise<{ access_token: string; tenant_id: string } | null> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
// Custom header: a cross-site form cannot send it, and fetch would need a preflight.
"X-Requested-With": "workpilot",
};
if (action === "switch" && accessToken) headers.Authorization = `Bearer ${accessToken}`;
const res = await fetch(`/api/session/${action}`, {
method: "POST",
headers,
body: body === undefined ? undefined : JSON.stringify(body),
credentials: "same-origin",
cache: "no-store",
});
if (action === "logout") return null;
const data = (await res.json().catch(() => ({}))) as {
access_token?: string;
tenant_id?: string;
detail?: unknown;
};
if (!res.ok || !data.access_token || !data.tenant_id) {
const detail = typeof data.detail === "string" ? data.detail : res.statusText;
throw new SessionError(detail || "request failed", res.status);
}
return { access_token: data.access_token, tenant_id: data.tenant_id };
}
export async function login(email: string, password: string): Promise<void> {
const r = await sessionCall("login", { email, password });
setAccessToken(r?.access_token ?? null);
}
export async function signup(business_name: string, email: string, password: string) {
const r = await sessionCall("signup", { business_name, email, password });
setAccessToken(r?.access_token ?? null);
}
export async function switchTenant(tenant_id: string): Promise<void> {
const r = await sessionCall("switch", { tenant_id });
setAccessToken(r?.access_token ?? null);
stepup = null;
}
export async function logout(): Promise<void> {
setAccessToken(null);
await sessionCall("logout").catch(() => null);
}
/** Exchange the httpOnly refresh cookie for a new access token. Concurrent callers share one
* request (the refresh token rotates, so parallel refreshes would race). */
export function refreshAccessToken(): Promise<string | null> {
if (!refreshing) {
refreshing = sessionCall("refresh")
.then((r) => {
setAccessToken(r?.access_token ?? null);
return accessToken;
})
.catch(() => {
setAccessToken(null);
return null;
})
.finally(() => {
refreshing = null;
});
}
return refreshing;
}