mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-23 18:17:44 +02:00
* feat: identify clients via X-Client-Platform/Version/OS
Adds client identification headers (and matching WS query params) across
all first-party clients so the server can split logs/metrics/gating by
caller without parsing User-Agent.
- HTTP: X-Client-Platform, X-Client-Version, X-Client-OS
- WS: client_platform, client_version, client_os query params
- Platform ∈ {web, desktop, cli, daemon}; OS ∈ {macos, windows, linux}
Wired through the shared TS ApiClient/WSClient via a new identity option
on CoreProvider. Web reads its version from package.json/env; Desktop
captures version + OS synchronously in preload via sendSync IPC. Go CLI
and daemon clients populate the same headers using runtime.GOOS
(normalized darwin → macos).
Server-side adds a ClientMetadata middleware that stashes the headers in
request context; the request logger and logger.RequestAttrs surface them
on every access log and handler-level log. Realtime hub logs the same
fields on websocket connect.
CORS allowlist extended for the new headers.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* test: address client-identity PR nits
- Memoize the CoreProvider identity object on Web and Desktop, and key
WSProvider's effect on identity primitives instead of the object
reference, so unrelated parent re-renders no longer tear down and
reconnect the WebSocket.
- Add direct header-injection tests for the CLI and daemon Go HTTP
clients (X-Client-Platform/Version/OS) and a normalizeGOOS unit test
on both packages.
- Add a TS test for WSClient that asserts client_platform/client_version/
client_os land on the upgrade URL and never leak the auth token.
- Add a hub test that dials the WS endpoint with client_* query params
and asserts the "websocket connected" log entry surfaces them as
structured attributes.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
168 lines
4.9 KiB
TypeScript
168 lines
4.9 KiB
TypeScript
import type { WSMessage, WSEventType } from "../types/events";
|
|
import { type Logger, noopLogger } from "../logger";
|
|
|
|
type EventHandler = (payload: unknown, actorId?: string) => void;
|
|
|
|
/** Identifies the WS client to the server. Sent as `client_platform`,
|
|
* `client_version`, and `client_os` query parameters on the upgrade URL —
|
|
* browsers cannot set custom headers on WebSocket handshakes, so query
|
|
* params are the only portable channel. */
|
|
export interface WSClientIdentity {
|
|
platform?: string;
|
|
version?: string;
|
|
os?: string;
|
|
}
|
|
|
|
export class WSClient {
|
|
private ws: WebSocket | null = null;
|
|
private baseUrl: string;
|
|
private token: string | null = null;
|
|
private workspaceSlug: string | null = null;
|
|
private cookieAuth = false;
|
|
private identity: WSClientIdentity | undefined;
|
|
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;
|
|
identity?: WSClientIdentity;
|
|
},
|
|
) {
|
|
this.baseUrl = url;
|
|
this.logger = options?.logger ?? noopLogger;
|
|
this.cookieAuth = options?.cookieAuth ?? false;
|
|
this.identity = options?.identity;
|
|
}
|
|
|
|
setAuth(token: string | null, workspaceSlug: string) {
|
|
this.token = token;
|
|
this.workspaceSlug = workspaceSlug;
|
|
}
|
|
|
|
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.workspaceSlug)
|
|
url.searchParams.set("workspace_slug", this.workspaceSlug);
|
|
if (this.identity?.platform)
|
|
url.searchParams.set("client_platform", this.identity.platform);
|
|
if (this.identity?.version)
|
|
url.searchParams.set("client_version", this.identity.version);
|
|
if (this.identity?.os)
|
|
url.searchParams.set("client_os", this.identity.os);
|
|
|
|
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));
|
|
}
|
|
}
|
|
}
|