mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-14 05:39:08 +02:00
* fix(security): use first-message auth for WebSocket instead of URL query param Token was exposed in URL query parameters (HIGH-4 from security audit), visible in server/proxy logs, browser history, and referrer headers. Now non-cookie clients (desktop, CLI) send the token as the first WebSocket message after the connection opens. Cookie-based auth (web) continues to work unchanged. Server-side auth priority flipped to cookie-first. Closes MUL-580 * fix(security): add auth_ack and fix test JSON construction Server sends auth_ack after successful first-message auth so the client knows auth completed before firing reconnect callbacks. Test now uses json.Marshal instead of string concatenation for the auth message. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(test): update WebSocket integration test for first-message auth The integration test still passed the token as a URL query param, causing a timeout since the server now expects first-message auth for non-cookie clients. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: yushen <ldnvnbl@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
143 lines
4.1 KiB
TypeScript
143 lines
4.1 KiB
TypeScript
import type { WSMessage, WSEventType } from "../types/events";
|
|
import { type Logger, noopLogger } from "../logger";
|
|
|
|
type EventHandler = (payload: unknown, actorId?: string) => void;
|
|
|
|
export class WSClient {
|
|
private ws: WebSocket | null = null;
|
|
private baseUrl: string;
|
|
private token: string | null = null;
|
|
private workspaceId: string | null = null;
|
|
private cookieAuth = false;
|
|
private handlers = new Map<WSEventType, Set<EventHandler>>();
|
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private hasConnectedBefore = false;
|
|
private onReconnectCallbacks = new Set<() => void>();
|
|
private anyHandlers = new Set<(msg: WSMessage) => void>();
|
|
private logger: Logger;
|
|
|
|
constructor(url: string, options?: { logger?: Logger; cookieAuth?: boolean }) {
|
|
this.baseUrl = url;
|
|
this.logger = options?.logger ?? noopLogger;
|
|
this.cookieAuth = options?.cookieAuth ?? false;
|
|
}
|
|
|
|
setAuth(token: string | null, workspaceId: string) {
|
|
this.token = token;
|
|
this.workspaceId = workspaceId;
|
|
}
|
|
|
|
connect() {
|
|
const url = new URL(this.baseUrl);
|
|
// Token is never sent as a URL query parameter — it would be logged by
|
|
// proxies, CDNs, and browser history. In cookie mode the HttpOnly cookie
|
|
// is sent automatically with the upgrade request. In token mode the token
|
|
// is delivered as the first WebSocket message after the connection opens.
|
|
if (this.workspaceId)
|
|
url.searchParams.set("workspace_id", this.workspaceId);
|
|
|
|
this.ws = new WebSocket(url.toString());
|
|
|
|
this.ws.onopen = () => {
|
|
if (!this.cookieAuth && this.token) {
|
|
this.ws!.send(
|
|
JSON.stringify({ type: "auth", payload: { token: this.token } }),
|
|
);
|
|
return;
|
|
}
|
|
|
|
this.onAuthenticated();
|
|
};
|
|
|
|
this.ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data as string) as WSMessage;
|
|
if ((msg as any).type === "auth_ack") {
|
|
this.onAuthenticated();
|
|
return;
|
|
}
|
|
this.logger.debug("received", msg.type);
|
|
const eventHandlers = this.handlers.get(msg.type);
|
|
if (eventHandlers) {
|
|
for (const handler of eventHandlers) {
|
|
handler(msg.payload, msg.actor_id);
|
|
}
|
|
}
|
|
for (const handler of this.anyHandlers) {
|
|
handler(msg);
|
|
}
|
|
};
|
|
|
|
this.ws.onclose = () => {
|
|
this.logger.warn("disconnected, reconnecting in 3s");
|
|
this.reconnectTimer = setTimeout(() => this.connect(), 3000);
|
|
};
|
|
|
|
this.ws.onerror = () => {
|
|
// Suppress — onclose handles reconnect; errors during StrictMode
|
|
// double-fire are expected in dev and harmless.
|
|
};
|
|
}
|
|
|
|
private onAuthenticated() {
|
|
this.logger.info("connected");
|
|
if (this.hasConnectedBefore) {
|
|
for (const cb of this.onReconnectCallbacks) {
|
|
try {
|
|
cb();
|
|
} catch {
|
|
// ignore reconnect callback errors
|
|
}
|
|
}
|
|
}
|
|
this.hasConnectedBefore = true;
|
|
}
|
|
|
|
disconnect() {
|
|
if (this.reconnectTimer) {
|
|
clearTimeout(this.reconnectTimer);
|
|
this.reconnectTimer = null;
|
|
}
|
|
if (this.ws) {
|
|
// Remove handlers before close to prevent onclose from scheduling a reconnect
|
|
this.ws.onclose = null;
|
|
this.ws.onerror = null;
|
|
this.ws.close();
|
|
this.ws = null;
|
|
}
|
|
this.hasConnectedBefore = false;
|
|
this.handlers.clear();
|
|
this.anyHandlers.clear();
|
|
this.onReconnectCallbacks.clear();
|
|
}
|
|
|
|
on(event: WSEventType, handler: EventHandler) {
|
|
if (!this.handlers.has(event)) {
|
|
this.handlers.set(event, new Set());
|
|
}
|
|
this.handlers.get(event)!.add(handler);
|
|
return () => {
|
|
this.handlers.get(event)?.delete(handler);
|
|
};
|
|
}
|
|
|
|
onAny(handler: (msg: WSMessage) => void) {
|
|
this.anyHandlers.add(handler);
|
|
return () => {
|
|
this.anyHandlers.delete(handler);
|
|
};
|
|
}
|
|
|
|
onReconnect(callback: () => void) {
|
|
this.onReconnectCallbacks.add(callback);
|
|
return () => {
|
|
this.onReconnectCallbacks.delete(callback);
|
|
};
|
|
}
|
|
|
|
send(message: WSMessage) {
|
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify(message));
|
|
}
|
|
}
|
|
}
|