|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Hocuspocus (Yjs WebSocket) Server for ChatBox v2 |
| 5 | + * |
| 6 | + * Provides real-time shared state via Yjs documents served over WebSocket. |
| 7 | + * Each application room maps to a Yjs document. Presence is handled through |
| 8 | + * Hocuspocus awareness on the client side. |
| 9 | + * |
| 10 | + * Env vars: |
| 11 | + * PORT - HTTP/WebSocket port (default 3006) |
| 12 | + * HOST - Bind address (default 0.0.0.0) |
| 13 | + * HOCUSPOCUS_SECRET - Optional shared secret for token auth |
| 14 | + * |
| 15 | + * Usage: node hocuspocus-server.js |
| 16 | + */ |
| 17 | + |
| 18 | +import { Server } from "@hocuspocus/server"; |
| 19 | + |
| 20 | +const PORT = parseInt(process.env.PORT || "3006", 10); |
| 21 | +const HOST = process.env.HOST || "0.0.0.0"; |
| 22 | +const SECRET = process.env.HOCUSPOCUS_SECRET || ""; |
| 23 | + |
| 24 | +function writeJson(response, statusCode, payload) { |
| 25 | + response.writeHead(statusCode, { "Content-Type": "application/json" }); |
| 26 | + response.end(JSON.stringify(payload)); |
| 27 | +} |
| 28 | + |
| 29 | +const server = new Server({ |
| 30 | + name: "lowcoder-hocuspocus", |
| 31 | + quiet: true, |
| 32 | + address: HOST, |
| 33 | + port: PORT, |
| 34 | + |
| 35 | + async onListen() { |
| 36 | + console.log(`[hocuspocus] listening on ws://${HOST}:${PORT}`); |
| 37 | + }, |
| 38 | + |
| 39 | + async onRequest({ request, response }) { |
| 40 | + if (request.url === "/health") { |
| 41 | + writeJson(response, 200, { |
| 42 | + status: "ok", |
| 43 | + host: HOST, |
| 44 | + port: PORT, |
| 45 | + auth: SECRET ? "enabled" : "disabled", |
| 46 | + }); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + if (request.url === "/") { |
| 51 | + writeJson(response, 200, { |
| 52 | + name: "lowcoder-hocuspocus", |
| 53 | + websocket: `ws://${HOST}:${PORT}`, |
| 54 | + health: "/health", |
| 55 | + }); |
| 56 | + } |
| 57 | + }, |
| 58 | + |
| 59 | + async onAuthenticate({ token, documentName }) { |
| 60 | + if (!SECRET) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + if (token !== SECRET) { |
| 65 | + console.warn(`[hocuspocus] rejected connection for ${documentName}: invalid token`); |
| 66 | + throw new Error("Unauthorized"); |
| 67 | + } |
| 68 | + }, |
| 69 | + |
| 70 | + async onConnect({ documentName, socketId }) { |
| 71 | + console.log(`[hocuspocus] connect socket=${socketId} document=${documentName}`); |
| 72 | + }, |
| 73 | + |
| 74 | + async onDisconnect({ documentName, socketId }) { |
| 75 | + console.log(`[hocuspocus] disconnect socket=${socketId} document=${documentName}`); |
| 76 | + }, |
| 77 | +}); |
| 78 | + |
| 79 | +try { |
| 80 | + await server.listen(); |
| 81 | +} catch (error) { |
| 82 | + console.error("[hocuspocus] failed to start", error); |
| 83 | + process.exit(1); |
| 84 | +} |
0 commit comments