refactor(auth): require bearer token only, drop legacy token header and cookie
Authenticate requests solely from the Authorization: Bearer header on the server; stop accepting the legacy `token` header and `usertoken` cookie. The frontend no longer sets auth cookies (only clears legacy ones), omits credentials on all requests, and drops the redundant `token` header. Project event SSE now streams over fetch so it can carry the Authorization header, which EventSource cannot. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,14 +2,15 @@ import type { AccountDevice, AuthCodeResponse, AuthOptions, AuthSession, AuthUse
|
||||
import { createApiFailure, createNetworkFailure } from "@/infrastructure/userMessages";
|
||||
|
||||
const sessionStorageKey = "img-infinite-canvas.auth.session";
|
||||
const accessTokenCookie = "usertoken";
|
||||
const refreshTokenCookie = "refreshToken";
|
||||
const legacyAccessTokenCookie = "usertoken";
|
||||
const legacyRefreshTokenCookie = "refreshToken";
|
||||
|
||||
async function request<T>(path: string, body: unknown): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
method: "POST",
|
||||
credentials: "omit",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
@@ -30,7 +31,7 @@ async function request<T>(path: string, body: unknown): Promise<T> {
|
||||
async function get<T>(path: string): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(path, { cache: "no-store" });
|
||||
response = await fetch(path, { cache: "no-store", credentials: "omit" });
|
||||
} catch (err) {
|
||||
throw createNetworkFailure("auth", err);
|
||||
}
|
||||
@@ -55,7 +56,8 @@ async function apiRequest<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
response = await fetch(path, {
|
||||
...init,
|
||||
headers,
|
||||
cache: "no-store"
|
||||
cache: "no-store",
|
||||
credentials: "omit"
|
||||
});
|
||||
} catch (err) {
|
||||
throw createNetworkFailure("auth", err);
|
||||
@@ -131,6 +133,7 @@ export const authGateway = {
|
||||
if (upload.uploadUrl && !upload.uploadUrl.includes("/memory-assets/")) {
|
||||
await fetch(upload.uploadUrl, {
|
||||
method: "PUT",
|
||||
credentials: "omit",
|
||||
headers: upload.headers,
|
||||
body: file
|
||||
});
|
||||
@@ -141,6 +144,7 @@ export const authGateway = {
|
||||
|
||||
export function readStoredAuthSession(): StoredAuthSession | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
clearLegacyAuthCookies();
|
||||
const raw = window.localStorage.getItem(sessionStorageKey);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
@@ -160,10 +164,7 @@ export function storeAuthSession(session: AuthSession): StoredAuthSession {
|
||||
const stored = { ...session, savedAt: Date.now() };
|
||||
if (typeof window !== "undefined") {
|
||||
window.localStorage.setItem(sessionStorageKey, JSON.stringify(stored));
|
||||
setCookie(accessTokenCookie, session.accessToken, session.expiresIn);
|
||||
if (session.refreshToken && session.refreshExpiresIn) {
|
||||
setCookie(refreshTokenCookie, session.refreshToken, session.refreshExpiresIn);
|
||||
}
|
||||
clearLegacyAuthCookies();
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
@@ -188,8 +189,7 @@ export function updateStoredAuthUser(userPatch: Partial<AuthUser>): StoredAuthSe
|
||||
export function clearStoredAuthSession() {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(sessionStorageKey);
|
||||
expireCookie(accessTokenCookie);
|
||||
expireCookie(refreshTokenCookie);
|
||||
clearLegacyAuthCookies();
|
||||
}
|
||||
|
||||
export function getAuthAccessToken() {
|
||||
@@ -197,11 +197,10 @@ export function getAuthAccessToken() {
|
||||
}
|
||||
|
||||
export function authHeaders() {
|
||||
const token = getAuthAccessToken();
|
||||
if (!token) return {};
|
||||
const accessToken = getAuthAccessToken();
|
||||
if (!accessToken) return {};
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
token
|
||||
Authorization: `Bearer ${accessToken}`
|
||||
} satisfies Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -210,8 +209,9 @@ function isSessionExpired(session: StoredAuthSession) {
|
||||
return expiresIn > 0 && session.savedAt + expiresIn * 1000 <= Date.now() + 30_000;
|
||||
}
|
||||
|
||||
function setCookie(name: string, value: string, maxAge: number) {
|
||||
document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.max(0, Math.floor(maxAge))}; SameSite=Lax`;
|
||||
function clearLegacyAuthCookies() {
|
||||
expireCookie(legacyAccessTokenCookie);
|
||||
expireCookie(legacyRefreshTokenCookie);
|
||||
}
|
||||
|
||||
function expireCookie(name: string) {
|
||||
|
||||
@@ -159,7 +159,8 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
...init,
|
||||
headers
|
||||
headers,
|
||||
credentials: "omit"
|
||||
});
|
||||
} catch (err) {
|
||||
throw createNetworkFailure("design", err);
|
||||
@@ -393,43 +394,56 @@ export const designGateway = {
|
||||
},
|
||||
|
||||
projectEvents(projectId: string, handlers: ProjectEventHandlers, options: ProjectEventsOptions = {}) {
|
||||
const source = new EventSource(projectEventsUrl(projectId, options));
|
||||
const controller = new AbortController();
|
||||
let settled = false;
|
||||
const readProject = (event: MessageEvent) => {
|
||||
const payload = JSON.parse(event.data) as { project: Project };
|
||||
const readProject = (data: string) => {
|
||||
const payload = JSON.parse(data) as { project: Project };
|
||||
return payload.project;
|
||||
};
|
||||
|
||||
source.addEventListener("project", (event) => handlers.onProject?.(readProject(event as MessageEvent)));
|
||||
source.addEventListener("thinking", (event) => handlers.onThinking?.(JSON.parse((event as MessageEvent).data) as AgentMessage));
|
||||
source.addEventListener("text_extraction", (event) => handlers.onTextExtraction?.(JSON.parse((event as MessageEvent).data) as ExtractNodeTextResponse));
|
||||
source.addEventListener("done", (event) => {
|
||||
const close = () => {
|
||||
settled = true;
|
||||
handlers.onDone?.(readProject(event as MessageEvent));
|
||||
source.close();
|
||||
});
|
||||
source.addEventListener("timeout", (event) => {
|
||||
settled = true;
|
||||
handlers.onTimeout?.(readProject(event as MessageEvent));
|
||||
source.close();
|
||||
});
|
||||
source.addEventListener("stream_error", (event) => {
|
||||
settled = true;
|
||||
if ((event as MessageEvent).data) {
|
||||
const payload = JSON.parse((event as MessageEvent).data) as { error?: string };
|
||||
handlers.onError?.(new Error(payload.error ?? "Event stream failed"));
|
||||
} else {
|
||||
handlers.onError?.(new Error("Event stream failed"));
|
||||
controller.abort();
|
||||
};
|
||||
const onEvent = (event: string, data: string) => {
|
||||
if (event === "project") {
|
||||
handlers.onProject?.(readProject(data));
|
||||
return;
|
||||
}
|
||||
if (event === "thinking") {
|
||||
handlers.onThinking?.(JSON.parse(data) as AgentMessage);
|
||||
return;
|
||||
}
|
||||
if (event === "text_extraction") {
|
||||
handlers.onTextExtraction?.(JSON.parse(data) as ExtractNodeTextResponse);
|
||||
return;
|
||||
}
|
||||
if (event === "done") {
|
||||
settled = true;
|
||||
handlers.onDone?.(readProject(data));
|
||||
controller.abort();
|
||||
return;
|
||||
}
|
||||
if (event === "timeout") {
|
||||
settled = true;
|
||||
handlers.onTimeout?.(readProject(data));
|
||||
controller.abort();
|
||||
return;
|
||||
}
|
||||
if (event === "stream_error") {
|
||||
settled = true;
|
||||
const payload = data ? (JSON.parse(data) as { error?: string }) : {};
|
||||
handlers.onError?.(new Error(payload.error ?? "Event stream failed"));
|
||||
controller.abort();
|
||||
}
|
||||
source.close();
|
||||
});
|
||||
source.onerror = () => {
|
||||
if (settled || source.readyState === EventSource.CLOSED) return;
|
||||
handlers.onError?.(new Error("Event stream failed"));
|
||||
source.close();
|
||||
};
|
||||
|
||||
return () => source.close();
|
||||
void streamProjectEvents(projectEventsUrl(projectId, options), controller.signal, onEvent).catch((error: Error) => {
|
||||
if (settled || controller.signal.aborted) return;
|
||||
settled = true;
|
||||
handlers.onError?.(error);
|
||||
});
|
||||
|
||||
return close;
|
||||
},
|
||||
|
||||
saveCanvas(
|
||||
@@ -507,6 +521,7 @@ export const designGateway = {
|
||||
if (upload.uploadUrl && !upload.uploadUrl.includes("/memory-assets/")) {
|
||||
await fetch(upload.uploadUrl, {
|
||||
method: "PUT",
|
||||
credentials: "omit",
|
||||
headers: upload.headers,
|
||||
body: file
|
||||
});
|
||||
@@ -866,3 +881,56 @@ function projectEventsUrl(projectId: string, options: ProjectEventsOptions) {
|
||||
const query = params.toString();
|
||||
return `/api/projects/${projectId}/events${query ? `?${query}` : ""}`;
|
||||
}
|
||||
|
||||
async function streamProjectEvents(url: string, signal: AbortSignal, onEvent: (event: string, data: string) => void) {
|
||||
const headers = new Headers();
|
||||
Object.entries(authHeaders()).forEach(([key, value]) => headers.set(key, value));
|
||||
const response = await fetch(url, {
|
||||
headers,
|
||||
signal,
|
||||
cache: "no-store",
|
||||
credentials: "omit"
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw createApiFailure("design", response, payload);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new Error("Event stream failed");
|
||||
}
|
||||
|
||||
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buffer = "";
|
||||
try {
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += value;
|
||||
const parts = buffer.split(/\r?\n\r?\n/);
|
||||
buffer = parts.pop() ?? "";
|
||||
parts.forEach((part) => emitServerSentEvent(part, onEvent));
|
||||
}
|
||||
if (buffer.trim()) {
|
||||
emitServerSentEvent(buffer, onEvent);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function emitServerSentEvent(raw: string, onEvent: (event: string, data: string) => void) {
|
||||
let event = "message";
|
||||
const data: string[] = [];
|
||||
raw.split(/\r?\n/).forEach((line) => {
|
||||
if (line.startsWith("event:")) {
|
||||
event = line.slice("event:".length).trim();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith("data:")) {
|
||||
data.push(line.slice("data:".length).trimStart());
|
||||
}
|
||||
});
|
||||
if (data.length > 0) {
|
||||
onEvent(event, data.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user