diff --git a/CHANGELOG.md b/CHANGELOG.md index c5e45de..cdf4394 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.78.0 + +- **House of RC connection (step 1):** Settings → System → 🏠 House of RC. Paste the club's API key once and press **Save key**; it is stored only on the server (`data/houseofrc.json`, readable by the server user only) and is never sent back to any browser, export or backup. **Test connection** shows the account and the request limit, e.g. "Connected as (name) (id …) · 60 requests/min". With the admin PIN on, saving, removing and using the key needs a login. The key can also come from the `HOUSEOFRC_API_KEY` environment variable. + ## 1.77.2 ### Fixed diff --git a/README.md b/README.md index c19e7d0..199f7fd 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore is meant for a trusted race network: - **Admin PIN** (Settings → System & backup, off by default) protects every change through the API. The login lasts 30 days and is throttled against guessing. - **Race Controller Master:** one computer at a time runs the race (the decoder, start, pause, resume, stop, false start, resetting a heat and the autopilot, also from the speaker panel). Judging corrections and the other calls work from any computer. The computer running the server (page opened on `localhost`) becomes master on its own and shows a green line "🎙 You are the Race Controller Master" with **Release master**. Phones and other computers follow the race live (updated every second), show "You are following the race …" and become master only when someone presses the button; that computer then remembers the role. They can also prepare drivers and races. Whoever works as race controller presses **Take over as master**, and the previous master lets go of the decoder within seconds. With the admin PIN on, taking over needs a login. Name the computer under Settings → System, e.g. "Speaker booth". Overlays and OBS are always view-only. +- **House of RC:** under Settings → System → 🏠 House of RC you save the club's API key once (stored on the server only, never shown again) and press **Test connection**. Importing entries and posting results back are being built together with House of RC (see ROADMAP.md). - **`RC_ADMIN_ALLOWED_CIDRS`** restricts admin changes to certain addresses or networks, e.g. `192.168.1.0/24`. - **`RC_ALLOWED_ORIGINS`** is for a UI deliberately served from another address. - **Don't expose port 8081 to the internet.** Reads are not PIN protected. Publish only the public overlay and mobile profile paths through a reverse proxy or VPN. diff --git a/README.sv.md b/README.sv.md index 37aae62..6ac7536 100644 --- a/README.sv.md +++ b/README.sv.md @@ -335,6 +335,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore är tänkt för ett betrott racenätverk: - **Admin-PIN** (Inställningar → System & backup, av som standard) skyddar alla ändringar via API:t. Inloggningen gäller i 30 dagar och är skyddad mot gissning. - **Race Controller Master:** bara en dator åt gången kör racet (decodern, start, paus, fortsätt, stopp, tjuvstart, nollställ heat och autopiloten, även från speakerpanelen). Domarvyns korrigeringar och övriga utrop fungerar från alla datorer. Datorn som kör servern (sidan öppnad på `localhost`) blir master av sig själv och visar en grön rad "🎙 Du är Race Controller Master" med **Släpp master**. Mobiler och andra datorer följer racet live (uppdateras varje sekund), visar "Du följer racet …" och blir master bara när någon trycker på knappen; den datorn minns sedan rollen. De kan också förbereda förare och race. Den som jobbar som race controller trycker **Ta över som master**, och den förra mastern släpper decodern inom några sekunder. Med admin-PIN krävs inloggning för att ta över. Ge datorn ett namn under Inställningar → System, t.ex. "Speakerbåset". Overlays och OBS är alltid bara visning. +- **House of RC:** under Inställningar → System → 🏠 House of RC sparar du klubbens API-nyckel en gång (bara på servern, visas aldrig igen) och trycker **Testa anslutning**. Att hämta anmälningar och skicka tillbaka resultat byggs tillsammans med House of RC (se ROADMAP.md). - **`RC_ADMIN_ALLOWED_CIDRS`** begränsar adminändringar till vissa adresser eller nät, till exempel `192.168.1.0/24`. - **`RC_ALLOWED_ORIGINS`** används för ett gränssnitt som medvetet körs från en annan adress. - **Exponera inte port 8081 mot internet.** Läsningar skyddas inte av PIN. Publicera bara sökvägarna för publik overlay och mobilprofil via reverse proxy eller VPN. diff --git a/package-lock.json b/package-lock.json index b6345c5..8a05bb0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.77.2", + "version": "1.78.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.77.2", + "version": "1.78.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index dc22b22..f023121 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.77.2", + "version": "1.78.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/server.js b/server.js index fd91738..731d003 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,7 @@ const { createTts, resolvePiperBinary } = require("./server/tts"); const { installAll: installPiperAll, VOICES: PIPER_VOICES } = require("./server/tts_install"); const { createDecoderSimulator } = require("./server/decoder_sim"); const { buildStyledPdf } = require("./server/pdf_render"); +const { createHouseOfRc } = require("./server/houseofrc"); const PORT = Number(process.env.PORT || 8081); const HOST = process.env.HOST || "0.0.0.0"; @@ -20,6 +21,7 @@ const DB_DIR = process.env.RC_TIMING_DATA_DIR ? path.resolve(process.env.RC_TIMI const DB_PATH = path.join(DB_DIR, "rc_timing.sqlite"); const AMMC_CONFIG_PATH = path.join(DB_DIR, "ammc_config.json"); const auth = createAuth({ dataDir: DB_DIR, allowedCidrs: process.env.RC_ADMIN_ALLOWED_CIDRS || "" }); +const houseOfRc = createHouseOfRc({ dataDir: DB_DIR }); const tts = createTts({ dataDir: DB_DIR, projectDir: __dirname, @@ -469,6 +471,20 @@ app.post("/api/controller/release", (req, res) => { res.json(controllerView()); }); +// House of RC: the key is write-only from the browser (POST is PIN-protected by the middleware). +app.get("/api/houseofrc/status", (_req, res) => res.json(houseOfRc.status())); +app.post("/api/houseofrc/key", (req, res) => { + try { + res.json({ ok: true, ...houseOfRc.setKey(req.body?.apiKey) }); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); +app.post("/api/houseofrc/test", async (_req, res) => { + const result = await houseOfRc.testConnection(); + res.status(result.ok ? 200 : 502).json(result); +}); + app.post("/api/state", (req, res) => { if (!req.body || typeof req.body !== "object") { res.status(400).json({ error: "Expected JSON body" }); diff --git a/server/houseofrc.js b/server/houseofrc.js new file mode 100644 index 0000000..b34b022 --- /dev/null +++ b/server/houseofrc.js @@ -0,0 +1,79 @@ +// House of RC (api.houseofrc.com) connection. The API key is a club secret: it lives only in +// data/houseofrc.json (mode 600) or the HOUSEOFRC_API_KEY env var, never in app_state, so it +// can't leak through GET /api/state, a JSON export or a backup. The browser only ever sees +// whether a key is set and its last four characters. +const fs = require("fs"); +const path = require("path"); + +const DEFAULT_BASE_URL = "https://api.houseofrc.com"; +const TIMEOUT_MS = 10000; + +function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fetch }) { + const configPath = path.join(dataDir, "houseofrc.json"); + const baseUrl = String(env.HOUSEOFRC_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, ""); + + const readStoredKey = () => { + try { + return String(JSON.parse(fs.readFileSync(configPath, "utf8")).apiKey || ""); + } catch { + return ""; + } + }; + const getKey = () => String(env.HOUSEOFRC_API_KEY || "").trim() || readStoredKey(); + + function status() { + const key = getKey(); + return { + configured: Boolean(key), + source: env.HOUSEOFRC_API_KEY ? "env" : key ? "file" : "none", + keyHint: key ? `…${key.slice(-4)}` : "", + }; + } + + function setKey(value) { + const key = String(value || "").trim(); + if (!key) { + fs.rmSync(configPath, { force: true }); + return status(); + } + if (key.length < 16 || key.length > 200 || /\s/.test(key)) throw new Error("invalid_key"); + fs.mkdirSync(dataDir, { recursive: true }); + fs.writeFileSync(configPath, JSON.stringify({ apiKey: key, savedAt: new Date().toISOString() }), { mode: 0o600 }); + fs.chmodSync(configPath, 0o600); + return status(); + } + + // GET against the API with the club key. Returns { ok, status, data, error, retryAfter }. + async function get(apiPath, query = {}) { + const key = getKey(); + if (!key) return { ok: false, status: 0, error: "not_configured" }; + const url = new URL(baseUrl + apiPath); + Object.entries(query).forEach(([name, value]) => { + if (value !== undefined && value !== null && value !== "") url.searchParams.set(name, String(value)); + }); + try { + const response = await fetchImpl(url, { + headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + const data = await response.json().catch(() => null); + if (response.ok) return { ok: true, status: response.status, data }; + const error = response.status === 401 || response.status === 403 ? "unauthorized" + : response.status === 429 ? "rate_limited" : "http_error"; + return { ok: false, status: response.status, error, retryAfter: Number(response.headers.get("retry-after")) || 0 }; + } catch (error) { + return { ok: false, status: 0, error: error?.name === "TimeoutError" ? "timeout" : "unreachable" }; + } + } + + async function testConnection() { + const result = await get("/v1/me"); + if (!result.ok) return result; + const body = result.data?.data || {}; + return { ok: true, status: result.status, user: body.user || null, rateLimit: body.rate_limit ?? null }; + } + + return { status, setKey, get, testConnection }; +} + +module.exports = { createHouseOfRc, DEFAULT_BASE_URL }; diff --git a/src/app.js b/src/app.js index 2a2fdef..58990a2 100644 --- a/src/app.js +++ b/src/app.js @@ -2184,6 +2184,24 @@ const TRANSLATIONS = { "tts.download": "Hämta", "tts.downloading": "Hämtar...", "tts.test_failed": "Kunde inte spela upp den lokala rösten - kontrollera installationen.", + "houseofrc.title": "House of RC", + "houseofrc.hint": "Klubbens API-nyckel från House of RC. Den sparas bara på servern (data/houseofrc.json) och visas aldrig igen, inte ens här.", + "houseofrc.key": "API-nyckel", + "houseofrc.save": "Spara nyckel", + "houseofrc.test": "Testa anslutning", + "houseofrc.testing": "Testar…", + "houseofrc.remove": "Ta bort nyckel", + "houseofrc.remove_confirm": "Ta bort House of RC-nyckeln från servern?", + "houseofrc.state_none": "Ingen nyckel sparad.", + "houseofrc.state_saved": "Nyckel sparad på servern ({hint}).", + "houseofrc.state_env": "Nyckel från miljövariabeln HOUSEOFRC_API_KEY ({hint}).", + "houseofrc.connected": "✅ Ansluten som {name} (id {id}) · {limit} anrop/min", + "houseofrc.err_not_configured": "Ingen nyckel sparad.", + "houseofrc.err_unauthorized": "House of RC godkände inte nyckeln. Kontrollera att den är rätt kopierad.", + "houseofrc.err_rate_limited": "För många anrop. Vänta {seconds} s och försök igen.", + "houseofrc.err_unreachable": "Når inte House of RC. Har servern internet?", + "houseofrc.err_invalid_key": "Det ser inte ut som en API-nyckel.", + "houseofrc.err_other": "House of RC svarade med fel ({status}).", "auth.title": "Admin-PIN", "auth.hint": "Skyddar alla ändringar (race, resultat, inställningar, uppdatering) med en PIN. Läsning och publika overlay-/träningslänkar påverkas inte. Inloggningen sparas i webbläsaren i 30 dagar.", "auth.state_off": "Av - vem som helst på nätverket kan ändra.", @@ -4336,6 +4354,24 @@ const TRANSLATIONS = { "tts.download": "Download", "tts.downloading": "Downloading...", "tts.test_failed": "Could not play the local voice - check the installation.", + "houseofrc.title": "House of RC", + "houseofrc.hint": "The club's House of RC API key. It is stored on the server only (data/houseofrc.json) and never shown again, not even here.", + "houseofrc.key": "API key", + "houseofrc.save": "Save key", + "houseofrc.test": "Test connection", + "houseofrc.testing": "Testing…", + "houseofrc.remove": "Remove key", + "houseofrc.remove_confirm": "Remove the House of RC key from the server?", + "houseofrc.state_none": "No key saved.", + "houseofrc.state_saved": "Key saved on the server ({hint}).", + "houseofrc.state_env": "Key from the HOUSEOFRC_API_KEY environment variable ({hint}).", + "houseofrc.connected": "✅ Connected as {name} (id {id}) · {limit} requests/min", + "houseofrc.err_not_configured": "No key saved.", + "houseofrc.err_unauthorized": "House of RC rejected the key. Check that it was copied correctly.", + "houseofrc.err_rate_limited": "Too many requests. Wait {seconds} s and try again.", + "houseofrc.err_unreachable": "Can't reach House of RC. Does the server have internet?", + "houseofrc.err_invalid_key": "That doesn't look like an API key.", + "houseofrc.err_other": "House of RC answered with an error ({status}).", "auth.title": "Admin PIN", "auth.hint": "Protects every change (races, results, settings, updates) with a PIN. Reading and public overlay/training links are unaffected. The login is remembered in this browser for 30 days.", "auth.state_off": "Off - anyone on the network can make changes.", diff --git a/src/houseofrc_view.js b/src/houseofrc_view.js new file mode 100644 index 0000000..cdcfecc --- /dev/null +++ b/src/houseofrc_view.js @@ -0,0 +1,77 @@ +// Settings → System → House of RC: save the club's API key on the server and test it. +// The key is never read back; the server only tells whether one is set (and its last 4 chars). +async function postJson(path, body) { + try { + const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) }); + return { status: response.status, body: await response.json().catch(() => ({})) }; + } catch { + return { status: 0, body: { error: "unreachable" } }; + } +} + +export function describeHouseOfRcError(t, code, body = {}) { + if (code === 401 && body.error === "auth_required") return t("auth.login_required"); + const key = { + not_configured: "houseofrc.err_not_configured", + unauthorized: "houseofrc.err_unauthorized", + rate_limited: "houseofrc.err_rate_limited", + timeout: "houseofrc.err_unreachable", + unreachable: "houseofrc.err_unreachable", + invalid_key: "houseofrc.err_invalid_key", + }[body.error]; + return key ? t(key, { seconds: body.retryAfter || 60 }) : t("houseofrc.err_other", { status: body.status || code }); +} + +export async function mountHouseOfRcSettings(container, { t, escapeHtml }) { + if (!container) return; + const status = await fetch("/api/houseofrc/status").then((res) => res.json()).catch(() => null); + if (!status) { + container.innerHTML = `

