moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
import type { WebSocket } from 'ws';
import type { WsServerEvent } from '@waggle/shared';
export class ConnectionManager {
private connections = new Map<string, Map<string, WebSocket>>(); // teamId -> userId -> ws
add(teamId: string, userId: string, ws: WebSocket): void {
if (!this.connections.has(teamId)) {
this.connections.set(teamId, new Map());
}
this.connections.get(teamId)!.set(userId, ws);
}
remove(teamId: string, userId: string): void {
this.connections.get(teamId)?.delete(userId);
if (this.connections.get(teamId)?.size === 0) {
this.connections.delete(teamId);
}
}
broadcast(teamId: string, event: WsServerEvent, excludeUserId?: string): void {
const team = this.connections.get(teamId);
if (!team) return;
const data = JSON.stringify(event);
for (const [userId, ws] of team) {
if (userId !== excludeUserId && ws.readyState === ws.OPEN) {
ws.send(data);
}
}
}
sendTo(teamId: string, userId: string, event: WsServerEvent): void {
const ws = this.connections.get(teamId)?.get(userId);
if (ws && ws.readyState === ws.OPEN) {
ws.send(JSON.stringify(event));
}
}
getConnectedUsers(teamId: string): string[] {
return Array.from(this.connections.get(teamId)?.keys() ?? []);
}
getTeamCount(): number {
return this.connections.size;
}
}

View File

