feat: handle Cloudflare Access session expiry and serve go2rtc same-origin
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 1m59s

- 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
This commit is contained in:
2026-10-26 00:50:08 +01:00
parent 907ad8a0b9
commit c6b08b4812
24 changed files with 672 additions and 988 deletions
+3 -5
View File
@@ -5,15 +5,13 @@ GROUP_ID=1001
# --- APP ---
APP_ORIGIN=https://kaisa.esiah.dev
MEDIA_DIR=./media
CONFIG_DIR=./config
LOG_LEVEL=info
MAX_RECORDING_MINUTES=120
DISK_MIN_FREE_GB=2
# --- GO2RTC ---
GO2RTC_USERNAME=kai-sa-cam
GO2RTC_PASSWORD=
# --- CLOUDFLARE ACCESS (validation du JWT côté serveur, optionnel) ---
CF_ACCESS_TEAM_DOMAIN=https://esiah-dev.cloudflareaccess.com
CF_ACCESS_AUD=
# --- AUDIO / BLUETOOTH (host side) ---
PULSE_SERVER=unix:/run/user/1001/pulse/native
+83 -62
View File
@@ -5,52 +5,66 @@ Application de surveillance vidéo avec enregistrement manuel, écoute bidirecti
## Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ Cloudflare Tunnel (kai-sa-cam-tunnel) │
│ └── kaisa.esiah.dev → kai-sa-cam:8090 │
└─────────────────────────────────────────────────────────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌─────────────────┐ ┌──────────────┐
│ kai-sa-cam │ │kai-sa-go2rtc │
│ (API + UI + │ │ (RTSP flux) │
│ recorder + │ │ │
│ BT bridge) │ │ │
└─────────────────┘ └──────────────┘
│ │
└─────────┬─────────┘
│
┌─────────┴─────────┐
▼ ▼
kai-sa-cam-internal /dev/video0 + /dev/snd
│
▼
┌──────────────────┐
│ PulseAudio/PipeWire │
│ (enceinte BT) │
└──────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ Cloudflare Access (login, session, JWT) │
│ │ │
│ Cloudflare Tunnel (kai-sa-cam-tunnel) │
│ └── kaisa.esiah.dev → kai-sa-cam:8090 (seule route) │
└──────────────────────────────┬───────────────────────────────┘
▼
┌─────────────────────┐
│ kai-sa-cam │
│ UI + API + recorder│
│ + talkback (WS) │
│ proxy /go2rtc/* │
└──────────┬──────────┘
│ kai-sa-cam-internal (réseau interne)
┌──────────▼──────────┐
│ kai-sa-go2rtc │ ← aucun accès externe
│ (flux webcam) │
└──────────┬──────────┘
▼
/dev/video0 + /dev/snd
kai-sa-cam ──► PulseAudio (socket hôte) ──► enceinte BT
```
go2rtc n'est joignable que depuis `kai-sa-cam` : le flux ne peut pas être consulté sans passer par Cloudflare Access.
## Composants
- **kai-sa-cam** : API Node + UI React/Tailwind + recorder + BT bridge (WebSocket → PulseAudio)
- **kai-sa-go2rtc** : Flux RTSP webcam (vidéo + son caméra), durci (non-privileged, devices restreints)
- **kai-sa-cam** : API Node + UI React/Tailwind + recorder + talkback (WebSocket → paplay → PulseAudio) + proxy `/go2rtc` vers go2rtc
- **kai-sa-go2rtc** : flux webcam, durci (non-privileged, devices restreints), sur le réseau interne uniquement
## Fonctionnalités
- **Live view** : Flux vidéo MSE via go2rtc, son caméra
- **Push-to-record manuel** : Enregistrement vidéo + son caméra (jamais micro navigateur)
- **Snapshots manuels** : Capture instantanée JPEG
- **Talkback** : Micro navigateur → enceinte Bluetooth (WebSocket → paplay → PulseAudio)
- **Stockage plat** : Tout dans `/media` sans arborescence
- **Export ZIP** : Téléchargement de tous les médias + suppression auto après succès
- **Auth** : Cloudflare Access uniquement (pas de JWT interne)
- **Live view** : flux MSE via go2rtc, servi en même origine (`/go2rtc/stream.html`)
- **Push-to-record manuel** : enregistrement vidéo (jamais le micro du navigateur)
- **Snapshots manuels** : capture instantanée JPEG
- **Talkback** : micro navigateur → enceinte Bluetooth, reconnexion automatique
- **Stockage plat** : tout dans `./media` sans arborescence
- **Export ZIP** : téléchargement de tous les médias + suppression auto après succès
- **Auth** : Cloudflare Access uniquement, avec validation optionnelle du JWT côté serveur
- **Session expirée** : détectée côté client, popup de reconnexion, requête rejouée sans recharger la page
## Réseaux
- `kai-sa-cam-internal` (internal) : Communication kai-sa-cam ↔ kai-sa-go2rtc
- `kai-sa-cam-tunnel` (external) : Exposition via Cloudflare Tunnel
- `kai-sa-cam-internal` (internal) : kai-sa-cam ↔ kai-sa-go2rtc
- `kai-sa-cam-tunnel` (external) : exposition de `kai-sa-cam` uniquement via Cloudflare Tunnel
## Cloudflare Access
Application Access sur `kaisa.esiah.dev` (aucun chemin en Bypass) :
- **Session duration** : 24 h ou plus (réglage qui détermine la fréquence des reconnexions)
- **HTTP Only** activé, **Same Site** = Lax, CORS laissé vide (tout est en même origine)
- Aucune route de tunnel ni application Access pour go2rtc
### Validation du JWT côté serveur (optionnel)
Si `CF_ACCESS_TEAM_DOMAIN` et `CF_ACCESS_AUD` sont renseignées, le serveur refuse (401) toute requête HTTP ou WebSocket sans en-tête `Cf-Access-Jwt-Assertion` valide. `/api/health` reste accessible pour les sondes locales. Vides, la vérification est désactivée.
L'AUD tag se trouve dans Zero Trust → Access → Applications → `kaisa.esiah.dev`.
## Installation locale (dev)
@@ -62,33 +76,38 @@ cp .env.example .env # adapter si besoin
make up-dev # démarre kai-sa-cam + kai-sa-go2rtc
```
Accès : `http://localhost:8090` (via proxy Vite) ou via tunnel si configuré.
Accès : `http://localhost:8090`, ou via le proxy Vite qui doit relayer `/api` (WebSocket compris), `/go2rtc` (WebSocket compris) et `/auth` vers `:8090`.
## Installation production (serveur)
```bash
# Sur le serveur
cd /srv/apps/kai-sa-cam
cp .env.example .env # une seule fois, puis renseigner CF_ACCESS_AUD
mkdir -p media config
sudo chown 1001:1001 media # le conteneur tourne en 1001:1001
make up-prod
```
Le runner GitHub Actions `kai-sa-cam` déploie automatiquement sur push `main`.
Le runner GitHub Actions `kai-sa-cam` déploie automatiquement sur push `main`. Le fichier `.env` n'est pas versionné : il reste sur le serveur d'un déploiement à l'autre.
## Variables d'environnement
| Variable | Défaut | Description |
|----------|--------|-------------|
| `TZ` | Europe/Paris | Fuseau horaire |
| `USER_ID` / `GROUP_ID` | 1001 | UID/GID pour volumes |
| `APP_ORIGIN` | https://kaisa.esiah.dev | Origine CORS |
| `MEDIA_DIR` | ./media | Stockage médias |
| `CONFIG_DIR` | ./config | Config go2rtc |
| `LOG_LEVEL` | info | Niveau de log |
| `MAX_RECORDING_MINUTES` | 120 | Durée max enregistrement |
| `DISK_MIN_FREE_GB` | 2 | Espace disque minimum |
| `GO2RTC_USERNAME` | kai-sa-cam | Auth go2rtc |
| `GO2RTC_PASSWORD` | - | Auth go2rtc |
| `BT_MAC` | 69:B2:C0:04:A4:80 | Adresse enceinte BT |
Lues par `docker-compose.yml` depuis `.env` :
| Variable | Défaut | Description |
| ----------------------- | -------------------------------- | ---------------------------------------------------------------------- |
| `TZ` | Europe/Paris | Fuseau horaire |
| `USER_ID` / `GROUP_ID` | 1001 | UID/GID de l'utilisateur hôte |
| `APP_ORIGIN` | https://kaisa.esiah.dev | Origine de l'application |
| `LOG_LEVEL` | info | Niveau de log |
| `MAX_RECORDING_MINUTES` | 120 | Durée max d'un enregistrement |
| `DISK_MIN_FREE_GB` | 2 | Espace disque minimum |
| `CF_ACCESS_TEAM_DOMAIN` | - | Domaine d'équipe Access (ex. `https://esiah-dev.cloudflareaccess.com`) |
| `CF_ACCESS_AUD` | - | AUD tag de l'application Access |
| `PULSE_SERVER` | unix:/run/user/1001/pulse/native | Socket PulseAudio de l'hôte |
| `BT_MAC` | 69:B2:C0:04:A4:80 | Adresse de l'enceinte BT (service hôte) |
Fixées dans le compose (pas dans `.env`) : `MEDIA_DIR=/media`, `CONFIG_DIR=/config`, `GO2RTC_URL`, `GO2RTC_RTSP_URL`.
## Commandes Make
@@ -106,14 +125,15 @@ make restart # Redémarre services
## Sécurité
- **go2rtc** : non-privileged, `devices: [/dev/video0, /dev/snd]`, `cap_drop: ALL`, `no-new-privileges`, `read_only`
- **go2rtc** : non-privileged, `devices: [/dev/video0, /dev/snd]`, `cap_drop: ALL`, `no-new-privileges`, `read_only`, réseau interne uniquement
- **kai-sa-cam** : non-root (UID 1001), `cap_drop: ALL`, `no-new-privileges`, `read_only`, pas de D-Bus
- **Bluetooth** : géré via service hôte `kai-sa-cam-bt.service` (pas de D-Bus dans conteneurs)
- **Auth** : Cloudflare Access uniquement
- **Auth** : Cloudflare Access + validation optionnelle du JWT dans l'application
## Stockage
- Tout dans `/media` (plat, pas de sous-dossiers)
- `./media` (hôte) monté sur `/media` : bind mount, pas un volume Docker. Sur le serveur : `/srv/apps/kai-sa-cam/media`
- Tout est à plat (pas de sous-dossiers)
- Enregistrements : `.mp4` (push-to-record manuel, max 120 min)
- Snapshots : `.jpg` (manuels)
- Export ZIP : supprime les fichiers **uniquement si le ZIP se termine sans erreur**
@@ -121,12 +141,13 @@ make restart # Redémarre services
## Dépannage
| Symptôme | Action |
|----------|--------|
| Pas de vidéo | `make status`, vérifier `/dev/video0` |
| Pas de son caméra | Cliquer sur la vidéo, vérifier gain |
| Micro → enceinte ne marche pas | `make logs-cam`, vérifier Pulse/BT |
| Enregistrement ne démarre pas | Espace disque, `make logs-cam` |
| Symptôme | Action |
| ------------------------------ | ------------------------------------------------------------------------------------------------ |
| Pas de vidéo | `make status`, vérifier `/dev/video0`, `make logs-go2rtc` |
| Bandeau « Session expirée » | Cliquer « Se reconnecter » (popup Access) ; allonger la session dans Cloudflare |
| Tout répond 401 | `CF_ACCESS_AUD` / `CF_ACCESS_TEAM_DOMAIN` incorrects : les vider pour désactiver la vérification |
| Micro → enceinte ne marche pas | `make logs-cam`, vérifier Pulse/BT |
| Enregistrement ne démarre pas | Espace disque, droits sur `./media` (1001:1001), `make logs-cam` |
## Déploiement
@@ -135,4 +156,4 @@ Le workflow GitHub Actions `.github/workflows/deploy.yml` tourne sur runner `sel
1. `git pull` sur `/srv/apps/kai-sa-cam`
2. `docker compose --profile prod build`
3. `docker compose --profile prod up -d`
4. `docker image prune -f`
4. `docker image prune -f`
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

-16
View File
@@ -1,16 +0,0 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="icon" type="image/png" href="/logo.png" />
<title>Kai-Sa-Cam</title>
<meta name="theme-color" content="#1a1a2e" />
<script type="module" crossorigin src="/assets/index-CG2sCz3I.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-1rRaNqus.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 331 KiB

-482
View File
@@ -1,482 +0,0 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/server/index.ts
var import_express5 = __toESM(require("express"), 1);
var import_http_proxy_middleware = require("http-proxy-middleware");
var import_http = require("http");
var import_ws = require("ws");
var import_child_process2 = require("child_process");
var import_path3 = require("path");
// src/server/recorder.ts
var import_express = require("express");
var import_child_process = require("child_process");
var import_fs = require("fs");
var import_path = require("path");
var router = (0, import_express.Router)();
var MEDIA_DIR = process.env.MEDIA_DIR || "/media";
var CONFIG_DIR = process.env.CONFIG_DIR || "/config";
var GO2RTC_RTSP_URL = process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
var MAX_RECORDING_MINUTES = parseInt(process.env.MAX_RECORDING_MINUTES || "120", 10);
var DISK_MIN_FREE_GB = parseInt(process.env.DISK_MIN_FREE_GB || "2", 10);
var recordingProcess = null;
var recordingStartTime = null;
var currentRecordingFile = null;
if (!(0, import_fs.existsSync)(MEDIA_DIR)) {
(0, import_fs.mkdirSync)(MEDIA_DIR, { recursive: true });
}
function checkDiskSpace() {
try {
const stats = (0, import_fs.statSync)(MEDIA_DIR);
return true;
} catch {
return false;
}
}
function generateFilename(ext) {
const now = /* @__PURE__ */ new Date();
const timestamp = now.toISOString().replace(/[:.]/g, "-").split("T").join("_");
return `recording_${timestamp}.${ext}`;
}
function finalizeRecording(partPath) {
if (!partPath) return;
if (!(0, import_fs.existsSync)(partPath)) {
console.log("No part file to finalize");
return;
}
try {
const stats = (0, import_fs.statSync)(partPath);
if (stats.size < 1024) {
console.error(`Recording file too small (${stats.size} bytes), removing: ${partPath}`);
try {
(0, import_fs.unlinkSync)(partPath);
} catch {
}
return;
}
const finalPath = partPath.replace(/\.part$/, ".mp4");
(0, import_fs.renameSync)(partPath, finalPath);
console.log(`Recording saved: ${finalPath} (${stats.size} bytes)`);
} catch (e) {
console.error("Failed to finalize recording:", e);
}
}
router.post("/start", async (req, res) => {
if (recordingProcess) {
return res.status(409).json({ error: "Enregistrement d\xE9j\xE0 en cours" });
}
if (!checkDiskSpace()) {
return res.status(507).json({ error: "Espace disque insuffisant" });
}
const filename = generateFilename("part");
const filepath = (0, import_path.join)(MEDIA_DIR, filename);
currentRecordingFile = filepath;
recordingStartTime = Date.now();
const args = [
"-hide_banner",
"-loglevel",
"warning",
"-rtsp_transport",
"tcp",
"-fflags",
"+genpts",
"-use_wallclock_as_timestamps",
"1",
"-avoid_negative_ts",
"make_zero",
"-i",
GO2RTC_RTSP_URL,
"-c:v",
"libx264",
"-preset",
"ultrafast",
"-tune",
"zerolatency",
"-profile:v",
"baseline",
"-pix_fmt",
"yuv420p",
"-g",
"30",
"-an",
// no audio
"-f",
"mp4",
"-movflags",
"+frag_keyframe+empty_moov+default_base_moof",
"-t",
`${MAX_RECORDING_MINUTES * 60}`,
filepath
];
const ffmpegPath = process.env.FFMPEG_PATH || "ffmpeg";
console.log("Starting ffmpeg with args:", args.join(" "));
console.log("Working directory:", process.cwd());
console.log("User:", process.getuid?.() || "N/A");
recordingProcess = (0, import_child_process.spawn)(ffmpegPath, args, {
stdio: ["ignore", "pipe", "pipe"],
cwd: process.cwd()
});
recordingProcess.stdout?.on("data", (data) => {
console.log(`ffmpeg stdout: ${data}`);
});
recordingProcess.stderr?.on("data", (data) => {
const msg = data.toString();
if (msg.trim()) console.log(`ffmpeg stderr: ${msg}`);
});
recordingProcess.stdout?.resume();
recordingProcess.stderr?.resume();
recordingProcess.on("close", (code) => {
console.log(`Recording ffmpeg exited with code ${code}`);
const fileToFinalize = currentRecordingFile;
finalizeRecording(fileToFinalize);
recordingProcess = null;
currentRecordingFile = null;
recordingStartTime = null;
});
recordingProcess.on("error", (err) => {
console.error("Recording process error:", err);
const fileToFinalize = currentRecordingFile;
finalizeRecording(fileToFinalize);
recordingProcess = null;
currentRecordingFile = null;
recordingStartTime = null;
});
res.json({ status: "started", filename: currentRecordingFile.replace(/\.part$/, ".mp4") });
});
router.post("/stop", async (req, res) => {
if (!recordingProcess) {
return res.status(409).json({ error: "Aucun enregistrement en cours" });
}
const proc = recordingProcess;
const fileToFinalize = currentRecordingFile;
try {
proc.kill("SIGINT");
} catch (e) {
console.error("Error sending SIGINT:", e);
}
let waited = 0;
while (recordingProcess && waited < 15e3) {
await new Promise((r) => setTimeout(r, 100));
waited += 100;
}
if (recordingProcess) {
try {
recordingProcess.kill("SIGKILL");
} catch (e) {
console.error("Error sending SIGKILL:", e);
}
await new Promise((r) => setTimeout(r, 500));
recordingProcess = null;
currentRecordingFile = null;
recordingStartTime = null;
finalizeRecording(fileToFinalize);
return res.status(500).json({ error: "\xC9chec arr\xEAt enregistrement" });
}
res.json({ status: "stopped" });
});
router.get("/status", async (req, res) => {
res.json({
isRecording: !!recordingProcess,
startTime: recordingStartTime,
currentFile: currentRecordingFile?.replace(/\.part$/, ".mp4")
});
});
// src/server/media.ts
var import_express2 = require("express");
var import_fs2 = require("fs");
var import_path2 = require("path");
var import_archiver = __toESM(require("archiver"), 1);
var router2 = (0, import_express2.Router)();
var MEDIA_DIR2 = process.env.MEDIA_DIR || "/media";
var CONFIG_DIR2 = process.env.CONFIG_DIR || "/config";
if (!(0, import_fs2.existsSync)(MEDIA_DIR2)) {
require("fs").mkdirSync(MEDIA_DIR2, { recursive: true });
}
function getMediaType(filename) {
const ext = (0, import_path2.extname)(filename).toLowerCase();
if ([".mp4", ".webm", ".mov", ".mkv"].includes(ext)) return "video";
if ([".jpg", ".jpeg", ".png", ".webp", ".bmp"].includes(ext)) return "image";
return "other";
}
router2.get("/", async (req, res) => {
try {
const files = (0, import_fs2.readdirSync)(MEDIA_DIR2);
const media = files.filter((f) => getMediaType(f) !== "other").map((filename) => {
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
const stats = (0, import_fs2.statSync)(filepath);
return {
filename,
type: getMediaType(filename),
size: stats.size,
mtime: stats.mtime.toISOString(),
url: `/api/media/${filename}`
};
}).sort((a, b) => new Date(b.mtime).getTime() - new Date(a.mtime).getTime());
res.json(media);
} catch (e) {
console.error("Media list error:", e);
res.status(500).json({ error: "Failed to list media" });
}
});
router2.get("/:filename", async (req, res) => {
const { filename } = req.params;
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
if (!(0, import_fs2.existsSync)(filepath)) {
return res.status(404).json({ error: "File not found" });
}
const resolved = require("path").resolve(filepath);
if (!resolved.startsWith(require("path").resolve(MEDIA_DIR2))) {
return res.status(403).json({ error: "Forbidden" });
}
const stats = (0, import_fs2.statSync)(filepath);
const download = req.query.download === "1";
if (download) {
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
}
res.setHeader("Content-Length", stats.size);
res.setHeader("Accept-Ranges", "bytes");
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1;
const chunksize = end - start + 1;
res.status(206);
res.setHeader("Content-Range", `bytes ${start}-${end}/${stats.size}`);
res.setHeader("Content-Length", chunksize);
const stream2 = (0, import_fs2.createReadStream)(filepath, { start, end });
return stream2.pipe(res);
}
const stream = (0, import_fs2.createReadStream)(filepath);
stream.pipe(res);
});
router2.post("/snapshots", async (req, res) => {
const { spawn: spawn3 } = await import("child_process");
const GO2RTC_RTSP_URL2 = process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
const MEDIA_DIR3 = process.env.MEDIA_DIR || "/media";
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").split("T").join("_");
const filename = `snapshot_${timestamp}.jpg`;
const filepath = (0, import_path2.join)(MEDIA_DIR3, filename);
const ffmpegPath = process.env.FFMPEG_PATH || "ffmpeg";
const args = [
"-hide_banner",
"-loglevel",
"warning",
"-rtsp_transport",
"tcp",
"-i",
GO2RTC_RTSP_URL2,
"-frames:v",
"1",
"-q:v",
"2",
"-update",
"1",
filepath
];
const child = spawn3(ffmpegPath, args);
return new Promise((resolve, reject) => {
let stderr = "";
child.stderr?.on("data", (data) => {
stderr += data.toString();
});
child.on("close", (code) => {
if (code === 0) {
res.json({ filename });
resolve();
} else {
console.error("Snapshot ffmpeg failed:", stderr);
res.status(500).json({ error: "Snapshot failed", details: stderr });
reject(new Error("Snapshot failed"));
}
});
child.on("error", (err) => {
res.status(500).json({ error: "Snapshot error", details: err.message });
reject(err);
});
});
});
router2.delete("/:filename", async (req, res) => {
const { filename } = req.params;
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
if (!(0, import_fs2.existsSync)(filepath)) {
return res.status(404).json({ error: "File not found" });
}
const resolved = require("path").resolve(filepath);
if (!resolved.startsWith(require("path").resolve(MEDIA_DIR2))) {
return res.status(403).json({ error: "Forbidden" });
}
try {
(0, import_fs2.unlinkSync)(filepath);
res.json({ status: "deleted" });
} catch (e) {
console.error("Delete error:", e);
res.status(500).json({ error: "Failed to delete" });
}
});
router2.post("/export", async (req, res) => {
try {
const files = (0, import_fs2.readdirSync)(MEDIA_DIR2).filter((f) => getMediaType(f) !== "other");
if (files.length === 0) {
return res.status(404).json({ error: "No media to export" });
}
const archive = (0, import_archiver.default)("zip", { zlib: { level: 9 } });
let completed = false;
let aborted = false;
res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-Disposition", `attachment; filename="kai-sa-cam-media-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.zip"`);
archive.on("error", (err) => {
console.error("Archive error:", err);
if (!completed) {
res.status(500).json({ error: "Archive creation failed" });
}
});
archive.on("end", () => {
completed = true;
console.log("Archive completed");
setTimeout(() => {
for (const file of files) {
try {
const filepath = (0, import_path2.join)(MEDIA_DIR2, file);
if ((0, import_fs2.existsSync)(filepath)) {
(0, import_fs2.unlinkSync)(filepath);
console.log(`Deleted after export: ${file}`);
}
} catch (e) {
console.error(`Failed to delete ${file}:`, e);
}
}
}, 100);
});
req.on("aborted", () => {
aborted = true;
console.log("Export aborted by client");
});
res.on("close", () => {
if (!res.writableFinished) {
aborted = true;
console.log("Export connection closed prematurely");
}
});
archive.pipe(res);
for (const file of files) {
const filepath = (0, import_path2.join)(MEDIA_DIR2, file);
if ((0, import_fs2.existsSync)(filepath)) {
archive.file(filepath, { name: file });
}
}
await archive.finalize();
} catch (e) {
console.error("Export error:", e);
if (!res.headersSent) {
res.status(500).json({ error: "Export failed" });
}
}
});
// src/server/talk.ts
var import_express3 = require("express");
var router3 = (0, import_express3.Router)();
router3.get("/status", async (req, res) => {
res.json({ status: "ok", message: "Talk endpoint available at /api/talk WebSocket" });
});
// src/server/health.ts
var import_express4 = require("express");
var router4 = (0, import_express4.Router)();
router4.get("/health", async (req, res) => {
res.json({ status: "ok", service: "kai-sa-cam", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
});
// src/server/index.ts
var __dirname = process.cwd();
var app = (0, import_express5.default)();
var PORT = process.env.PORT || 8090;
app.use(import_express5.default.json({ limit: "10mb" }));
app.use(import_express5.default.urlencoded({ extended: true }));
app.use(import_express5.default.static((0, import_path3.join)(__dirname, "dist")));
var go2rtcProxy = (0, import_http_proxy_middleware.createProxyMiddleware)({
target: process.env.GO2RTC_URL || "http://kai-sa-go2rtc:1984",
changeOrigin: true,
ws: true,
pathRewrite: {
"^/go2rtc": ""
}
});
app.use("/go2rtc", go2rtcProxy);
app.use("/api/recordings", router);
app.use("/api/media", router2);
app.use("/api/talk", router3);
app.use("/api", router4);
app.get("*", (req, res, next) => {
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc")) {
return next();
}
res.sendFile((0, import_path3.join)(__dirname, "dist/index.html"));
});
var server = (0, import_http.createServer)(app);
server.on("upgrade", (req, socket, head) => {
if (req.url?.startsWith("/go2rtc")) {
go2rtcProxy.upgrade(req, socket, head);
}
});
var wss = new import_ws.WebSocketServer({ server, path: "/api/talk" });
wss.on("connection", (ws, _req) => {
console.log("Talk WS connection established");
let paplayProcess = null;
ws.on("message", (data, isBinary) => {
if (!isBinary) {
try {
const msg = JSON.parse(data.toString());
if (msg.rate && !paplayProcess) {
paplayProcess = (0, import_child_process2.spawn)("paplay", [
"--raw",
`--rate=${msg.rate}`,
"--format=s16le",
"--channels=1",
"--latency-msec=150"
]);
paplayProcess.on("error", (e) => console.error("paplay error:", e.message));
}
} catch (e) {
console.error("Talk WS message parse error:", e);
}
return;
}
if (paplayProcess?.stdin) {
paplayProcess.stdin.write(data);
}
});
ws.on("close", () => {
if (paplayProcess) {
paplayProcess.stdin.end();
paplayProcess = null;
}
});
});
server.listen(PORT, () => {
console.log(`kai-sa-cam server running on port ${PORT}`);
});
+10
View File
@@ -12,6 +12,7 @@
"express": "^4.19.2",
"ffmpeg-static": "^5.2.0",
"http-proxy-middleware": "^3.0.0",
"jose": "^6.2.13",
"ws": "^8.17.0"
},
"devDependencies": {
@@ -3095,6 +3096,15 @@
"jiti": "bin/jiti.js"
}
},
"node_modules/jose": {
"version": "6.2.13",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz",
"integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+17 -16
View File
@@ -10,27 +10,28 @@
"start": "node dist/server/index.cjs"
},
"dependencies": {
"express": "^4.19.2",
"http-proxy-middleware": "^3.0.0",
"archiver": "^7.0.1",
"ws": "^8.17.0",
"ffmpeg-static": "^5.2.0"
"express": "^4.19.2",
"ffmpeg-static": "^5.2.0",
"http-proxy-middleware": "^3.0.0",
"jose": "^6.2.13",
"ws": "^8.17.0"
},
"devDependencies": {
"@types/node": "^20.12.7",
"@types/express": "^4.17.21",
"@types/ws": "^8.5.10",
"@types/archiver": "^6.0.2",
"typescript": "^5.4.5",
"vite": "^5.2.11",
"@vitejs/plugin-react": "^4.2.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@types/express": "^4.17.21",
"@types/node": "^20.12.7",
"@types/react": "^18.3.2",
"@types/react-dom": "^18.3.0",
"tailwindcss": "^3.4.3",
"postcss": "^8.4.38",
"@types/ws": "^8.5.10",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.19",
"esbuild": "^0.21.3"
"esbuild": "^0.21.3",
"postcss": "^8.4.38",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"tailwindcss": "^3.4.3",
"typescript": "^5.4.5",
"vite": "^5.2.11"
}
}
}
+45 -21
View File
@@ -4,14 +4,21 @@ import { Controls } from "./components/Controls";
import { MediaGallery } from "./components/MediaGallery";
import { useRecorder } from "./hooks/useRecorder";
import { useTalk } from "./hooks/useTalk";
import {
apiFetch,
onSessionChange,
reauthenticate,
startSessionMonitor,
} from "./lib/api";
export function App() {
const [activeTab, setActiveTab] = useState<"live" | "media">("live");
const [isRecording, setIsRecording] = useState(false);
const [isTalking, setIsTalking] = useState(false);
const [gain, setGain] = useState(1);
const [recordingTime, setRecordingTime] = useState(0);
const [snapshots, setSnapshots] = useState<string[]>([]);
const [sessionExpired, setSessionExpired] = useState(false);
const [streamKey, setStreamKey] = useState(0);
const {
startRecording,
@@ -29,17 +36,25 @@ export function App() {
onTimeUpdate: (t) => setRecordingTime(t),
});
const { startTalk, stopTalk, error: talkError } = useTalk({ gain });
const {
isTalking,
startTalk,
stopTalk,
error: talkError,
} = useTalk({ gain });
// Surveillance de la session Cloudflare Access + bandeau de reconnexion
useEffect(() => {
const handleBeforeUnload = () => {
if (isRecording) {
navigator.sendBeacon("/api/recordings/stop");
}
const off = onSessionChange((expired) => {
setSessionExpired(expired);
if (!expired) setStreamKey((k) => k + 1); // recharge le flux vidéo après reconnexion
});
const stop = startSessionMonitor();
return () => {
off();
stop();
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [isRecording]);
}, []);
const handleRecord = async () => {
if (isRecording) {
@@ -51,10 +66,7 @@ export function App() {
const handleSnapshot = async () => {
try {
const res = await fetch("/api/media/snapshots", {
method: "POST",
credentials: "include",
});
const res = await apiFetch("/api/media/snapshots", { method: "POST" });
if (!res.ok) throw new Error("Snapshot failed");
const data = await res.json();
setSnapshots((prev) => [data.filename, ...prev]);
@@ -64,13 +76,8 @@ export function App() {
};
const handleTalk = async () => {
if (isTalking) {
stopTalk();
setIsTalking(false);
} else {
await startTalk();
setIsTalking(true);
}
if (isTalking) stopTalk();
else await startTalk();
};
return (
@@ -82,6 +89,18 @@ export function App() {
</h1>
</header>
{sessionExpired && (
<div className="bg-amber-600 text-white text-sm px-4 py-2 flex items-center justify-between">
<span>Session expirée.</span>
<button
className="underline font-medium"
onClick={() => reauthenticate().catch(() => {})}
>
Se reconnecter
</button>
</div>
)}
<main className="flex-1 flex flex-col">
<nav className="flex border-b border-gray-700 bg-gray-800">
<button
@@ -100,7 +119,12 @@ export function App() {
{activeTab === "live" ? (
<div className="flex-1 flex flex-col p-4 gap-4 overflow-hidden">
<VideoPlayer streamUrl="https://stream.esiah.dev/stream.html?src=webcam&mode=mse" />
{/* Même origine => même session Access, plus de stream.esiah.dev.
Le key force le rechargement du flux après une reconnexion. */}
<VideoPlayer
key={streamKey}
streamUrl="/go2rtc/stream.html?src=webcam&mode=mse"
/>
<Controls
isRecording={isRecording}
recordingTime={recordingTime}
+19 -10
View File
@@ -1,4 +1,5 @@
import { useState, useEffect } from "react";
import { apiFetch, SessionExpiredError } from "../lib/api";
interface MediaItem {
filename: string;
@@ -16,12 +17,16 @@ export function MediaGallery() {
const fetchMedia = async () => {
try {
const res = await fetch("/api/media", { credentials: "include" });
const res = await apiFetch("/api/media");
if (!res.ok) throw new Error();
const data = await res.json();
setMedia(data);
} catch (e) {
setError("Erreur chargement médias");
setError(
e instanceof SessionExpiredError
? "Session expirée, reconnecte-toi"
: "Erreur chargement médias",
);
}
};
@@ -31,24 +36,24 @@ export function MediaGallery() {
const handleDelete = async (filename: string) => {
try {
const res = await fetch(`/api/media/${filename}`, {
const res = await apiFetch(`/api/media/${encodeURIComponent(filename)}`, {
method: "DELETE",
credentials: "include",
});
if (!res.ok) throw new Error();
setMedia((prev) => prev.filter((m) => m.filename !== filename));
setItemToDelete(null);
} catch (e) {
setError("Erreur suppression");
setError(
e instanceof SessionExpiredError
? "Session expirée, reconnecte-toi"
: "Erreur suppression",
);
}
};
const handleExportAll = async () => {
try {
const res = await fetch("/api/media/export", {
method: "POST",
credentials: "include",
});
const res = await apiFetch("/api/media/export", { method: "POST" });
if (!res.ok) throw new Error();
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
@@ -61,7 +66,11 @@ export function MediaGallery() {
window.URL.revokeObjectURL(url);
fetchMedia();
} catch (e) {
setError("Erreur export");
setError(
e instanceof SessionExpiredError
? "Session expirée, reconnecte-toi"
: "Erreur export",
);
}
};
+2 -13
View File
@@ -1,25 +1,14 @@
import { useEffect, useRef } from "react";
interface VideoPlayerProps {
streamUrl: string;
streamUrl: string; // chemin same-origin, ex: /go2rtc/stream.html?src=webcam&mode=mse
}
export function VideoPlayer({ streamUrl }: VideoPlayerProps) {
const iframeRef = useRef<HTMLIFrameElement>(null);
useEffect(() => {
if (iframeRef.current) {
iframeRef.current.src = streamUrl;
}
}, [streamUrl]);
return (
<div className="flex-1 min-h-[300px] relative bg-black rounded-lg overflow-hidden flex items-center justify-center">
<iframe
ref={iframeRef}
src={streamUrl}
className="w-full h-full border-none absolute inset-0"
allow="autoplay; encrypted-media"
allow="autoplay; encrypted-media; fullscreen"
title="Flux caméra"
/>
</div>
+75 -44
View File
@@ -1,4 +1,5 @@
import { useState, useCallback, useRef, useEffect } from "react";
import { apiFetch, SessionExpiredError } from "../lib/api";
interface UseRecorderOptions {
onStart?: () => void;
@@ -6,6 +7,21 @@ interface UseRecorderOptions {
onTimeUpdate?: (seconds: number) => void;
}
const errMsg = (e: unknown, fallback: string) =>
e instanceof SessionExpiredError
? "Session expirée, reconnecte-toi"
: e instanceof Error
? e.message
: fallback;
async function readError(res: Response, fallback: string) {
try {
return (await res.json()).error || fallback;
} catch {
return fallback;
}
}
export function useRecorder({
onStart,
onStop,
@@ -14,67 +30,82 @@ export function useRecorder({
const [isRecording, setIsRecording] = useState(false);
const [error, setError] = useState<string | null>(null);
const intervalRef = useRef<number>();
const startTimeRef = useRef<number>();
const isRecordingRef = useRef(isRecording);
const isRecordingRef = useRef(false);
isRecordingRef.current = isRecording;
const stopRecording = useCallback(async () => {
setError(null);
try {
const res = await fetch("/api/recordings/stop", { method: "POST" });
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || "Failed to stop recording");
}
setIsRecording(false);
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
onStop?.();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur arrêt enregistrement");
}
}, [onStop]);
// Callbacks toujours à jour sans recréer les fonctions
const cb = useRef({ onStart, onStop, onTimeUpdate });
cb.current = { onStart, onStop, onTimeUpdate };
const clearTimer = () => {
if (intervalRef.current) clearInterval(intervalRef.current);
intervalRef.current = undefined;
};
const beginTimer = (startedAt: number) => {
clearTimer();
const tick = () =>
cb.current.onTimeUpdate?.(Math.floor((Date.now() - startedAt) / 1000));
tick();
intervalRef.current = window.setInterval(tick, 1000);
};
const markStopped = () => {
clearTimer();
setIsRecording(false);
cb.current.onStop?.();
};
// Récupère un enregistrement déjà en cours côté serveur (reload, autre onglet, 409)
const adoptRunning = useCallback(async (): Promise<boolean> => {
const res = await apiFetch("/api/recordings/status");
const s = await res.json();
if (!s.isRecording) return false;
setIsRecording(true);
cb.current.onStart?.();
beginTimer(s.startTime ?? Date.now());
return true;
}, []);
const startRecording = useCallback(async () => {
setError(null);
try {
const res = await fetch("/api/recordings/start", { method: "POST" });
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || "Failed to start recording");
}
const res = await apiFetch("/api/recordings/start", { method: "POST" });
if (res.status === 409 && (await adoptRunning())) return;
if (!res.ok)
throw new Error(await readError(res, "Failed to start recording"));
setIsRecording(true);
startTimeRef.current = Date.now();
onStart?.();
intervalRef.current = window.setInterval(() => {
onTimeUpdate?.(
Math.floor(
(Date.now() - (startTimeRef.current || Date.now())) / 1000,
),
);
}, 1000);
cb.current.onStart?.();
beginTimer(Date.now());
} catch (e) {
setError(
e instanceof Error ? e.message : "Erreur démarrage enregistrement",
);
setError(errMsg(e, "Erreur démarrage enregistrement"));
}
}, [onStart, onTimeUpdate]);
}, [adoptRunning]);
const stopRecording = useCallback(async () => {
setError(null);
try {
const res = await apiFetch("/api/recordings/stop", { method: "POST" });
// 409 = plus rien en cours côté serveur : l'UI doit juste se resynchroniser
if (!res.ok && res.status !== 409)
throw new Error(await readError(res, "Failed to stop recording"));
markStopped();
} catch (e) {
setError(errMsg(e, "Erreur arrêt enregistrement"));
}
}, []);
useEffect(() => {
adoptRunning().catch(() => {});
const handleBeforeUnload = () => {
if (isRecordingRef.current) {
navigator.sendBeacon("/api/recordings/stop");
}
if (isRecordingRef.current) navigator.sendBeacon("/api/recordings/stop");
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
clearTimer();
};
}, []);
}, [adoptRunning]);
return { isRecording, error, startRecording, stopRecording };
}
+129 -91
View File
@@ -1,129 +1,167 @@
import { useState, useCallback, useRef, useEffect } from "react";
import { checkSession, reauthenticate, wsUrl } from "../lib/api";
interface UseTalkOptions {
gain?: number;
}
const WORKLET = `
class Processor extends AudioWorkletProcessor {
process(inputs) {
const input = inputs[0]
if (input && input.length > 0) {
const f = input[0]
const i16 = new Int16Array(f.length)
for (let i = 0; i < f.length; i++) {
const s = Math.max(-1, Math.min(1, f[i]))
i16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF
}
this.port.postMessage(i16.buffer, [i16.buffer])
}
return true
}
}
registerProcessor('pcm-processor', Processor)
`;
const MAX_ATTEMPTS = 10;
export function useTalk({ gain = 1 }: UseTalkOptions = {}) {
const [isTalking, setIsTalking] = useState(false);
const [error, setError] = useState<string | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const mediaStreamRef = useRef<MediaStream | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const workletNodeRef = useRef<AudioWorkletNode | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const ctxRef = useRef<AudioContext | null>(null);
const gainNodeRef = useRef<GainNode | null>(null);
const nodeRef = useRef<AudioWorkletNode | null>(null);
const wantRef = useRef(false); // l'utilisateur veut parler
const attemptsRef = useRef(0);
const retryRef = useRef<number>();
useEffect(() => {
if (gainNodeRef.current) {
gainNodeRef.current.gain.value = gain;
}
if (gainNodeRef.current) gainNodeRef.current.gain.value = gain;
}, [gain]);
const stopTalk = useCallback((reason?: string) => {
wantRef.current = false;
clearTimeout(retryRef.current);
const ws = wsRef.current;
wsRef.current = null;
ws?.close();
streamRef.current?.getTracks().forEach((t) => t.stop());
streamRef.current = null;
ctxRef.current?.close().catch(() => {});
ctxRef.current = null;
gainNodeRef.current = null;
nodeRef.current = null;
setIsTalking(false);
if (typeof reason === "string") setError(reason);
}, []);
// Ouvre (ou rouvre) UNIQUEMENT le WebSocket ; micro + AudioContext restent en place.
const connect = useCallback(() => {
const ctx = ctxRef.current;
const node = nodeRef.current;
if (!ctx || !node || !wantRef.current) return;
const ws = new WebSocket(wsUrl("/api/talk"));
ws.binaryType = "arraybuffer";
wsRef.current = ws;
ws.onopen = () => {
attemptsRef.current = 0;
setError(null);
ws.send(JSON.stringify({ rate: ctx.sampleRate }));
};
node.port.onmessage = (e) => {
const cur = wsRef.current;
if (cur && cur.readyState === WebSocket.OPEN) cur.send(e.data);
};
ws.onclose = async (ev) => {
if (wsRef.current !== ws) return; // fermeture volontaire / ancienne socket
wsRef.current = null;
if (!wantRef.current) return;
if (ev.code === 4001)
return stopTalk("Micro repris par un autre appareil");
if (++attemptsRef.current > MAX_ATTEMPTS)
return stopTalk("Connexion micro perdue");
// Cause probable : session Access expirée (le handshake WS est redirigé)
if (!(await checkSession())) {
try {
await reauthenticate(); // popup ; peut être bloquée hors geste utilisateur
} catch {
return stopTalk("Session expirée, reconnecte-toi puis réessaie");
}
}
const delay = Math.min(500 * 2 ** (attemptsRef.current - 1), 5000);
retryRef.current = window.setTimeout(connect, delay);
};
// onerror est toujours suivi de onclose : la logique de reconnexion y est centralisée.
}, [stopTalk]);
const startTalk = useCallback(async () => {
setError(null);
if (wantRef.current) return;
try {
// Valide la session AVANT de demander le micro (évite un état à moitié initialisé)
if (!(await checkSession())) await reauthenticate();
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
},
audio: { echoCancellation: true, noiseSuppression: true },
});
mediaStreamRef.current = stream;
streamRef.current = stream;
stream.getAudioTracks()[0].onended = () => stopTalk("Micro déconnecté");
const audioContext = new AudioContext();
audioContextRef.current = audioContext;
await audioContext.resume();
const ctx = new AudioContext();
ctxRef.current = ctx;
await ctx.resume();
const workletBlob = new Blob(
[
`
class Processor extends AudioWorkletProcessor {
process(inputs) {
const input = inputs[0]
if (input && input.length > 0) {
const float32 = input[0]
const int16 = new Int16Array(float32.length)
for (let i = 0; i < float32.length; i++) {
const s = Math.max(-1, Math.min(1, float32[i]))
int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF
}
this.port.postMessage(int16.buffer, [int16.buffer])
}
return true
}
}
registerProcessor('pcm-processor', Processor)
`,
],
{ type: "application/javascript" },
const url = URL.createObjectURL(
new Blob([WORKLET], { type: "application/javascript" }),
);
const workletUrl = URL.createObjectURL(workletBlob);
await audioContext.audioWorklet.addModule(workletUrl);
try {
await ctx.audioWorklet.addModule(url);
} finally {
URL.revokeObjectURL(url);
}
const workletNode = new AudioWorkletNode(audioContext, "pcm-processor");
workletNodeRef.current = workletNode;
const source = audioContext.createMediaStreamSource(stream);
const gainNode = audioContext.createGain();
const node = new AudioWorkletNode(ctx, "pcm-processor");
nodeRef.current = node;
const source = ctx.createMediaStreamSource(stream);
const gainNode = ctx.createGain();
gainNode.gain.value = gain;
gainNodeRef.current = gainNode;
source.connect(gainNode);
gainNode.connect(workletNode);
workletNode.connect(audioContext.destination);
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${protocol}//${location.host}/api/talk`);
wsRef.current = ws;
ws.binaryType = "arraybuffer";
ws.onopen = () => {
ws.send(JSON.stringify({ rate: audioContext.sampleRate, gain }));
};
ws.onerror = () => {
setError("Erreur connexion micro");
stopTalk();
};
workletNode.port.onmessage = (e) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(e.data);
}
};
gainNode.connect(node);
node.connect(ctx.destination); // le worklet ne produit aucun son en sortie
wantRef.current = true;
attemptsRef.current = 0;
setIsTalking(true);
connect();
} catch (e) {
setError(
stopTalk(
e instanceof Error ? e.message : "Impossible d'accéder au microphone",
);
}
}, [gain]);
}, [gain, connect, stopTalk]);
const stopTalk = useCallback(() => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach((t) => t.stop());
mediaStreamRef.current = null;
}
if (audioContextRef.current) {
audioContextRef.current.close();
audioContextRef.current = null;
}
workletNodeRef.current = null;
gainNodeRef.current = null;
setIsTalking(false);
// Mobile : l'AudioContext est suspendu quand l'onglet passe en arrière-plan
useEffect(() => {
const onVis = () => {
if (document.visibilityState === "visible")
ctxRef.current?.resume().catch(() => {});
};
document.addEventListener("visibilitychange", onVis);
return () => document.removeEventListener("visibilitychange", onVis);
}, []);
useEffect(() => {
return () => {
stopTalk();
};
}, [stopTalk]);
useEffect(() => () => stopTalk(), [stopTalk]);
return { isTalking, error, startTalk, stopTalk };
return { isTalking, error, startTalk, stopTalk: () => stopTalk() };
}
+133
View File
@@ -0,0 +1,133 @@
// Client API avec gestion de l'expiration de session Cloudflare Access.
// Principe : fetch avec redirect:"manual" -> une redirection vers cloudflareaccess.com
// donne une réponse "opaqueredirect" (au lieu du "NetworkError" CORS). On rouvre alors
// une popup /auth/done (protégée par Access) qui se ferme seule, puis on rejoue la requête.
export class SessionExpiredError extends Error {
constructor() {
super("Session Cloudflare Access expirée");
}
}
type Listener = (expired: boolean) => void;
const listeners = new Set<Listener>();
let expired = false;
function setExpired(v: boolean) {
if (expired !== v) {
expired = v;
listeners.forEach((l) => l(v));
}
}
export function onSessionChange(l: Listener): () => void {
listeners.add(l);
return () => listeners.delete(l);
}
function isExpiredResponse(r: Response): boolean {
return r.type === "opaqueredirect" || r.status === 0 || r.status === 401;
}
async function probe(): Promise<"ok" | "expired" | "offline"> {
try {
const r = await fetch("/api/health", {
credentials: "same-origin",
redirect: "manual",
cache: "no-store",
});
return isExpiredResponse(r) ? "expired" : "ok";
} catch {
return "offline";
}
}
/** true si la session est valide (ou si on est simplement hors-ligne). */
export async function checkSession(): Promise<boolean> {
const s = await probe();
setExpired(s === "expired");
return s !== "expired";
}
let pending: Promise<void> | null = null;
/** Ouvre la popup de reconnexion. À appeler depuis un clic si possible (anti-popup-blocker). */
export function reauthenticate(): Promise<void> {
pending ??= new Promise<void>((resolve, reject) => {
const w = window.open(
"/auth/done",
"kaisa-auth",
"popup,width=480,height=680",
);
if (!w) return reject(new SessionExpiredError());
let done = false;
const finish = async () => {
if (done) return;
done = true;
clearInterval(poll);
window.removeEventListener("message", onMsg);
(await checkSession()) ? resolve() : reject(new SessionExpiredError());
};
const onMsg = (e: MessageEvent) => {
if (e.origin === location.origin && e.data === "kaisa-auth-ok")
void finish();
};
window.addEventListener("message", onMsg);
const poll = setInterval(() => {
if (w.closed) void finish();
}, 500);
}).finally(() => {
pending = null;
});
return pending!;
}
export async function apiFetch(
input: string,
init: RequestInit = {},
): Promise<Response> {
const run = () =>
fetch(input, { ...init, credentials: "same-origin", redirect: "manual" });
let res: Response | null = null;
let err: unknown;
try {
res = await run();
} catch (e) {
err = e;
}
if (res && !isExpiredResponse(res)) {
setExpired(false);
return res;
}
// Erreur réseau : vraie panne, ou session expirée ? On teste.
if (!res && (await probe()) !== "expired") throw err;
setExpired(true);
await reauthenticate(); // lève SessionExpiredError si annulé / popup bloquée
const retry = await run();
if (isExpiredResponse(retry)) throw new SessionExpiredError();
setExpired(false);
return retry;
}
export function wsUrl(path: string): string {
return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${path}`;
}
/** Vérifie la session toutes les minutes, au retour sur l'onglet et au retour du réseau. */
export function startSessionMonitor(): () => void {
const tick = () => void checkSession();
const id = setInterval(tick, 60_000);
const onVis = () => document.visibilityState === "visible" && tick();
document.addEventListener("visibilitychange", onVis);
window.addEventListener("online", tick);
tick();
return () => {
clearInterval(id);
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("online", tick);
};
}
+152 -44
View File
@@ -1,97 +1,205 @@
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";
// Use process.cwd() instead of import.meta.url for bundled compatibility
const __dirname = process.cwd();
const app = express();
const PORT = process.env.PORT || 8090;
// Middleware
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 }));
// Serve static files (built React app)
// 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")));
// Proxy go2rtc requests
// 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: true,
pathRewrite: {
"^/go2rtc": "",
},
ws: false,
pathRewrite: { "^/go2rtc": "" },
});
app.use("/go2rtc", go2rtcProxy);
// API routes
app.use("/api/recordings", recorderRouter);
app.use("/api/media", mediaRouter);
app.use("/api/talk", talkRouter);
app.use("/api", healthRouter);
// SPA fallback - serve index.html for non-API routes
app.get("*", (req, res, next) => {
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc")) {
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc"))
return next();
}
res.sendFile(join(__dirname, "dist/index.html"));
});
const server = createServer(app);
server.on("upgrade", (req: any, socket: any, head: any) => {
if (req.url?.startsWith("/go2rtc")) {
go2rtcProxy.upgrade(req, socket, head);
// ---------------------------------------------------------------------------
// 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();
});
// WebSocket server for talk
const wss = new WebSocketServer({ server, path: "/api/talk" });
// ---------------------------------------------------------------------------
// 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) => {
let paplayProcess: ChildProcessWithoutNullStreams | null = null;
// 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);
}
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
if (!isBinary) {
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 {
const msg = JSON.parse(data.toString());
if (msg.rate && !paplayProcess) {
paplayProcess = spawn("paplay", [
"--raw",
`--rate=${msg.rate}`,
"--format=s16le",
"--channels=1",
"--latency-msec=150",
]);
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");
}
} catch (e) {}
});
p.stdin.on("error", () => {});
p.stdout.resume();
p.stderr.resume();
me.player = p;
return;
}
if (paplayProcess?.stdin) {
paplayProcess.stdin.write(data);
}
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", () => {
if (paplayProcess) {
paplayProcess.kill("SIGKILL");
paplayProcess = null;
}
});
ws.on("close", cleanup);
ws.on("error", cleanup);
});
server.listen(PORT, () => {
console.log(`kai-sa-cam server running on port ${PORT}`);
});
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}`),
);
+2 -2
View File
@@ -17,7 +17,6 @@ services:
- /home/esiahdmin/.config/pulse/cookie:/root/.config/pulse/cookie:ro
networks:
- kai-sa-cam-internal
- kai-sa-cam-tunnel
cap_drop:
- ALL
security_opt:
@@ -45,10 +44,11 @@ services:
- MAX_RECORDING_MINUTES=${MAX_RECORDING_MINUTES:-120}
- DISK_MIN_FREE_GB=${DISK_MIN_FREE_GB:-2}
- GO2RTC_URL=http://kai-sa-go2rtc:1984
- GO2RTC_PUBLIC_URL=https://stream.esiah.dev
- GO2RTC_RTSP_URL=rtsp://kai-sa-go2rtc:8554/webcam
- PULSE_SERVER=${PULSE_SERVER}
- XDG_RUNTIME_DIR=/run/user/1001
- CF_ACCESS_TEAM_DOMAIN=${CF_ACCESS_TEAM_DOMAIN:-}
- CF_ACCESS_AUD=${CF_ACCESS_AUD:-}
volumes:
- ./media:/media
- ./config:/config
-9
View File
@@ -1,9 +0,0 @@
FROM node:22-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
pulseaudio-utils bluez ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
RUN npm i ws
COPY server.js index.html entrypoint.sh ./
RUN chmod +x entrypoint.sh
CMD ["./entrypoint.sh"]
-21
View File
@@ -1,21 +0,0 @@
#!/bin/bash
# Boucle de maintien : Bluetooth + volume de l'enceinte
(
while true; do
if ! bluetoothctl info "$BT_MAC" 2>/dev/null | grep -q "Connected: yes"; then
echo "[bt] connexion à $BT_MAC"
bluetoothctl connect "$BT_MAC" >/dev/null 2>&1
sleep 5
fi
if bluetoothctl info "$BT_MAC" 2>/dev/null | grep -q "Connected: yes"; then
SINK=$(pactl list short sinks 2>/dev/null | grep -i bluez | awk '{print $2}' | head -1)
if [ -n "$SINK" ]; then
pactl set-default-sink "$SINK" 2>/dev/null
pactl set-sink-volume "$SINK" "${SINK_VOLUME:-100%}" 2>/dev/null
pactl set-sink-mute "$SINK" 0 2>/dev/null
fi
fi
sleep 15
done
) &
exec node server.js
-59
View File
@@ -1,59 +0,0 @@
<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cam</title>
<body style="margin:0;font-family:sans-serif;background:#111;color:#eee">
<iframe src="/stream.html?src=webcam&mode=mse" style="width:100%;height:62vh;border:0"></iframe>
<div style="padding:6px 10px;display:flex;gap:10px;align-items:center">
<span id="s" style="flex:1">micro éteint</span>
<label>Gain <input id="g" type="range" min="0.2" max="5" step="0.1" value="1"></label>
</div>
<button id="b" style="width:100%;height:18vh;font-size:2rem">🎤 Micro OFF</button>
<script>
const s = document.getElementById('s'), b = document.getElementById('b'), g = document.getElementById('g');
let ws, ctx, node, stream, wake, on = false, buf = [], n = 0;
const worklet = URL.createObjectURL(new Blob([
"class P extends AudioWorkletProcessor{process(i){const c=i[0][0];if(c)this.port.postMessage(c.slice(0));return true}}registerProcessor('p',P)"
], { type: 'application/javascript' }));
function connect() {
if (!on) return;
ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/mic/ws');
ws.onopen = () => { ws.send(JSON.stringify({ rate: ctx.sampleRate })); s.textContent = 'micro actif (' + ctx.sampleRate + ' Hz)'; };
ws.onclose = () => { if (on) { s.textContent = 'reconnexion...'; setTimeout(connect, 1000); } };
}
async function lock() { try { wake = await navigator.wakeLock.request('screen'); } catch (e) {} }
async function start() {
on = true; s.textContent = 'demande micro...';
try { stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }); }
catch (e) { on = false; s.textContent = 'micro refusé: ' + e.message; return; }
ctx = new AudioContext(); await ctx.resume();
await ctx.audioWorklet.addModule(worklet);
const src = ctx.createMediaStreamSource(stream);
node = new AudioWorkletNode(ctx, 'p');
node.port.onmessage = e => {
buf.push(e.data); n += e.data.length;
if (n < 2048) return;
const o = new Int16Array(n), k0 = +g.value; let k = 0;
for (const c of buf) for (let i = 0; i < c.length; i++) o[k++] = Math.max(-1, Math.min(1, c[i] * k0)) * 32767;
buf = []; n = 0;
if (ws && ws.readyState === 1) ws.send(o.buffer);
};
const mute = ctx.createGain(); mute.gain.value = 0;
src.connect(node); node.connect(mute); mute.connect(ctx.destination);
connect(); lock(); try { document.querySelector('iframe').contentDocument.querySelector('video').muted = true; } catch (e) {}
b.textContent = '🎤 Micro ON (toucher pour couper)';
}
function stop() {
on = false; s.textContent = 'micro éteint'; b.textContent = '🎤 Micro OFF';
try { node && node.disconnect(); } catch (e) {}
stream && stream.getTracks().forEach(t => t.stop());
ctx && ctx.close(); ws && ws.close(); wake && wake.release().catch(() => {});
node = stream = ctx = ws = wake = null; buf = []; n = 0;
}
b.onclick = () => on ? stop() : start();
document.addEventListener('visibilitychange', () => {
if (on && document.visibilityState === 'visible') { ctx && ctx.resume(); lock(); }
});
</script>
-36
View File
@@ -1,36 +0,0 @@
const http = require('http'), fs = require('fs'), { spawn } = require('child_process');
const { WebSocketServer } = require('ws');
const page = fs.readFileSync('index.html');
const srv = http.createServer((q, r) => {
if (q.url.split('?')[0] !== '/mic') { r.statusCode = 404; return r.end(); }
r.setHeader('content-type', 'text/html');
r.end(page);
});
const wss = new WebSocketServer({ server: srv, path: '/mic/ws' });
let active = null;
wss.on('connection', ws => {
if (active) { try { active.ws.close(); } catch (e) {} try { active.p && active.p.stdin.end(); } catch (e) {} }
const me = { ws, p: null };
active = me;
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', (d, bin) => {
if (!bin) {
if (me.p) return;
let rate = 48000;
try { rate = parseInt(JSON.parse(d.toString()).rate) || 48000; } catch (e) {}
me.p = spawn('paplay', ['--raw', '--rate=' + rate, '--format=s16le', '--channels=1', '--latency-msec=150']);
me.p.on('error', e => console.log('paplay error', e.message));
me.p.stdin.on('error', () => {});
console.log('mic start', rate);
return;
}
if (me.p) me.p.stdin.write(d);
});
ws.on('close', () => { if (me.p) me.p.stdin.end(); if (active === me) active = null; console.log('mic stop'); });
});
setInterval(() => wss.clients.forEach(ws => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false; ws.ping();
}), 20000);
srv.listen(8090);
Executable → Regular
+2 -2
View File
@@ -9,7 +9,7 @@ last=$(cat "$STAMP" 2>/dev/null || echo 0)
recreate() {
echo "$(date '+%F %T') $1 : recreation go2rtc" >> "$LOG"
(cd /srv/apps/cam && docker compose up -d --force-recreate go2rtc >/dev/null 2>&1)
(cd /srv/apps/kai-sa-cam && docker compose --profile prod up -d --force-recreate kai-sa-go2rtc >/dev/null 2>&1)
echo "$now" > "$STAMP"
}
@@ -25,7 +25,7 @@ if lsusb | grep -q '1d5b:0104'; then
exit 0
fi
echo "ok" > "$STATE"
if [ "$(docker inspect -f '{{.State.Running}}' go2rtc 2>/dev/null)" != "true" ]; then
if [ "$(docker inspect -f '{{.State.Running}}' kai-sa-go2rtc 2>/dev/null)" != "true" ]; then
recreate "go2rtc arrete"
fi
else