Spaces:
Running

File size: 4,403 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// 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;
}