v3.0稳定的worker.js (perfect sfu edition v3)

/* ===================================================================== * 会议后台 — Cloudflare Worker + Durable Objects * --------------------------------------------------------------------- * 三件事: * 1) /rtc —— WebSocket 信令(谁在房间、会话ID、举手、聊天、演示控制) * 2) /sfu/* —— 反向代理到 Cloudflare Realtime SFU,注入 App Token * (Token 只在这里,前端 F12 看不到) * 3) /slide —— 演示图片的小型中转(存在房间的 Durable Object 内存里) * 媒体(音视频/屏幕)走 SFU,不经过这里的转发逻辑。 * ===================================================================== */ var ALLOWED_ORIGINS = [ "https://www.web3businesssolution.com", "https://web3businesssolution.com" ]; /* 限流改成两个互不干扰的令牌桶,这样心跳永远挤不掉聊天: * - 心跳 state(每 3 秒一次):桶 10 个,每秒回 1 个 —— 绰绰有余 * - 用户消息(聊天/表情/举手/控制):桶 80 个,每秒回 25 个 * 人手动狂刷打不满;脚本滥用被压到 25/秒,免费额度仍受保护 */ var HB_CAPACITY = 10, HB_REFILL = 1; var MSG_CAPACITY = 80, MSG_REFILL = 25; var MAX_PEERS_PER_ROOM = 60; var MAX_MSG_BYTES = 256 * 1024; var MAX_SLIDE_BYTES = 8 * 1024 * 1024; var SFU_BASE = "https://rtc.live.cloudflare.com/v1/apps/"; function originAllowed(origin) { if (!origin) return false; return ALLOWED_ORIGINS.includes(origin); } function cleanRoom(raw) { return String(raw || "").toLowerCase().replace(/[^a-z0-9_]/g, "").slice(0, 40); } function corsHeaders(origin) { return { "Access-Control-Allow-Origin": origin, "Access-Control-Allow-Methods": "GET,POST,PUT,OPTIONS", "Access-Control-Allow-Headers": "content-type", "Access-Control-Max-Age": "86400" }; } var worker_default = { async fetch(request, env) { const url = new URL(request.url); const origin = request.headers.get("Origin"); const path = url.pathname; // 健康检查 if (path === "/" || path === "") { return new Response("ok", { status: 200, headers: { "content-type": "text/plain" } }); } // CORS 预检(/sfu 和 /slide 是跨域 fetch,需要) if (request.method === "OPTIONS" && (path === "/sfu" || path.startsWith("/sfu/") || path === "/slide")) { if (!originAllowed(origin)) return new Response("forbidden", { status: 403 }); return new Response(null, { status: 204, headers: corsHeaders(origin) }); } // ---- SFU 代理:把前端的 /sfu/... 转发到 Cloudflare Realtime,带上 Token ---- if (path === "/sfu" || path.startsWith("/sfu/")) { if (!originAllowed(origin)) return new Response("forbidden", { status: 403 }); if (!env.SFU_APP_ID || !env.SFU_APP_TOKEN) { return new Response("sfu not configured", { status: 500, headers: corsHeaders(origin) }); } const suffix = path.slice(4); // 去掉前缀 "/sfu" const target = SFU_BASE + env.SFU_APP_ID + suffix + url.search; const init = { method: request.method, headers: { "Authorization": "Bearer " + env.SFU_APP_TOKEN, "Content-Type": "application/json" } }; if (request.method !== "GET" && request.method !== "HEAD") { init.body = await request.text(); } let up; try { up = await fetch(target, init); } catch (_) { return new Response("sfu upstream error", { status: 502, headers: corsHeaders(origin) }); } const body = await up.text(); const h = corsHeaders(origin); h["content-type"] = up.headers.get("content-type") || "application/json"; return new Response(body, { status: up.status, headers: h }); } // ---- 演示图片中转:存到房间的 Durable Object ---- if (path === "/slide") { if (!originAllowed(origin)) return new Response("forbidden", { status: 403 }); const room = cleanRoom(url.searchParams.get("r")); if (!room) return new Response("bad room", { status: 400, headers: corsHeaders(origin) }); const id = env.ROOM.idFromName(room); return env.ROOM.get(id).fetch(request); } // ---- 信令 WebSocket ---- if (path !== "/rtc") return new Response("not found", { status: 404 }); if (!originAllowed(origin)) return new Response("forbidden", { status: 403 }); if (request.headers.get("Upgrade") !== "websocket") { return new Response("expected websocket", { status: 426 }); } const room = cleanRoom(url.searchParams.get("r")); if (!room) return new Response("bad room", { status: 400 }); const id = env.ROOM.idFromName(room); return env.ROOM.get(id).fetch(request); } }; /* ======================= 房间(Durable Object)======================= */ var Room = class { constructor(state, env) { this.state = state; this.env = env; this.peers = new Map(); this.slide = null; // { id, w, h, buf } } async fetch(request) { const url = new URL(request.url); // 演示图片存取 if (url.pathname === "/slide") { const origin = request.headers.get("Origin") || ""; const h = { "Access-Control-Allow-Origin": origin }; if (request.method === "POST") { const buf = await request.arrayBuffer(); if (buf.byteLength > MAX_SLIDE_BYTES) return new Response("too large", { status: 413, headers: h }); this.slide = { id: (url.searchParams.get("id") || "").slice(0, 40), w: url.searchParams.get("w") || "0", h: url.searchParams.get("h") || "0", buf }; return new Response("ok", { status: 200, headers: h }); } const want = (url.searchParams.get("id") || "").slice(0, 40); if (!this.slide || (want && this.slide.id !== want)) { return new Response("not found", { status: 404, headers: h }); } const rh = Object.assign({ "content-type": "image/jpeg", "cache-control": "no-store" }, h); return new Response(this.slide.buf, { status: 200, headers: rh }); } // WebSocket 信令 const pair = new WebSocketPair(); const client = pair[0]; const server = pair[1]; this.accept(server); return new Response(null, { status: 101, webSocket: client }); } accept(ws) { ws.accept(); let clientId = null; const bucket = { hb: HB_CAPACITY, msg: MSG_CAPACITY, at: Date.now() }; const take = (isHeartbeat) => { const now = Date.now(); const dt = Math.max(0, now - bucket.at) / 1000; bucket.at = now; bucket.hb = Math.min(HB_CAPACITY, bucket.hb + dt * HB_REFILL); bucket.msg = Math.min(MSG_CAPACITY, bucket.msg + dt * MSG_REFILL); if (isHeartbeat) { if (bucket.hb < 1) return false; bucket.hb -= 1; return true; } if (bucket.msg < 1) return false; bucket.msg -= 1; return true; }; ws.addEventListener("message", (evt) => { let raw = evt.data; if (typeof raw !== "string") return; if (raw.length > MAX_MSG_BYTES) return; let msg; try { msg = JSON.parse(raw); } catch (_) { return; } if (!msg || typeof msg !== "object" || typeof msg.t !== "string") return; if (typeof msg.from !== "string" || !/^[a-z0-9]{4,40}$/.test(msg.from)) return; // 心跳和用户消息分开计费,聊天不会被心跳挤掉 if (!take(msg.t === "state")) return; if (!clientId) { clientId = msg.from; if (this.peers.size >= MAX_PEERS_PER_ROOM && !this.peers.has(clientId)) { try { ws.close(1013, "room full"); } catch (_) {} return; } this.peers.set(clientId, ws); } else if (msg.from !== clientId) { return; } const to = typeof msg.to === "string" ? msg.to : null; if (to) { const dst = this.peers.get(to); if (dst && dst.readyState === 1) { try { dst.send(raw); } catch (_) {} } } else { for (const [pid, pws] of this.peers) { if (pid === clientId) continue; if (pws.readyState === 1) { try { pws.send(raw); } catch (_) {} } } } }); const cleanup = () => { if (clientId && this.peers.get(clientId) === ws) { this.peers.delete(clientId); const byeMsg = JSON.stringify({ t: "bye", from: clientId }); for (const [, pws] of this.peers) { if (pws.readyState === 1) { try { pws.send(byeMsg); } catch (_) {} } } } }; ws.addEventListener("close", cleanup); ws.addEventListener("error", cleanup); } }; export { Room, worker_default as default };