${escapeHtml(t("houseofrc.err_unreachable"))}

`; + return; + } + const remount = () => mountHouseOfRcSettings(container, { t, escapeHtml }); + const stateText = !status.configured ? t("houseofrc.state_none") + : status.source === "env" ? t("houseofrc.state_env", { hint: status.keyHint }) + : t("houseofrc.state_saved", { hint: status.keyHint }); + container.innerHTML = ` +

${escapeHtml(stateText)}

+

${escapeHtml(t("houseofrc.hint"))}

+
+ +
+ + + ${status.source === "file" ? `` : ""} +
+
+ `; + const result = container.querySelector("#houseOfRcResult"); + const show = (text, isError = false) => { + result.textContent = text; + result.className = isError ? "error" : "hint"; + result.hidden = false; + }; + container.querySelector("#houseOfRcKeyForm").addEventListener("submit", async (event) => { + event.preventDefault(); + const apiKey = String(new FormData(event.currentTarget).get("apiKey") || "").trim(); + if (!apiKey) return; + const { status: code, body } = await postJson("/api/houseofrc/key", { apiKey }); + if (code !== 200) return show(describeHouseOfRcError(t, code, body), true); + await remount(); + container.querySelector("#houseOfRcTest")?.click(); + }); + container.querySelector("#houseOfRcTest")?.addEventListener("click", async () => { + show(t("houseofrc.testing")); + const { status: code, body } = await postJson("/api/houseofrc/test"); + if (code === 200 && body.ok) show(t("houseofrc.connected", { name: body.user?.name || "?", id: body.user?.id ?? "?", limit: body.rateLimit ?? "?" })); + else show(describeHouseOfRcError(t, code, body), true); + }); + container.querySelector("#houseOfRcRemove")?.addEventListener("click", async () => { + if (!window.confirm(t("houseofrc.remove_confirm"))) return; + const { status: code, body } = await postJson("/api/houseofrc/key", { apiKey: "" }); + if (code !== 200) return show(describeHouseOfRcError(t, code, body), true); + remount(); + }); +} diff --git a/src/settings.js b/src/settings.js index 4abcdd9..4911f01 100644 --- a/src/settings.js +++ b/src/settings.js @@ -1,6 +1,7 @@ import { normalizePublicBaseUrl } from "./public_url.js"; import { decoderDiagnosticsMarkup, mountDecoderDiagnostics } from "./decoder_diagnostics_view.js"; import { mountAuthSettings } from "./auth_view.js"; +import { mountHouseOfRcSettings } from "./houseofrc_view.js"; import { mountTtsSettings } from "./tts_settings_view.js"; import { mountDecoderSimSettings } from "./decoder_sim_view.js"; import { formatSpokenLapTime, formatShortLapCall } from "./race_audio.js"; @@ -464,6 +465,11 @@ export function renderSettings(deps) {
+
+

🏠 ${t("houseofrc.title")}

+
+
+

🎙 ${t("controller.title")}

@@ -632,6 +638,7 @@ Erik Eriksson;654321;4WD;Associated;; pendingSettingsFocusId = ""; } mountAuthSettings(document.getElementById("authSettings"), { t, escapeHtml }); + mountHouseOfRcSettings(document.getElementById("houseOfRcSettings"), { t, escapeHtml }); // Per computer, not in the shared settings: sent with the next heartbeat of the master lock. document.getElementById("controllerName")?.addEventListener("change", (event) => { try { localStorage.setItem("rc_controller_name", event.target.value.trim()); } catch { /* storage blocked */ } diff --git a/tests/server_persistence.integration.test.js b/tests/server_persistence.integration.test.js index ef527d4..5ea7454 100644 --- a/tests/server_persistence.integration.test.js +++ b/tests/server_persistence.integration.test.js @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; -import fs, { mkdtempSync, rmSync, readFileSync } from "node:fs"; +import fs, { mkdtempSync, rmSync, readFileSync, statSync, existsSync } from "node:fs"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -726,3 +726,58 @@ test("Race Controller Master: one browser holds the lock, take-over needs force rmSync(dataDir, { recursive: true, force: true }); } }); + +test("House of RC: the key is stored server-side only, never returned, and the test call uses it", { timeout: 20000 }, async () => { + const { createServer } = await import("node:http"); + const seen = []; + const mock = createServer((req, res) => { + seen.push({ url: req.url, auth: req.headers.authorization }); + const ok = req.headers.authorization === "Bearer hrc_test_secret_key_1234"; + res.writeHead(ok ? 200 : 401, { "Content-Type": "application/json" }); + res.end(JSON.stringify(ok ? { data: { user: { id: 68, name: "Test Club" }, rate_limit: 60 } } : { error: "unauthorized" })); + }); + await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve)); + const dataDir = mkdtempSync(join(tmpdir(), "live-rc-test-hor-")); + const port = await reservePort(); + const baseUrl = `http://127.0.0.1:${port}`; + const child = spawn(process.execPath, [join(projectRoot, "server.js")], { + cwd: projectRoot, + env: { ...process.env, HOST: "127.0.0.1", PORT: String(port), RC_TIMING_DATA_DIR: dataDir, RC_TIMING_PID_FILE: "", HOUSEOFRC_API_KEY: "", HOUSEOFRC_BASE_URL: `http://127.0.0.1:${mock.address().port}` }, + stdio: ["ignore", "pipe", "pipe"], + }); + const post = (path, body, cookie = "") => fetch(`${baseUrl}${path}`, { method: "POST", headers: { "Content-Type": "application/json", ...(cookie ? { Cookie: cookie } : {}) }, body: JSON.stringify(body) }); + const status = async () => (await fetch(`${baseUrl}/api/houseofrc/status`)).json(); + + try { + await waitForServer(child); + assert.equal((await status()).configured, false); + assert.equal((await (await post("/api/houseofrc/test", {})).json()).error, "not_configured"); + assert.equal((await post("/api/houseofrc/key", { apiKey: "short" })).status, 400, "rejects something that is not a key"); + + assert.equal((await post("/api/houseofrc/key", { apiKey: "hrc_wrong_key_000000" })).status, 200); + assert.equal((await (await post("/api/houseofrc/test", {})).json()).error, "unauthorized", "a rejected key is reported as such"); + + const saved = await (await post("/api/houseofrc/key", { apiKey: " hrc_test_secret_key_1234 " })).json(); + assert.deepEqual([saved.configured, saved.source, saved.keyHint], [true, "file", "…1234"]); + const test = await (await post("/api/houseofrc/test", {})).json(); + assert.deepEqual([test.ok, test.user.name, test.rateLimit], [true, "Test Club", 60]); + assert.equal(seen.at(-1).url, "/v1/me"); + + const keyFile = join(dataDir, "houseofrc.json"); + assert.equal(statSync(keyFile).mode & 0o777, 0o600, "only the server user can read the key file"); + for (const path of ["/api/houseofrc/status", "/api/state"]) { + assert.ok(!(await (await fetch(`${baseUrl}${path}`)).text()).includes("hrc_test_secret"), `${path} never returns the key`); + } + + const cookie = (await post("/api/auth/pin", { newPin: "4711" })).headers.get("set-cookie").split(";")[0]; + assert.equal((await post("/api/houseofrc/key", { apiKey: "" })).status, 401, "with a PIN, changing the key needs login"); + assert.equal((await post("/api/houseofrc/test", {})).status, 401, "and so does using it"); + assert.equal((await post("/api/houseofrc/key", { apiKey: "" }, cookie)).status, 200); + assert.equal((await status()).configured, false, "an empty key removes it"); + assert.equal(existsSync(keyFile), false); + } finally { + await stopServer(child); + mock.close(); + rmSync(dataDir, { recursive: true, force: true }); + } +});