@@ -0,0 +1,251 @@
import type { FastifyInstance } from 'fastify';
import type { WsClientEvent, WsServerEvent } from '@waggle/shared';
import { createClerkClient, verifyToken } from '@clerk/fastify';
import { ConnectionManager } from './connection-manager.js';
import { teams, messages, users } from '../db/schema.js';
import { eq } from 'drizzle-orm';
export const connectionManager = new ConnectionManager();
/**
* Validate that a string looks like a JWT (3 dot-separated base64url segments).
* This is a structural check, not a cryptographic verification.
*/
function isJwtStructure(token: string): boolean {
const parts = token.split('.');
if (parts.length !== 3) return false;
// Each segment should be non-empty and valid base64url
const base64urlRegex = /^[A-Za-z0-9_-]+$/;
return parts.every((part) => part.length > 0 && base64urlRegex.test(part));
}
// Overridable verifier for testing — allows tests to swap in a mock
export type WsTokenVerifier = (token: string) => Promise<{ sub: string }>;
let _wsTokenVerifier: WsTokenVerifier | null = null;
/** Override the WS token verifier (for testing only) */
export function setWsTokenVerifier(verifier: WsTokenVerifier | null): void {
_wsTokenVerifier = verifier;
}
export async function wsGateway(fastify: FastifyInstance) {
// Create Clerk client for JWT verification if secret key is available
const clerkSecretKey = fastify.config.clerkSecretKey;
const clerk = clerkSecretKey
? createClerkClient({ secretKey: clerkSecretKey })
: null;
// Hard fail in production if no JWT verification path is configured. Without
// either a Clerk client or a test override, the gateway would have no way to
// cryptographically verify incoming tokens — the previous fallback (unsigned
// JWT decode) is forgeable. NODE_ENV !== 'production' (dev / desktop /
// testing) is allowed to start without the key, but connections without a
// verifier are rejected at request time below.
if (!clerk && !_wsTokenVerifier && process.env.NODE_ENV === 'production') {
throw new Error(
'[ws-gateway] CLERK_SECRET_KEY required in production. WebSocket gateway ' +
'refuses to start without cryptographic JWT verification configured. ' +
'Set CLERK_SECRET_KEY in environment or settings.json.',
);
}
if (!clerk && !_wsTokenVerifier) {
fastify.log.warn(
'[ws-gateway] CLERK_SECRET_KEY absent; WebSocket connections will be rejected. ' +
'This is dev/desktop mode — set CLERK_SECRET_KEY for cloud/SaaS deployments.',
);
}
fastify.get('/ws', { websocket: true }, (socket, request) => {
let userId: string | null = null;
let teamId: string | null = null;
socket.on('message', async (raw: Buffer | string) => {
try {
const event = JSON.parse(raw.toString()) as WsClientEvent;
switch (event.type) {
case 'authenticate': {
const token = event.token;
// Reject tokens that are not JWTs (plain userIds, random strings)
if (!isJwtStructure(token)) {
socket.send(
JSON.stringify({
type: 'error',
message: 'Invalid token: must be a valid JWT',
}),
);
return;
}
try {
let sub: string;
if (_wsTokenVerifier) {
// Test override path
const result = await _wsTokenVerifier(token);
sub = result.sub;
} else if (clerk) {
// Production path: full Clerk JWT verification. `clerk` is only
// non-null when clerkSecretKey is set, so the secretKey below is
// always present here.
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
sub = payload.sub;
} else {
// No verifier available — reject. The startup check above ensures
// production cannot reach this branch. Dev/desktop without a key
// hits this and is rejected at connection time (no silent decode).
socket.send(
JSON.stringify({
type: 'error',
message: 'Authentication unavailable: server has no JWT verifier configured',
}),
);
socket.close();
return;
}
// Look up internal user by Clerk ID
const [user] = await fastify.db
.select()
.from(users)
.where(eq(users.clerkId, sub));
if (!user) {
socket.send(
JSON.stringify({
type: 'error',
message: 'User not found',
}),
);
return;
}
userId = user.id;
socket.send(JSON.stringify({ type: 'authenticated', userId }));
} catch {
socket.send(
JSON.stringify({
type: 'error',
message: 'Token verification failed',
}),
);
}
break;
}
case 'join_team': {
if (!userId) {
socket.send(JSON.stringify({ type: 'error', message: 'Not authenticated' }));
return;
}
const [team] = await fastify.db
.select()
.from(teams)
.where(eq(teams.slug, event.teamSlug));
if (!team) {
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
return;
}
// Leave previous team if any
if (teamId && userId) {
connectionManager.remove(teamId, userId);
}
teamId = team.id;
connectionManager.add(teamId, userId, socket);
// Subscribe to Redis channel for this team
const channel = `team:${teamId}:waggle`;
try {
const existingChannels = await fastify.redisSub.call('PUBSUB', 'CHANNELS', channel) as string[];
// Only subscribe if not already subscribed (redisSub is shared)
if (!existingChannels || !existingChannels.includes(channel)) {
await fastify.redisSub.subscribe(channel);
}
} catch {
// Redis subscribe failure is non-fatal — real-time updates won't work
// but join should still succeed
}
socket.send(JSON.stringify({ type: 'joined_team', teamSlug: event.teamSlug }));
break;
}
case 'send_message': {
if (!userId || !teamId) {
socket.send(JSON.stringify({ type: 'error', message: 'Not in a team' }));
return;
}
// Persist message
const [msg] = await fastify.db
.insert(messages)
.values({
teamId,
senderId: userId,
type: event.messageType,
subtype: event.subtype,
content: event.content,
})
.returning();
// Publish to Redis for cross-process delivery
await fastify.redis.publish(
`team:${teamId}:waggle`,
JSON.stringify(msg),
);
break;
}
}
} catch {
socket.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
}
});
socket.on('close', () => {
if (teamId && userId) {
connectionManager.remove(teamId, userId);
}
});
});
// Forward Redis pub/sub messages to WebSocket clients
fastify.redisSub.on('message', (channel: string, data: string) => {
const match = channel.match(/^team:(.+):waggle$/);
if (!match) return;
const tId = match[1];
try {
const event: WsServerEvent = { type: 'waggle_message', message: JSON.parse(data) };
connectionManager.broadcast(tId, event);
} catch {
// Ignore malformed messages from Redis
}
});
// Subscribe to job progress channels via pattern matching
await fastify.redisSub.psubscribe('job:*:progress');
// Forward job progress events to WebSocket clients
fastify.redisSub.on('pmessage', (_pattern: string, channel: string, data: string) => {
const jobMatch = channel.match(/^job:(.+):progress$/);
if (!jobMatch) return;
try {
const parsed = JSON.parse(data);
const event: WsServerEvent = {
type: 'job_progress',
jobId: jobMatch[1],
progress: parsed,
};
// Route to the team that owns this job
if (parsed.teamId) {
connectionManager.broadcast(parsed.teamId, event);
}
} catch {
// Ignore malformed messages from Redis
}
});
}