Files
Kai-Sa-Cam/apps/kai-sa-cam/src/server/index.ts
T
Esiah c6b08b4812
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 1m59s
feat: handle Cloudflare Access session expiry and serve go2rtc same-origin
- add apiFetch wrapper with re-auth popup, retry and session monitor
- proxy go2rtc through the app (/go2rtc) and drop the public stream hostname
- route WebSocket upgrades manually (the talk WSS was rejecting go2rtc MSE)
- harden talkback: paplay error handling, heartbeat, single speaker, reconnect
- sync recording state with the server on load and on 409
- optionally verify Cf-Access-Jwt-Assertion (CF_ACCESS_TEAM_DOMAIN/AUD)
- keep go2rtc on the internal network only
- remove unused env vars, update README and cam-watch script
2026-10-26 00:50:08 +01:00

206 lines
6.4 KiB
TypeScript

import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
import { createServer } from "http";
import type { IncomingHttpHeaders } from "http";
import { WebSocketServer, WebSocket } from "ws";
import { spawn, ChildProcessWithoutNullStreams } from "child_process";
import { join } from "path";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { recorderRouter } from "./recorder.js";
import { mediaRouter } from "./media.js";
import { talkRouter } from "./talk.js";
import { healthRouter } from "./health.js";
const __dirname = process.cwd();
const app = express();
const PORT = process.env.PORT || 8090;
const TEAM = process.env.CF_ACCESS_TEAM_DOMAIN;
const AUD = process.env.CF_ACCESS_AUD;
const jwks =
TEAM && AUD
? createRemoteJWKSet(new URL(`${TEAM}/cdn-cgi/access/certs`))
: null;
async function verifyAccess(headers: IncomingHttpHeaders): Promise<boolean> {
if (!jwks) return true;
const token = headers["cf-access-jwt-assertion"];
if (typeof token !== "string") return false;
try {
await jwtVerify(token, jwks, { issuer: TEAM, audience: AUD });
return true;
} catch {
return false;
}
}
app.use(async (req, res, next) => {
if (req.path === "/api/health") return next(); // sondes locales
if (await verifyAccess(req.headers)) return next();
res.status(401).json({ error: "unauthorized" });
});
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true }));
// Page chargée dans la popup de reconnexion (déjà derrière Access).
app.get("/auth/done", (_req, res) => {
res.setHeader("Cache-Control", "no-store");
res
.type("html")
.send(
`<!doctype html><meta charset="utf-8"><title>OK</title><body style="font-family:sans-serif;background:#111827;color:#fff;text-align:center;padding-top:30vh">Connecté ✔<script>try{window.opener&&window.opener.postMessage("kaisa-auth-ok",location.origin)}catch(e){}window.close()</script>`,
);
});
app.use(express.static(join(__dirname, "dist")));
// go2rtc : uniquement via ce proxy (même origine que l'app => même session Access).
// ws:false car l'upgrade est routé à la main plus bas (sinon le proxy
// intercepterait aussi /api/talk).
const go2rtcProxy = createProxyMiddleware({
target: process.env.GO2RTC_URL || "http://kai-sa-go2rtc:1984",
changeOrigin: true,
ws: false,
pathRewrite: { "^/go2rtc": "" },
});
app.use("/go2rtc", go2rtcProxy);
app.use("/api/recordings", recorderRouter);
app.use("/api/media", mediaRouter);
app.use("/api/talk", talkRouter);
app.use("/api", healthRouter);
app.get("*", (req, res, next) => {
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc"))
return next();
res.sendFile(join(__dirname, "dist/index.html"));
});
const server = createServer(app);
// ---------------------------------------------------------------------------
// WebSocket : routage manuel des upgrades.
// AVANT : new WebSocketServer({ server, path: "/api/talk" }) répondait 400 à tout
// upgrade d'un autre chemin, y compris /go2rtc/api/ws (flux MSE).
// ---------------------------------------------------------------------------
const wss = new WebSocketServer({ noServer: true, maxPayload: 1 << 20 });
server.on("upgrade", async (req, socket, head) => {
if (!(await verifyAccess(req.headers))) {
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
return socket.destroy();
}
const path = (req.url ?? "").split("?")[0];
if (path.startsWith("/go2rtc/")) {
return (go2rtcProxy as any).upgrade(req, socket, head);
}
if (path === "/api/talk") {
return wss.handleUpgrade(req, socket, head, (ws) =>
wss.emit("connection", ws, req),
);
}
socket.destroy();
});
// ---------------------------------------------------------------------------
// Talkback : micro navigateur -> paplay -> enceinte BT
// ---------------------------------------------------------------------------
type Talk = {
ws: WebSocket;
player: ChildProcessWithoutNullStreams | null;
cleanup: () => void;
};
let activeTalk: Talk | null = null;
wss.on("connection", (ws: WebSocket) => {
// Un seul "speaker" : une nouvelle connexion remplace l'ancienne (évite le blocage
// après un onglet mort / une coupure réseau).
const old = activeTalk;
if (old) {
old.cleanup(); // coupe paplay tout de suite
old.ws.close(4001, "replaced"); // le client n'essaie pas de se reconnecter
setTimeout(() => old.ws.terminate(), 1000);
}
const me: Talk = { ws, player: null, cleanup: () => {} };
activeTalk = me;
let alive = true;
ws.on("pong", () => (alive = true));
const heartbeat = setInterval(() => {
if (!alive) return ws.terminate();
alive = false;
ws.ping();
}, 15_000);
const cleanup = () => {
clearInterval(heartbeat);
const p = me.player;
me.player = null;
if (p) {
try {
p.stdin.destroy();
} catch {}
try {
p.kill("SIGKILL");
} catch {}
}
if (activeTalk === me) activeTalk = null;
};
me.cleanup = cleanup;
ws.on("message", (data: Buffer, isBinary: boolean) => {
if (!isBinary) {
if (me.player) return;
let rate = 48000;
try {
const r = Number(JSON.parse(data.toString()).rate);
if (r >= 8000 && r <= 96000) rate = r;
} catch {}
const p = spawn("paplay", [
"--raw",
`--rate=${rate}`,
"--format=s16le",
"--channels=1",
"--latency-msec=150",
]);
// Sans ces handlers, un EPIPE sur stdin ou un paplay introuvable
// = exception non gérée = crash du serveur Node.
p.on("error", (e) => {
console.error("paplay error:", e.message);
ws.close(1011, "paplay error");
});
p.on("exit", () => {
if (me.player === p) {
me.player = null;
ws.close(1011, "paplay exited");
}
});
p.stdin.on("error", () => {});
p.stdout.resume();
p.stderr.resume();
me.player = p;
return;
}
const p = me.player;
// Backpressure : on jette l'audio plutôt que d'accumuler de la latence.
if (p && p.stdin.writable && p.stdin.writableLength < 256 * 1024)
p.stdin.write(data);
});
ws.on("close", cleanup);
ws.on("error", cleanup);
});
process.on("uncaughtException", (e) => console.error("uncaughtException:", e));
process.on("unhandledRejection", (e) =>
console.error("unhandledRejection:", e),
);
server.listen(PORT, () =>
console.log(`kai-sa-cam server running on port ${PORT}`),
);