From bfc0f2299153bad623adb64a646c93aa4f62bddf Mon Sep 17 00:00:00 2001 From: RELMYMathieu Date: Tue, 17 Nov 2026 17:53:12 +0100 Subject: [PATCH 1/4] feat: a served http api instead of our locked internal api --- .github/workflows/api.yml | 46 + CHANGELOG.md | 14 + CONTRIBUTING.md | 21 +- .../JustReadTheInstructions/Web/README.txt | 8 + .../JustReadTheInstructions/Web/js/api.js | 14 +- .../Web/js/camera-card.js | 4 +- .../JustReadTheInstructions/Web/js/config.js | 39 +- .../Web/js/control-key.js | 42 + .../Web/js/layout-tray.js | 2 +- .../JustReadTheInstructions/Web/js/main.js | 1 - .../JustReadTheInstructions/Web/js/session.js | 2 +- .../JustReadTheInstructions/Web/js/viewer.js | 2 +- README.md | 1 + Source/ApiAccess.cs | 66 + Source/ApiCatalog.cs | 344 +++++ Source/ApiRoute.cs | 95 ++ Source/ApiSchema.cs | 79 ++ Source/JRTISettings.cs | 7 + Source/JRTISettingsGUI.cs | 24 + Source/JRTIStreamServer.GameRecording.cs | 6 - Source/JRTIStreamServer.Http.cs | 160 +-- Source/JRTIStreamServer.Layouts.cs | 26 - Source/JRTIStreamServer.Program.cs | 22 - Source/JRTIStreamServer.Routes.cs | 199 +++ Source/JRTIStreamServer.cs | 23 +- Tests/JRTI.Tests/ApiAccessTests.cs | 66 + Tests/JRTI.Tests/ApiCatalogTests.cs | 71 + Tests/JRTI.Tests/ApiRouterTests.cs | 74 ++ Tests/JRTI.Tests/JRTI.Tests.csproj | 4 + Tools/check-routes.mjs | 74 ++ Tools/mock-server.mjs | 111 +- docs/api.md | 73 ++ docs/layouts-obs.md | 2 +- docs/openapi.json | 1160 +++++++++++++++++ docs/settings.md | 3 +- mkdocs.yml | 1 + 36 files changed, 2706 insertions(+), 180 deletions(-) create mode 100644 .github/workflows/api.yml create mode 100644 GameData/JustReadTheInstructions/Web/js/control-key.js create mode 100644 Source/ApiAccess.cs create mode 100644 Source/ApiCatalog.cs create mode 100644 Source/ApiRoute.cs create mode 100644 Source/ApiSchema.cs create mode 100644 Source/JRTIStreamServer.Routes.cs create mode 100644 Tests/JRTI.Tests/ApiAccessTests.cs create mode 100644 Tests/JRTI.Tests/ApiCatalogTests.cs create mode 100644 Tests/JRTI.Tests/ApiRouterTests.cs create mode 100644 Tools/check-routes.mjs create mode 100644 docs/api.md create mode 100644 docs/openapi.json diff --git a/.github/workflows/api.yml b/.github/workflows/api.yml new file mode 100644 index 0000000..e5dbe47 --- /dev/null +++ b/.github/workflows/api.yml @@ -0,0 +1,46 @@ +name: api + +on: + push: + branches: [main] + paths: + - Source/** + - Tests/** + - Tools/** + - docs/openapi.json + - .github/workflows/api.yml + pull_request: + paths: + - Source/** + - Tests/** + - Tools/** + - docs/openapi.json + - .github/workflows/api.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: api-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Unit tests, including the published OpenAPI document + run: dotnet test Tests/JRTI.Tests + + - name: Mock server answers every API route + run: node Tools/check-routes.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f6668a..8a17dc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 > **Versioning note:** versions use the four-part `MAJOR.MINOR.PATCH.BUILD` form that KSP/Unity DLLs expect. The first three parts follow SemVer; the fourth part (`BUILD`) is repurposed here to mark pre-release / beta iterations of an upcoming version. +## Unreleased + +### Added + +- Web API (`/api/v1`) - every web UI route is also served under `/api/v1`, and `/api/v1` lists them all with the mod version and features, so other apps and pages can build on the same feeds. The old addresses keep working +- OpenAPI document (`/api/v1/openapi.json`, docs site) - every route with its request and response fields, to generate clients in any language +- Control key (Settings, Stream / Capture) - optional: other devices can still watch, but need the key to change settings, record or switch layouts. Copy link opens the web UI on another device with the key remembered +- Your own pages (`PluginData/Apps/`) - a folder there opens at `/apps//`, served by the game and kept across updates +- Web UI changes that survive updates (`PluginData/Web/`) - a file there replaces the shipped one of the same path + +### Changed + +- Web pages from other websites can no longer change camera settings, recordings or layouts. Pages served from localhost (development servers) can use the API from the browser + ## v3.3.0 - 2026-11-11 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5506ebc..10ea05d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -74,7 +74,26 @@ The web files in `GameData/JustReadTheInstructions/Web/` are static and need no node Tools/mock-server.mjs ``` -It serves the Web folder on port 8099. Keep it in step when you add an endpoint. +It serves the Web folder on port 8099. Set `MOCK_KEY=ABCD234567` to make it require a control key, as if every request came from another device. + +## Adding or changing an endpoint + +Every route is described once in `Source/ApiCatalog.cs` (path, method, fields) and bound to its handler in `Source/JRTIStreamServer.Routes.cs`. After a change: + +1. Regenerate the published OpenAPI document and run the tests (in bash; in PowerShell set `$env:JRTI_UPDATE_OPENAPI=1` first): + + ```bash + cd Tests/JRTI.Tests + JRTI_UPDATE_OPENAPI=1 dotnet test + ``` + + Commit the updated `docs/openapi.json`. Without the variable, the tests fail when it is out of date. + +2. Add the route to `Tools/mock-server.mjs`, then check that the mock answers every route in the document: + + ```bash + node Tools/check-routes.mjs + ``` ## Working on the docs diff --git a/GameData/JustReadTheInstructions/Web/README.txt b/GameData/JustReadTheInstructions/Web/README.txt index 11b5085..c02b111 100644 --- a/GameData/JustReadTheInstructions/Web/README.txt +++ b/GameData/JustReadTheInstructions/Web/README.txt @@ -31,6 +31,14 @@ To go back to the default, just delete your customlos.png. Any *standard* image format works (PNG recommended, 1920x1080). +YOUR OWN PAGES AND CHANGES +-------------------------- + +Files in GameData/JustReadTheInstructions/PluginData/Web/ replace the ones +here and survive updates. Your own pages go in PluginData/Apps// and +open at http://localhost:8080/apps//. See the API page of the docs. + + RECORDINGS ---------- diff --git a/GameData/JustReadTheInstructions/Web/js/api.js b/GameData/JustReadTheInstructions/Web/js/api.js index ed1c6ed..a2ad4be 100644 --- a/GameData/JustReadTheInstructions/Web/js/api.js +++ b/GameData/JustReadTheInstructions/Web/js/api.js @@ -1,4 +1,7 @@ import { API } from './config.js'; +import { controlKeyHeaders, askForControlKey } from './control-key.js'; + +const UNAUTHORIZED = 401; async function getJson(url, what) { const res = await fetch(url, { cache: 'no-store' }); @@ -6,12 +9,17 @@ async function getJson(url, what) { return res.json(); } -async function send(url, method, body, what) { - const res = await fetch(url, { +function request(url, method, body) { + return fetch(url, { method, - headers: body == null ? undefined : { 'Content-Type': 'application/json' }, + headers: { ...controlKeyHeaders(), ...(body == null ? {} : { 'Content-Type': 'application/json' }) }, body: body == null ? undefined : JSON.stringify(body), }); +} + +async function send(url, method, body, what) { + let res = await request(url, method, body); + if (res.status === UNAUTHORIZED && await askForControlKey()) res = await request(url, method, body); if (!res.ok) throw new Error(`${what} failed: ${res.status} ${await res.text()}`); return res; } diff --git a/GameData/JustReadTheInstructions/Web/js/camera-card.js b/GameData/JustReadTheInstructions/Web/js/camera-card.js index d0620aa..c674f03 100644 --- a/GameData/JustReadTheInstructions/Web/js/camera-card.js +++ b/GameData/JustReadTheInstructions/Web/js/camera-card.js @@ -19,7 +19,7 @@ export class CameraCard { this.id = cam.id; this.name = cam.name; this.streamUrl = cam.streamUrl; - this.snapshotBaseUrl = cam.snapshotUrl; + this.snapshotBaseUrl = API.snapshot(cam.id); this.streaming = cam.streaming; this.groupItems = null; this.onRecordingChange = null; @@ -257,7 +257,7 @@ export class CameraCard { } _moreItems() { - const streamUrl = API.stream(this.id); + const streamUrl = API.obsStream(this.id); const lanItem = menuItem({ label: 'Copy network stream URL', description: 'The same video, at the address other devices on your network can open', diff --git a/GameData/JustReadTheInstructions/Web/js/config.js b/GameData/JustReadTheInstructions/Web/js/config.js index 8765a66..cf49895 100644 --- a/GameData/JustReadTheInstructions/Web/js/config.js +++ b/GameData/JustReadTheInstructions/Web/js/config.js @@ -34,26 +34,29 @@ export const TRACKS = Object.freeze([ { id: 'target', label: 'Target', hint: 'Follows your target and zooms with its distance.' }, ]); +const V1 = '/api/v1'; + export const API = Object.freeze({ - session: '/session', - cameras: '/cameras', - snapshot: (id) => `/camera/${id}/snapshot?t=${Date.now()}`, - stream: (id) => `/camera/${id}/stream`, - audio: (id) => `/camera/${id}/audio`, - streams: (ids, preview) => `/streams?ids=${ids.join(',')}${preview ? '&preview=1' : ''}`, - status: (id) => `/camera/${id}/status`, - settings: (id) => `/camera/${id}/settings`, - gameRecording: (id, action, codec) => `/camera/${id}/recording/${action}${codec ? `?codec=${codec}` : ''}`, + discovery: V1, + session: `${V1}/session`, + cameras: `${V1}/cameras`, + snapshot: (id) => `${V1}/camera/${id}/snapshot`, + obsStream: (id) => `/camera/${id}/stream`, + audio: (id) => `${V1}/camera/${id}/audio`, + streams: (ids, preview) => `${V1}/streams?ids=${ids.join(',')}${preview ? '&preview=1' : ''}`, + status: (id) => `${V1}/camera/${id}/status`, + settings: (id) => `${V1}/camera/${id}/settings`, + gameRecording: (id, action, codec) => `${V1}/camera/${id}/recording/${action}${codec ? `?codec=${codec}` : ''}`, viewer: (id) => `/viewer.html?id=${id}`, - debugStats: '/debug/stats', - events: '/events', - program: '/program', - programTake: (name) => `/program/take/${encodeURIComponent(name)}`, - programClear: '/program/clear', - layouts: '/layouts', - layout: (name) => `/layouts/${encodeURIComponent(name)}`, - recordings: '/recordings', - recording: (file, download) => `/recordings/${encodeURIComponent(file)}${download ? '?download=1' : ''}`, + debugStats: `${V1}/debug/stats`, + events: `${V1}/events`, + program: `${V1}/program`, + programTake: (name) => `${V1}/program/take/${encodeURIComponent(name)}`, + programClear: `${V1}/program/clear`, + layouts: `${V1}/layouts`, + layout: (name) => `${V1}/layouts/${encodeURIComponent(name)}`, + recordings: `${V1}/recordings`, + recording: (file, download) => `${V1}/recordings/${encodeURIComponent(file)}${download ? '?download=1' : ''}`, }); export const VIDEO_CODECS = Object.freeze({ diff --git a/GameData/JustReadTheInstructions/Web/js/control-key.js b/GameData/JustReadTheInstructions/Web/js/control-key.js new file mode 100644 index 0000000..316ed4b --- /dev/null +++ b/GameData/JustReadTheInstructions/Web/js/control-key.js @@ -0,0 +1,42 @@ +const STORAGE_KEY = 'jrti.controlKey'; +const URL_PARAM = 'key'; +const PROMPT_TEXT = "This needs the control key from the game's JRTI settings (Web streaming server). Enter it once and this browser keeps it."; + +let asking = null; +let declined = false; + +function read() { + try { return localStorage.getItem(STORAGE_KEY); } catch { return null; } +} + +function store(key) { + try { localStorage.setItem(STORAGE_KEY, key); } catch { } +} + +function adoptKeyFromUrl() { + const url = new URL(location.href); + const key = url.searchParams.get(URL_PARAM); + if (!key) return; + store(key.trim().toUpperCase()); + url.searchParams.delete(URL_PARAM); + history.replaceState(history.state, '', url); +} + +export function controlKeyHeaders() { + const key = read(); + return key ? { Authorization: `Bearer ${key}` } : {}; +} + +export function askForControlKey() { + if (declined) return Promise.resolve(false); + asking ??= Promise.resolve().then(() => { + const key = prompt(PROMPT_TEXT)?.trim(); + if (key) store(key.toUpperCase()); + else declined = true; + asking = null; + return Boolean(key); + }); + return asking; +} + +adoptKeyFromUrl(); diff --git a/GameData/JustReadTheInstructions/Web/js/layout-tray.js b/GameData/JustReadTheInstructions/Web/js/layout-tray.js index 87d95a4..893f323 100644 --- a/GameData/JustReadTheInstructions/Web/js/layout-tray.js +++ b/GameData/JustReadTheInstructions/Web/js/layout-tray.js @@ -71,6 +71,6 @@ export class CameraTray { } _loadThumbnails() { - for (const [id, item] of this._items) item.img.src = API.snapshot(id); + for (const [id, item] of this._items) item.img.src = `${API.snapshot(id)}?t=${Date.now()}`; } } diff --git a/GameData/JustReadTheInstructions/Web/js/main.js b/GameData/JustReadTheInstructions/Web/js/main.js index 11f68ab..a5b0074 100644 --- a/GameData/JustReadTheInstructions/Web/js/main.js +++ b/GameData/JustReadTheInstructions/Web/js/main.js @@ -99,7 +99,6 @@ function restoreKnownCameras() { id, name, streaming: false, - snapshotUrl: `/camera/${id}/snapshot`, streamUrl: `/viewer.html?id=${id}`, }); card.markDestroyed(); diff --git a/GameData/JustReadTheInstructions/Web/js/session.js b/GameData/JustReadTheInstructions/Web/js/session.js index 702c23f..f33dcb5 100644 --- a/GameData/JustReadTheInstructions/Web/js/session.js +++ b/GameData/JustReadTheInstructions/Web/js/session.js @@ -1,6 +1,6 @@ import { fetchSession } from './api.js'; -const EMPTY_SESSION = Object.freeze({ launchId: null, version: null, inGameRecording: false, codecs: [], lanUrls: [] }); +const EMPTY_SESSION = Object.freeze({ launchId: null, version: null, inGameRecording: false, codecs: [], lanUrls: [], controlKeyRequired: false }); let pending = null; diff --git a/GameData/JustReadTheInstructions/Web/js/viewer.js b/GameData/JustReadTheInstructions/Web/js/viewer.js index 7a946e5..0b998a4 100644 --- a/GameData/JustReadTheInstructions/Web/js/viewer.js +++ b/GameData/JustReadTheInstructions/Web/js/viewer.js @@ -170,7 +170,7 @@ function main() { wireIdleChrome(); - const streamUrl = location.origin + API.stream(cameraId); + const streamUrl = location.origin + API.obsStream(cameraId); document.getElementById('viewer-copy').addEventListener('click', () => copyWithToast(streamUrl, 'Stream URL')); const fullscreenBtn = document.getElementById('viewer-fullscreen'); fullscreenBtn.hidden = !document.fullscreenEnabled; diff --git a/README.md b/README.md index bedf6b1..261dc00 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ * Hear the game from each camera's position - [Sound](https://relmymathieu.github.io/JustReadTheInstructions/sound/) * Record camera feeds as MP4 inside the game - [Recording](https://relmymathieu.github.io/JustReadTheInstructions/recording/) * Raw MJPEG feed URLs for OBS or other tools, with stable camera IDs +* An HTTP API to build your own pages and apps on the same feeds - [API](https://relmymathieu.github.io/JustReadTheInstructions/api/) ## Install diff --git a/Source/ApiAccess.cs b/Source/ApiAccess.cs new file mode 100644 index 0000000..d124088 --- /dev/null +++ b/Source/ApiAccess.cs @@ -0,0 +1,66 @@ +using System; +using System.Security.Cryptography; + +namespace JustReadTheInstructions +{ + public static class ApiAccess + { + private const string KeyAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; + public const int KeyLength = 10; + public const string BearerPrefix = "Bearer "; + + public static string NewKey() + { + var bytes = new byte[KeyLength]; + using (var random = RandomNumberGenerator.Create()) + random.GetBytes(bytes); + var key = new char[KeyLength]; + for (int i = 0; i < KeyLength; i++) + key[i] = KeyAlphabet[bytes[i] % KeyAlphabet.Length]; + return new string(key); + } + + public static bool IsValidKey(string key) + { + if (key == null || key.Length != KeyLength) return false; + foreach (char c in key) + if (KeyAlphabet.IndexOf(c) < 0) return false; + return true; + } + + public static string ProvidedKey(string authorizationHeader, string keyQuery) + { + if (authorizationHeader != null && authorizationHeader.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase)) + return authorizationHeader.Substring(BearerPrefix.Length).Trim(); + return keyQuery?.Trim(); + } + + public static bool KeyMatches(string provided, string expected) + { + if (provided == null || expected == null) return false; + provided = provided.ToUpperInvariant(); + int difference = provided.Length ^ expected.Length; + for (int i = 0; i < expected.Length; i++) + difference |= (i < provided.Length ? provided[i] : 0) ^ expected[i]; + return difference == 0; + } + + public static bool IsLocalhostOrigin(string origin) + { + if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri)) return false; + return uri.IsLoopback || uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) + || uri.Host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + } + + public static bool IsSameOrigin(string origin, string requestHost) + => Uri.TryCreate(origin, UriKind.Absolute, out var uri) + && string.Equals(uri.Authority, requestHost, StringComparison.OrdinalIgnoreCase); + + public static bool IsBlockedCrossSite(string secFetchSite, string origin, string requestHost) + { + if (origin == null || IsSameOrigin(origin, requestHost) || IsLocalhostOrigin(origin)) + return secFetchSite == "cross-site" && origin == null; + return true; + } + } +} diff --git a/Source/ApiCatalog.cs b/Source/ApiCatalog.cs new file mode 100644 index 0000000..1ce5e00 --- /dev/null +++ b/Source/ApiCatalog.cs @@ -0,0 +1,344 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using static JustReadTheInstructions.ApiSchema; + +namespace JustReadTheInstructions +{ + public sealed class ApiResponse + { + public int Status { get; } + public string ContentType { get; } + public ApiSchema Schema { get; } + public string Description { get; } + + private ApiResponse(int status, string contentType, ApiSchema schema, string description) + { + Status = status; + ContentType = contentType; + Schema = schema; + Description = description; + } + + public static ApiResponse Json(ApiSchema schema, string description = "JSON") => new ApiResponse(200, "application/json", schema, description); + public static ApiResponse Binary(string contentType, string description) => new ApiResponse(200, contentType, null, description); + public static ApiResponse Empty(int status, string description) => new ApiResponse(status, null, null, description); + } + + public sealed class ApiParameter + { + public string Name { get; } + public ApiSchema Schema { get; } + public string Description { get; } + + public ApiParameter(string name, ApiSchema schema, string description) + { + Name = name; + Schema = schema; + Description = description; + } + } + + public sealed class ApiOperation + { + public string Id { get; } + public string Method { get; } + public string Template { get; } + public string Summary { get; } + public string[] AlsoAccepts { get; set; } = new string[0]; + public bool Writes { get; set; } + public bool VersionedOnly { get; set; } + public ApiParameter[] Path { get; set; } = new ApiParameter[0]; + public ApiParameter[] Query { get; set; } = new ApiParameter[0]; + public ApiSchema Body { get; set; } + public ApiResponse Response { get; set; } + + public ApiOperation(string id, string method, string template, string summary) + { + Id = id; + Method = method; + Template = template; + Summary = summary; + } + + public IEnumerable Methods => new[] { Method }.Concat(AlsoAccepts); + + public IEnumerable PathParameterNames + => ApiRouter.Segments(Template).Where(s => s.StartsWith("{", System.StringComparison.Ordinal)).Select(s => s.Trim('{', '}')); + } + + public static class ApiCatalog + { + public const string Title = "Just Read The Instructions"; + + private static readonly ApiSchema Mic = Enum("game", "external", "onboard"); + private static readonly ApiSchema Track = Enum("off", "vessel", "target"); + private static readonly ApiSchema Codec = Enum("h264", "av1"); + + private static readonly ApiParameter CameraId = new ApiParameter("id", Integer, "Camera ID, as listed by /cameras"); + private static readonly ApiParameter LayoutName = new ApiParameter("layout", String, "Layout name: letters, digits, spaces, - and _ (64 at most)"); + + public static readonly IReadOnlyDictionary Components = new SortedDictionary(System.StringComparer.Ordinal) + { + ["Discovery"] = Object( + new ApiField("name", String), + new ApiField("version", String), + new ApiField("api", Integer), + new ApiField("launchId", String), + new ApiField("features", Object( + new ApiField("inGameRecording", Boolean), + new ApiField("codecs", ArrayOf(Codec)), + new ApiField("controlKeyRequired", Boolean))), + new ApiField("routes", ArrayOf(Ref("Route")))), + ["Route"] = Object( + new ApiField("id", String), + new ApiField("methods", ArrayOf(String)), + new ApiField("path", String), + new ApiField("summary", String), + new ApiField("writes", Boolean)), + ["Session"] = Object( + new ApiField("launchId", String), + new ApiField("version", String), + new ApiField("inGameRecording", Boolean), + new ApiField("codecs", ArrayOf(Codec)), + new ApiField("lanUrls", ArrayOf(String)), + new ApiField("controlKeyRequired", Boolean)), + ["Camera"] = Object( + new ApiField("id", Integer), + new ApiField("name", String), + new ApiField("streaming", Boolean), + new ApiField("viewerCount", Integer), + new ApiField("snapshotUrl", String), + new ApiField("streamUrl", String), + new ApiField("mic", Mic), + new ApiField("canPan", Boolean), + new ApiField("track", Track), + new ApiField("recording", Nullable(Ref("Recording")))), + ["Recording"] = Object( + new ApiField("file", String), + new ApiField("paused", Boolean), + new ApiField("elapsedMs", Integer), + new ApiField("bytes", Integer), + new ApiField("framesWritten", Integer), + new ApiField("framesDropped", Integer), + new ApiField("error", Nullable(String))), + ["CameraSettings"] = Object( + new ApiField("brightness", Number), + new ApiField("contrast", Number), + new ApiField("gamma", Number), + new ApiField("mic", Mic), + new ApiField("soundGain", Number), + new ApiField("autoGain", Boolean), + new ApiField("mastering", Boolean), + new ApiField("fov", Number, required: false), + new ApiField("fovMin", Number, required: false), + new ApiField("fovMax", Number, required: false), + new ApiField("fovLimitMin", Number, required: false), + new ApiField("fovLimitMax", Number, required: false), + new ApiField("pan", Ref("Pan"), required: false)), + ["Pan"] = Object( + new ApiField("yaw", Number), + new ApiField("pitch", Number), + new ApiField("pitchMin", Number), + new ApiField("pitchMax", Number), + new ApiField("track", Track)), + ["CameraSettingsChange"] = Object(new[] + { + new ApiField("brightness", Number), + new ApiField("contrast", Number), + new ApiField("gamma", Number), + new ApiField("fov", Number), + new ApiField("mic", Mic), + new ApiField("soundGain", Number), + new ApiField("autoGain", Boolean), + new ApiField("mastering", Boolean), + new ApiField("zoomRate", Number), + new ApiField("panYaw", Number), + new ApiField("panPitch", Number), + new ApiField("panYawRate", Number), + new ApiField("panPitchRate", Number), + new ApiField("track", Track), + }.Optional().ToArray()), + ["Program"] = Object( + new ApiField("layout", Nullable(String)), + new ApiField("version", Integer)), + ["LayoutEntry"] = Object( + new ApiField("name", String), + new ApiField("updated", DateTime)), + ["RecordingFile"] = Object( + new ApiField("file", String), + new ApiField("bytes", Integer), + new ApiField("modified", DateTime), + new ApiField("recording", Boolean)), + }; + + public static readonly IReadOnlyList Operations = new[] + { + new ApiOperation("getApi", "GET", "/", "Mod version, features and every route") + { VersionedOnly = true, Response = ApiResponse.Json(Ref("Discovery")) }, + new ApiOperation("getOpenApi", "GET", "/openapi.json", "This API as an OpenAPI 3.1 document, to generate clients") + { VersionedOnly = true, Response = ApiResponse.Json(AnyObject) }, + new ApiOperation("getSession", "GET", "/session", "Game session: launch id, mod version, recording support, codecs, network addresses") + { Response = ApiResponse.Json(Ref("Session")) }, + new ApiOperation("listCameras", "GET", "/cameras", "Cameras with their name, viewers, mic, pan and recording state") + { Response = ApiResponse.Json(ArrayOf(Ref("Camera"))) }, + new ApiOperation("getStreams", "GET", "/streams", "Several cameras in one multipart stream; each part names its camera in an X-Camera-Id header") + { + Query = new[] + { + new ApiParameter("ids", String, "Camera IDs separated by commas, such as 10,11"), + new ApiParameter("preview", Enum("1"), "1 for preview-size frames"), + }, + Response = ApiResponse.Binary("multipart/x-mixed-replace", "JPEG frames"), + }, + new ApiOperation("getEvents", "GET", "/events", "Server-Sent Events: program (the layout on air) and layout (a saved layout changed)") + { Response = ApiResponse.Binary("text/event-stream", "Events, with a ping comment every 15 seconds") }, + new ApiOperation("getDebugStats", "GET", "/debug/stats", "Latest performance sample") + { Response = ApiResponse.Json(AnyObject) }, + new ApiOperation("getProgram", "GET", "/program", "The layout on air") + { Response = ApiResponse.Json(Ref("Program")) }, + new ApiOperation("takeProgram", "POST", "/program/take/{layout}", "Puts a saved layout on air. Also answers GET, for Stream Deck and browser links") + { AlsoAccepts = new[] { "GET" }, Writes = true, Path = new[] { LayoutName }, Response = ApiResponse.Json(Ref("Program")) }, + new ApiOperation("clearProgram", "POST", "/program/clear", "Takes the program off air. Also answers GET, for links") + { AlsoAccepts = new[] { "GET" }, Writes = true, Response = ApiResponse.Json(Ref("Program")) }, + new ApiOperation("listLayouts", "GET", "/layouts", "Saved layouts") + { Response = ApiResponse.Json(ArrayOf(Ref("LayoutEntry"))) }, + new ApiOperation("getLayout", "GET", "/layouts/{layout}", "One saved layout, as saved by the layout page") + { Path = new[] { LayoutName }, Response = ApiResponse.Json(AnyObject) }, + new ApiOperation("saveLayout", "PUT", "/layouts/{layout}", "Saves a layout: a JSON object of 64 KB at most. Also answers POST") + { AlsoAccepts = new[] { "POST" }, Writes = true, Path = new[] { LayoutName }, Body = AnyObject, Response = ApiResponse.Empty(204, "Saved") }, + new ApiOperation("deleteLayout", "DELETE", "/layouts/{layout}", "Deletes a layout") + { Writes = true, Path = new[] { LayoutName }, Response = ApiResponse.Empty(204, "Deleted") }, + new ApiOperation("listRecordings", "GET", "/recordings", "Recordings on disk, newest first") + { Response = ApiResponse.Json(ArrayOf(Ref("RecordingFile"))) }, + new ApiOperation("getRecording", "GET", "/recordings/{file}", "One recording, with byte ranges for seeking") + { + Path = new[] { new ApiParameter("file", String, "File name, as listed by /recordings") }, + Query = new[] { new ApiParameter("download", Enum("1"), "1 to save it instead of playing it") }, + Response = ApiResponse.Binary("video/mp4", "The video file"), + }, + new ApiOperation("getSnapshot", "GET", "/camera/{id}/snapshot", "Latest frame") + { Path = new[] { CameraId }, Response = ApiResponse.Binary("image/jpeg", "JPEG image") }, + new ApiOperation("getStream", "GET", "/camera/{id}/stream", "MJPEG stream at render size, for OBS, VLC or an img tag") + { Path = new[] { CameraId }, Response = ApiResponse.Binary("multipart/x-mixed-replace", "JPEG frames") }, + new ApiOperation("getPreview", "GET", "/camera/{id}/preview", "MJPEG stream at preview size") + { Path = new[] { CameraId }, Response = ApiResponse.Binary("multipart/x-mixed-replace", "JPEG frames") }, + new ApiOperation("getAudio", "GET", "/camera/{id}/audio", "Camera sound as an endless WAV stream") + { Path = new[] { CameraId }, Response = ApiResponse.Binary("audio/wav", "PCM audio") }, + new ApiOperation("getCameraStatus", "GET", "/camera/{id}/status", "Answers ok while the camera exists") + { Path = new[] { CameraId }, Response = ApiResponse.Binary("text/plain", "ok") }, + new ApiOperation("getCameraSettings", "GET", "/camera/{id}/settings", "Image, sound, field of view and pan settings") + { Path = new[] { CameraId }, Response = ApiResponse.Json(Ref("CameraSettings")) }, + new ApiOperation("changeCameraSettings", "POST", "/camera/{id}/settings", "Changes any of the listed fields and leaves the others alone") + { Writes = true, Path = new[] { CameraId }, Body = Ref("CameraSettingsChange"), Response = ApiResponse.Empty(200, "Changed") }, + new ApiOperation("controlRecording", "POST", "/camera/{id}/recording/{action}", "Starts, stops, discards, pauses or resumes the in-game recording") + { + Writes = true, + Path = new[] { CameraId, new ApiParameter("action", Enum("start", "stop", "discard", "pause", "resume"), "What to do") }, + Query = new[] { new ApiParameter("codec", Codec, "Codec for start, h264 by default") }, + Response = ApiResponse.Json(Nullable(Ref("Recording")), "The recording, or null once stopped"), + }, + }; + + public static ApiOperation Find(string id) => Operations.First(op => op.Id == id); + } + + public static class OpenApiDocument + { + public static string Build(IEnumerable operations, IReadOnlyDictionary components) + { + var paths = operations + .GroupBy(op => op.Template) + .Select(group => $"{Quote(group.Key)}:{{{string.Join(",", group.Select(OperationJson))}}}"); + + var schemas = components.Select(kv => $"{Quote(kv.Key)}:{kv.Value}"); + + var json = new StringBuilder("{"); + json.Append("\"openapi\":\"3.1.0\","); + json.Append($"\"info\":{{\"title\":{Quote(ApiCatalog.Title)},\"version\":\"{ApiRouter.Version}\"}},"); + json.Append($"\"servers\":[{{\"url\":{Quote(ApiRouter.VersionPrefix)}}}],"); + json.Append($"\"paths\":{{{string.Join(",", paths)}}},"); + json.Append("\"components\":{"); + json.Append($"\"schemas\":{{{string.Join(",", schemas)}}},"); + json.Append("\"securitySchemes\":{\"controlKey\":{\"type\":\"http\",\"scheme\":\"bearer\",\"description\":\"Only when the player turns on Require a key. The key can also go in a key query parameter\"}}"); + json.Append("}}"); + return Json.Pretty(json.ToString()); + } + + private static string OperationJson(ApiOperation op) + { + var parameters = op.Path.Select(p => ParameterJson(p, "path", true)) + .Concat(op.Query.Select(p => ParameterJson(p, "query", false))) + .ToList(); + + var json = new StringBuilder($"{Quote(op.Method.ToLowerInvariant())}:{{"); + json.Append($"\"operationId\":{Quote(op.Id)},\"summary\":{Quote(op.Summary)}"); + if (parameters.Count > 0) json.Append($",\"parameters\":[{string.Join(",", parameters)}]"); + if (op.Body != null) json.Append($",\"requestBody\":{{\"required\":true,\"content\":{{\"application/json\":{{\"schema\":{op.Body}}}}}}}"); + json.Append($",\"responses\":{{{ResponseJson(op.Response)}"); + if (op.Writes) + json.Append(",\"401\":{\"description\":\"The control key is required and missing or wrong\"},\"403\":{\"description\":\"Sent by a web page from another site\"}"); + json.Append('}'); + if (op.Writes) json.Append(",\"security\":[{},{\"controlKey\":[]}]"); + return json.Append('}').ToString(); + } + + private static string ParameterJson(ApiParameter parameter, string location, bool required) + => $"{{\"name\":{Quote(parameter.Name)},\"in\":\"{location}\",\"required\":{(required ? "true" : "false")}," + + $"\"description\":{Quote(parameter.Description)},\"schema\":{parameter.Schema}}}"; + + private static string ResponseJson(ApiResponse response) + { + var json = new StringBuilder($"\"{response.Status}\":{{\"description\":{Quote(response.Description)}"); + if (response.ContentType != null) + { + json.Append($",\"content\":{{{Quote(response.ContentType)}:{{"); + if (response.Schema != null) json.Append($"\"schema\":{response.Schema}"); + json.Append("}}"); + } + return json.Append('}').ToString(); + } + } + + public static class Json + { + public static string Pretty(string json) + { + var output = new StringBuilder(); + int depth = 0; + bool inString = false; + for (int i = 0; i < json.Length; i++) + { + char c = json[i]; + if (inString) + { + output.Append(c); + if (c == '\\') output.Append(json[++i]); + else if (c == '"') inString = false; + continue; + } + switch (c) + { + case '"': inString = true; output.Append(c); break; + case '{': + case '[': + output.Append(c); + if (IsEmptyContainer(json, i)) { output.Append(json[++i]); break; } + NewLine(output, ++depth); + break; + case '}': + case ']': NewLine(output, --depth); output.Append(c); break; + case ',': output.Append(c); NewLine(output, depth); break; + case ':': output.Append(": "); break; + default: output.Append(c); break; + } + } + return output.Append('\n').ToString(); + } + + private static bool IsEmptyContainer(string json, int i) + => i + 1 < json.Length && (json[i + 1] == '}' || json[i + 1] == ']'); + + private static void NewLine(StringBuilder output, int depth) => output.Append('\n').Append(' ', depth * 2); + } +} diff --git a/Source/ApiRoute.cs b/Source/ApiRoute.cs new file mode 100644 index 0000000..1cd1992 --- /dev/null +++ b/Source/ApiRoute.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; + +namespace JustReadTheInstructions +{ + public sealed class RouteValues + { + private readonly Dictionary _values = new Dictionary(StringComparer.Ordinal); + + internal void Set(string name, string value) => _values[name] = value; + + public string this[string name] => _values.TryGetValue(name, out var value) ? value : null; + } + + public sealed class ApiRoute + { + private readonly string[] _segments; + + public ApiOperation Operation { get; } + public IReadOnlyList Methods { get; } + public Action Handler { get; } + + public ApiRoute(ApiOperation operation, Action handler) + { + Operation = operation; + Methods = operation.Methods.ToArray(); + Handler = handler; + _segments = ApiRouter.Segments(operation.Template); + } + + public bool Allows(string method) + => Methods.Contains(method) || (method == "HEAD" && Methods.Contains("GET")); + + public RouteValues Match(string[] path) + { + if (path.Length != _segments.Length) return null; + var values = new RouteValues(); + for (int i = 0; i < path.Length; i++) + { + var segment = _segments[i]; + if (IsParameter(segment)) values.Set(segment.Substring(1, segment.Length - 2), path[i]); + else if (!string.Equals(segment, path[i], StringComparison.Ordinal)) return null; + } + return values; + } + + private static bool IsParameter(string segment) + => segment.Length > 2 && segment[0] == '{' && segment[segment.Length - 1] == '}'; + } + + public static class ApiRouter + { + public const int Version = 1; + public const string VersionPrefix = "/api/v1"; + + public enum Outcome { Matched, WrongMethod, NotFound } + + public static string[] Segments(string path) + => path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + + public static bool TryStripVersion(string path, out string rest) + { + if (path == VersionPrefix) rest = "/"; + else rest = path.StartsWith(VersionPrefix + "/", StringComparison.Ordinal) ? path.Substring(VersionPrefix.Length) : null; + return rest != null; + } + + public static Outcome Resolve(IEnumerable routes, string method, string path, + out ApiRoute route, out RouteValues values, out IReadOnlyList allowed) + { + var segments = Segments(path); + var allowedMethods = new List(); + route = null; + values = null; + allowed = allowedMethods; + + foreach (var candidate in routes) + { + var match = candidate.Match(segments); + if (match == null) continue; + if (candidate.Allows(method)) + { + route = candidate; + values = match; + return Outcome.Matched; + } + allowedMethods.AddRange(candidate.Methods.Where(m => !allowedMethods.Contains(m))); + } + + return allowedMethods.Count > 0 ? Outcome.WrongMethod : Outcome.NotFound; + } + } +} diff --git a/Source/ApiSchema.cs b/Source/ApiSchema.cs new file mode 100644 index 0000000..6805aa7 --- /dev/null +++ b/Source/ApiSchema.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace JustReadTheInstructions +{ + public sealed class ApiField + { + public string Name { get; } + public ApiSchema Schema { get; } + public bool Required { get; } + + public ApiField(string name, ApiSchema schema, bool required = true) + { + Name = name; + Schema = schema; + Required = required; + } + } + + public sealed class ApiSchema + { + private readonly string _json; + + private ApiSchema(string json) => _json = json; + + public static readonly ApiSchema String = new ApiSchema("{\"type\":\"string\"}"); + public static readonly ApiSchema Integer = new ApiSchema("{\"type\":\"integer\"}"); + public static readonly ApiSchema Number = new ApiSchema("{\"type\":\"number\"}"); + public static readonly ApiSchema Boolean = new ApiSchema("{\"type\":\"boolean\"}"); + public static readonly ApiSchema DateTime = new ApiSchema("{\"type\":\"string\",\"format\":\"date-time\"}"); + public static readonly ApiSchema AnyObject = new ApiSchema("{\"type\":\"object\",\"additionalProperties\":true}"); + + public static ApiSchema Ref(string component) => new ApiSchema($"{{\"$ref\":\"#/components/schemas/{component}\"}}"); + + public static ApiSchema ArrayOf(ApiSchema items) => new ApiSchema($"{{\"type\":\"array\",\"items\":{items._json}}}"); + + public static ApiSchema Nullable(ApiSchema schema) => new ApiSchema($"{{\"oneOf\":[{schema._json},{{\"type\":\"null\"}}]}}"); + + public static ApiSchema Enum(params string[] values) + => new ApiSchema($"{{\"type\":\"string\",\"enum\":[{string.Join(",", values.Select(Quote))}]}}"); + + public static ApiSchema Object(params ApiField[] fields) + { + var properties = string.Join(",", fields.Select(f => $"{Quote(f.Name)}:{f.Schema._json}")); + var required = fields.Where(f => f.Required).Select(f => Quote(f.Name)).ToList(); + var json = new StringBuilder("{\"type\":\"object\",\"properties\":{").Append(properties).Append('}'); + if (required.Count > 0) json.Append(",\"required\":[").Append(string.Join(",", required)).Append(']'); + return new ApiSchema(json.Append('}').ToString()); + } + + public static string Quote(string text) + { + var json = new StringBuilder("\""); + foreach (char c in text) + { + switch (c) + { + case '"': json.Append("\\\""); break; + case '\\': json.Append("\\\\"); break; + case '\n': json.Append("\\n"); break; + default: + if (c < 0x20) json.Append($"\\u{(int)c:x4}"); + else json.Append(c); + break; + } + } + return json.Append('"').ToString(); + } + + public override string ToString() => _json; + } + + public static class ApiSchemaExtensions + { + public static IEnumerable Optional(this IEnumerable fields) + => fields.Select(f => new ApiField(f.Name, f.Schema, required: false)); + } +} diff --git a/Source/JRTISettings.cs b/Source/JRTISettings.cs index 83c670d..7d47c6e 100644 --- a/Source/JRTISettings.cs +++ b/Source/JRTISettings.cs @@ -37,6 +37,8 @@ public class JRTISettings : MonoBehaviour public static int StreamMaxFps { get; internal set; } = 30; public static bool SpreadCaptures { get; internal set; } = true; public static bool AutoStreamCameras { get; internal set; } = false; + public static bool RequireControlKey { get; internal set; } = false; + public static string ControlKey { get; internal set; } = ""; public static float FramePeriod => 1f / Mathf.Max(1, StreamMaxFps); @@ -77,6 +79,7 @@ private static void Sanitize() StreamPort = Mathf.Clamp(StreamPort, 1024, 65535); StreamJpegQuality = Mathf.Clamp(StreamJpegQuality, 1, 100); StreamMaxFps = Mathf.Clamp(StreamMaxFps, 1, 120); + if (RequireControlKey && !ApiAccess.IsValidKey(ControlKey)) ControlKey = ApiAccess.NewKey(); } void Awake() @@ -121,6 +124,8 @@ private static void LoadConfig() StreamMaxFps = ParseInt(settings, "StreamMaxFps", StreamMaxFps); SpreadCaptures = ParseBool(settings, "SpreadCaptures", SpreadCaptures); AutoStreamCameras = ParseBool(settings, "AutoStreamCameras", AutoStreamCameras); + RequireControlKey = ParseBool(settings, "RequireControlKey", RequireControlKey); + ControlKey = settings.GetValue("ControlKey") ?? ControlKey; EnableDeferred = ParseBool(settings, "EnableDeferred", EnableDeferred); EnableTUFX = ParseBool(settings, "EnableTUFX", EnableTUFX); @@ -185,6 +190,8 @@ public static bool Save() settings.AddValue("StreamMaxFps", StreamMaxFps); settings.AddValue("SpreadCaptures", SpreadCaptures); settings.AddValue("AutoStreamCameras", AutoStreamCameras); + settings.AddValue("RequireControlKey", RequireControlKey); + settings.AddValue("ControlKey", ControlKey); settings.AddValue("EnableDeferred", EnableDeferred); settings.AddValue("EnableTUFX", EnableTUFX); diff --git a/Source/JRTISettingsGUI.cs b/Source/JRTISettingsGUI.cs index 173f4f3..5c6a701 100644 --- a/Source/JRTISettingsGUI.cs +++ b/Source/JRTISettingsGUI.cs @@ -26,6 +26,7 @@ public class JRTISettingsGUI : MonoBehaviour private string _renderHeight; private string _antiAliasing; private bool _spreadCaptures; + private bool _requireControlKey; private bool _enableStreamServer; private string _streamPort; @@ -258,6 +259,8 @@ private void DrawStreamSection() if (portWarning != null) GUILayout.Label("⚠ " + portWarning, _warningStyle); GUILayout.Space(2); + DrawControlKey(); + GUILayout.Space(6); DrawField("JPEG Quality (1-100)", ref _jpegQuality, "f_quality"); GUILayout.Space(2); DrawField("Max FPS (camera windows and streams)", ref _maxFps, "f_fps"); @@ -467,6 +470,25 @@ private void DrawIntegrationToggle(string name, bool enabled, System.Action 3 ? parts[3] : ""); break; - default: ServeError(ctx, 404, "Unknown action"); break; - } - } - private static void ServeSnapshot(HttpListenerContext ctx, CameraStreamState state) { state.MarkSnapshotInterest(); @@ -258,37 +265,36 @@ private static void ServeDebugStats(HttpListenerContext ctx) ServeText(ctx, PerfFormat.ToJson(snapshot), "application/json"); } - private static void ServeOrUpdateSettings(HttpListenerContext ctx, int cameraId, CameraStreamState state) + private static void UpdateCameraSettings(HttpListenerContext ctx, CameraStreamState state) { - if (ctx.Request.HttpMethod == "POST") - { - string body; - using (var reader = new System.IO.StreamReader(ctx.Request.InputStream, Encoding.UTF8)) - body = reader.ReadToEnd(); - - if (TryParseJsonFloat(body, "brightness", out var b)) - state.Brightness = UnityEngine.Mathf.Clamp(b, -1f, 1f); - if (TryParseJsonFloat(body, "contrast", out var c)) - state.Contrast = UnityEngine.Mathf.Clamp(c, 0f, 3f); - if (TryParseJsonFloat(body, "gamma", out var g)) - state.Gamma = UnityEngine.Mathf.Clamp(g, 0.1f, 5f); - if (TryParseJsonFloat(body, "fov", out var fov)) - state.SetPendingFov(fov); - if (TryParseJsonString(body, "mic", out var mic) && CameraMics.TryParse(mic, out var parsedMic)) - state.Mic = parsedMic; - if (TryParseJsonFloat(body, "soundGain", out var soundGain)) - state.SoundGainDb = UnityEngine.Mathf.Clamp(soundGain, -24f, 24f); - if (TryParseJsonBool(body, "autoGain", out var autoGain)) - state.AutoGain = autoGain; - if (TryParseJsonBool(body, "mastering", out var mastering)) - state.Mastering = mastering; - UpdateAim(body, state.Aim); - - ctx.Response.StatusCode = 200; - ctx.Response.Close(); - return; - } + string body; + using (var reader = new System.IO.StreamReader(ctx.Request.InputStream, Encoding.UTF8)) + body = reader.ReadToEnd(); + + if (TryParseJsonFloat(body, "brightness", out var b)) + state.Brightness = UnityEngine.Mathf.Clamp(b, -1f, 1f); + if (TryParseJsonFloat(body, "contrast", out var c)) + state.Contrast = UnityEngine.Mathf.Clamp(c, 0f, 3f); + if (TryParseJsonFloat(body, "gamma", out var g)) + state.Gamma = UnityEngine.Mathf.Clamp(g, 0.1f, 5f); + if (TryParseJsonFloat(body, "fov", out var fov)) + state.SetPendingFov(fov); + if (TryParseJsonString(body, "mic", out var mic) && CameraMics.TryParse(mic, out var parsedMic)) + state.Mic = parsedMic; + if (TryParseJsonFloat(body, "soundGain", out var soundGain)) + state.SoundGainDb = UnityEngine.Mathf.Clamp(soundGain, -24f, 24f); + if (TryParseJsonBool(body, "autoGain", out var autoGain)) + state.AutoGain = autoGain; + if (TryParseJsonBool(body, "mastering", out var mastering)) + state.Mastering = mastering; + UpdateAim(body, state.Aim); + + ctx.Response.StatusCode = 200; + ctx.Response.Close(); + } + private static void ServeCameraSettings(HttpListenerContext ctx, CameraStreamState state) + { var ic = System.Globalization.CultureInfo.InvariantCulture; var sb = new StringBuilder("{"); sb.Append($"\"brightness\":{state.Brightness.ToString("F2", ic)},"); diff --git a/Source/JRTIStreamServer.Layouts.cs b/Source/JRTIStreamServer.Layouts.cs index 23e60ce..24ec456 100644 --- a/Source/JRTIStreamServer.Layouts.cs +++ b/Source/JRTIStreamServer.Layouts.cs @@ -27,32 +27,6 @@ private static bool LayoutExists(string name) private static string LayoutEventJson(string name) => $"{{\"name\":\"{EscapeJson(name)}\"}}"; - private void HandleLayouts(HttpListenerContext ctx, string path) - { - var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 1) - { - ServeLayoutList(ctx); - return; - } - - var name = parts.Length == 2 ? Uri.UnescapeDataString(parts[1]).Trim() : ""; - if (!LayoutNamePattern.IsMatch(name)) - { - ServeError(ctx, 400, "Layout names use letters, digits, spaces, - and _ (64 at most)"); - return; - } - - switch (ctx.Request.HttpMethod) - { - case "GET": ServeLayout(ctx, name); break; - case "PUT": - case "POST": SaveLayout(ctx, name); break; - case "DELETE": DeleteLayout(ctx, name); break; - default: ServeError(ctx, 405, "Use GET, PUT or DELETE"); break; - } - } - private static void ServeLayoutList(HttpListenerContext ctx) { var entries = new List(); diff --git a/Source/JRTIStreamServer.Program.cs b/Source/JRTIStreamServer.Program.cs index 5704051..fb5e606 100644 --- a/Source/JRTIStreamServer.Program.cs +++ b/Source/JRTIStreamServer.Program.cs @@ -65,28 +65,6 @@ private void SetProgramLayout(string name) BroadcastEvent("program", ProgramJson()); } - private void HandleProgram(HttpListenerContext ctx, string path) - { - var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 1 && ctx.Request.HttpMethod == "GET") - { - ServeText(ctx, ProgramJson(), "application/json"); - return; - } - if (parts.Length == 2 && parts[1] == "clear") - { - SetProgramLayout(null); - ServeText(ctx, ProgramJson(), "application/json"); - return; - } - if (parts.Length == 3 && parts[1] == "take") - { - TakeProgram(ctx, Uri.UnescapeDataString(parts[2]).Trim()); - return; - } - ServeError(ctx, 404, "Use GET /program, /program/take/ or /program/clear"); - } - private void TakeProgram(HttpListenerContext ctx, string name) { if (!LayoutNamePattern.IsMatch(name) || !LayoutExists(name)) diff --git a/Source/JRTIStreamServer.Routes.cs b/Source/JRTIStreamServer.Routes.cs new file mode 100644 index 0000000..f8df1dd --- /dev/null +++ b/Source/JRTIStreamServer.Routes.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using UnityEngine; + +namespace JustReadTheInstructions +{ + public partial class JRTIStreamServer + { + private const string ControlKeyQuery = "key"; + private const int PreflightMaxAgeSeconds = 600; + + private ApiRoute[] _apiRoutes; + private ApiRoute[] _pageRoutes; + private string _openApiJson; + + private IReadOnlyList ApiRoutes => _apiRoutes ?? (_apiRoutes = BuildApiRoutes()); + private IEnumerable UnversionedApiRoutes => ApiRoutes.Where(route => !route.Operation.VersionedOnly); + private IReadOnlyList PageRoutes => _pageRoutes ?? (_pageRoutes = BuildPageRoutes()); + private string OpenApiJson => _openApiJson ?? (_openApiJson = OpenApiDocument.Build(ApiCatalog.Operations, ApiCatalog.Components)); + + private Dictionary> ApiHandlers() => new Dictionary> + { + ["getApi"] = (ctx, _) => ServeApiDiscovery(ctx), + ["getOpenApi"] = (ctx, _) => ServeText(ctx, OpenApiJson, "application/json"), + ["getSession"] = (ctx, _) => ServeSession(ctx), + ["listCameras"] = (ctx, _) => ServeCameraList(ctx), + ["getStreams"] = (ctx, _) => ServeMultiStream(ctx), + ["getEvents"] = (ctx, _) => ServeEvents(ctx), + ["getDebugStats"] = (ctx, _) => ServeDebugStats(ctx), + ["getProgram"] = (ctx, _) => ServeText(ctx, ProgramJson(), "application/json"), + ["takeProgram"] = (ctx, v) => TakeProgram(ctx, LayoutName(v)), + ["clearProgram"] = (ctx, _) => { SetProgramLayout(null); ServeText(ctx, ProgramJson(), "application/json"); }, + ["listLayouts"] = (ctx, _) => ServeLayoutList(ctx), + ["getLayout"] = ForLayout(ServeLayout), + ["saveLayout"] = ForLayout(SaveLayout), + ["deleteLayout"] = ForLayout(DeleteLayout), + ["listRecordings"] = (ctx, _) => ServeRecordingList(ctx), + ["getRecording"] = (ctx, v) => ServeRecordingFile(ctx, v["file"]), + ["getSnapshot"] = ForCamera((ctx, id, state, _) => ServeSnapshot(ctx, state)), + ["getStream"] = ForCamera((ctx, id, state, _) => ServeMjpeg(ctx, state)), + ["getPreview"] = ForCamera((ctx, id, state, _) => ServePreviewMjpeg(ctx, state)), + ["getAudio"] = ForCamera((ctx, id, state, _) => ServeCameraAudio(ctx, id, state)), + ["getCameraStatus"] = ForCamera((ctx, id, state, _) => ServeText(ctx, "ok", "text/plain")), + ["getCameraSettings"] = ForCamera((ctx, id, state, _) => ServeCameraSettings(ctx, state)), + ["changeCameraSettings"] = ForCamera((ctx, id, state, _) => UpdateCameraSettings(ctx, state)), + ["controlRecording"] = ForCamera((ctx, id, state, v) => HandleGameRecording(ctx, id, state, v["action"])), + }; + + private ApiRoute[] BuildApiRoutes() + { + var handlers = ApiHandlers(); + foreach (var missing in ApiCatalog.Operations.Where(op => !handlers.ContainsKey(op.Id))) + Debug.LogError($"[JRTI-Stream]: API route {missing.Id} has no handler"); + return ApiCatalog.Operations + .Where(op => handlers.ContainsKey(op.Id)) + .Select(op => new ApiRoute(op, handlers[op.Id])) + .ToArray(); + } + + private ApiRoute[] BuildPageRoutes() => new[] + { + new ApiRoute(new ApiOperation("mainPage", "GET", "/", "Main page"), (ctx, _) => ServeWebFile(ctx, "index.html")), + new ApiRoute(new ApiOperation("mainPageFile", "GET", "/index.html", "Main page"), (ctx, _) => ServeWebFile(ctx, "index.html")), + new ApiRoute(new ApiOperation("cameraPage", "GET", "/camera/{id}", "Opens the viewer page"), (ctx, v) => RedirectToViewer(ctx, v["id"])), + }; + + private bool TryServeRoute(HttpListenerContext ctx, IEnumerable routes, string path) + { + var request = ctx.Request; + var origin = request.Headers["Origin"]; + bool corsAllowed = origin != null && ApiAccess.IsLocalhostOrigin(origin) && !ApiAccess.IsSameOrigin(origin, request.UserHostName); + + var outcome = ApiRouter.Resolve(routes, request.HttpMethod, path, out var route, out var values, out var allowed); + if (outcome == ApiRouter.Outcome.NotFound) return false; + + if (corsAllowed) + { + ctx.Response.Headers.Add("Access-Control-Allow-Origin", origin); + ctx.Response.Headers.Add("Vary", "Origin"); + } + + if (outcome == ApiRouter.Outcome.WrongMethod) + { + if (request.HttpMethod == "OPTIONS" && corsAllowed) ServePreflight(ctx, allowed); + else + { + ctx.Response.Headers.Add("Allow", string.Join(", ", allowed)); + ServeError(ctx, 405, $"Use {string.Join(" or ", allowed)}"); + } + return true; + } + + if (route.Operation.Writes && !MayWrite(ctx)) return true; + route.Handler(ctx, values); + return true; + } + + private static void ServePreflight(HttpListenerContext ctx, IReadOnlyList allowed) + { + ctx.Response.Headers.Add("Access-Control-Allow-Methods", string.Join(", ", allowed)); + ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Authorization, Content-Type"); + ctx.Response.Headers.Add("Access-Control-Allow-Private-Network", "true"); + ctx.Response.Headers.Add("Access-Control-Max-Age", PreflightMaxAgeSeconds.ToString()); + ctx.Response.StatusCode = 204; + ctx.Response.Close(); + } + + private static bool MayWrite(HttpListenerContext ctx) + { + var request = ctx.Request; + if (ApiAccess.IsBlockedCrossSite(request.Headers["Sec-Fetch-Site"], request.Headers["Origin"], request.UserHostName)) + { + ServeError(ctx, 403, "Pages from other websites cannot change anything here"); + return false; + } + + if (!JRTISettings.RequireControlKey || request.IsLocal) return true; + + var provided = ApiAccess.ProvidedKey(request.Headers["Authorization"], request.QueryString[ControlKeyQuery]); + if (ApiAccess.KeyMatches(provided, JRTISettings.ControlKey)) return true; + + ctx.Response.Headers.Add("WWW-Authenticate", "Bearer realm=\"JRTI\""); + ServeError(ctx, 401, "This needs the control key shown in the game's JRTI settings"); + return false; + } + + private Action ForCamera(Action handler) + => (ctx, values) => + { + if (!int.TryParse(values["id"], out int cameraId)) + { + ServeError(ctx, 400, "Invalid camera ID"); + return; + } + if (!_states.TryGetValue(cameraId, out var state)) + { + ServeError(ctx, 404, "Camera not found"); + return; + } + handler(ctx, cameraId, state, values); + }; + + private static Action ForLayout(Action handler) + => (ctx, values) => + { + var name = LayoutName(values); + if (!LayoutNamePattern.IsMatch(name)) + { + ServeError(ctx, 400, "Layout names use letters, digits, spaces, - and _ (64 at most)"); + return; + } + handler(ctx, name); + }; + + private static string LayoutName(RouteValues values) => Uri.UnescapeDataString(values["layout"]).Trim(); + + private static void RedirectToViewer(HttpListenerContext ctx, string id) + { + if (!int.TryParse(id, out int cameraId)) + { + ServeError(ctx, 400, "Invalid camera ID"); + return; + } + ctx.Response.Redirect($"/viewer.html?id={cameraId}"); + ctx.Response.Close(); + } + + private void ServeApiDiscovery(HttpListenerContext ctx) + { + var routes = ApiRoutes.Select(route => + $"{{\"id\":{ApiSchema.Quote(route.Operation.Id)}," + + $"\"methods\":[{string.Join(",", route.Methods.Select(ApiSchema.Quote))}]," + + $"\"path\":{ApiSchema.Quote(ApiRouter.VersionPrefix + route.Operation.Template.TrimEnd('/'))}," + + $"\"summary\":{ApiSchema.Quote(route.Operation.Summary)}," + + $"\"writes\":{Bool(route.Operation.Writes)}}}"); + + var json = new StringBuilder("{"); + json.Append($"\"name\":{ApiSchema.Quote(ApiCatalog.Title)},"); + json.Append($"\"version\":\"{JRTISettingsGUI.ModVersion}\","); + json.Append($"\"api\":{ApiRouter.Version},"); + json.Append($"\"launchId\":\"{LaunchId}\","); + json.Append($"\"features\":{{\"inGameRecording\":{Bool(InGameRecordingAvailable)},\"codecs\":{CodecsJson()},\"controlKeyRequired\":{Bool(JRTISettings.RequireControlKey)}}},"); + json.Append($"\"routes\":[{string.Join(",", routes)}]"); + json.Append('}'); + ServeText(ctx, json.ToString(), "application/json"); + } + + private static string Bool(bool value) => value ? "true" : "false"; + + internal string LinkWithControlKey() + { + var baseUrl = LanUrls().FirstOrDefault(); + return baseUrl == null ? null : $"{baseUrl}?{ControlKeyQuery}={JRTISettings.ControlKey}"; + } + } +} diff --git a/Source/JRTIStreamServer.cs b/Source/JRTIStreamServer.cs index d0ec6ce..2bb17f8 100644 --- a/Source/JRTIStreamServer.cs +++ b/Source/JRTIStreamServer.cs @@ -369,7 +369,8 @@ private void ServeSession(HttpListenerContext ctx) json.Append($"\"version\":\"{JRTISettingsGUI.ModVersion}\","); json.Append($"\"inGameRecording\":{(InGameRecordingAvailable ? "true" : "false")},"); json.Append($"\"codecs\":{CodecsJson()},"); - json.Append($"\"lanUrls\":[{string.Join(",", LanUrls().Select(url => $"\"{url}\""))}]"); + json.Append($"\"lanUrls\":[{string.Join(",", LanUrls().Select(url => $"\"{url}\""))}],"); + json.Append($"\"controlKeyRequired\":{Bool(JRTISettings.RequireControlKey)}"); json.Append('}'); ServeText(ctx, json.ToString(), "application/json"); } @@ -403,20 +404,16 @@ private void HandleRequest(HttpListenerContext ctx) var path = ctx.Request.Url.AbsolutePath; var trimmed = path == "/" ? "" : path.TrimEnd('/'); - if (trimmed == "" || trimmed == "/index.html") { ServeStaticFile(ctx, "index.html"); return; } - if (trimmed == "/cameras") { ServeCameraList(ctx); return; } - if (trimmed == "/streams") { ServeMultiStream(ctx); return; } - if (trimmed == "/session") { ServeSession(ctx); return; } - if (trimmed == "/debug/stats") { ServeDebugStats(ctx); return; } - if (trimmed == "/events") { ServeEvents(ctx); return; } - if (trimmed == "/program" || trimmed.StartsWith("/program/")) { HandleProgram(ctx, trimmed); return; } - if (trimmed == "/layouts" || trimmed.StartsWith("/layouts/")) { HandleLayouts(ctx, trimmed); return; } - if (trimmed == "/recordings") { ServeRecordingList(ctx); return; } - if (trimmed.StartsWith("/recordings/")) { ServeRecordingFile(ctx, trimmed.Substring("/recordings/".Length)); return; } - if (trimmed.StartsWith("/camera/")) { ServeCameraEndpoint(ctx, trimmed); return; } + if (ApiRouter.TryStripVersion(trimmed, out var apiPath)) + { + if (!TryServeRoute(ctx, ApiRoutes, apiPath)) ServeError(ctx, 404, $"Unknown route, see {ApiRouter.VersionPrefix} for the list"); + return; + } + if (TryServeRoute(ctx, PageRoutes, trimmed) || TryServeRoute(ctx, UnversionedApiRoutes, trimmed)) return; + if (TryServeApp(ctx, path)) return; var relative = trimmed.TrimStart('/'); - if (!string.IsNullOrEmpty(relative)) { ServeStaticFile(ctx, relative); return; } + if (!string.IsNullOrEmpty(relative)) { ServeWebFile(ctx, relative); return; } ServeError(ctx, 404, "Not found"); } diff --git a/Tests/JRTI.Tests/ApiAccessTests.cs b/Tests/JRTI.Tests/ApiAccessTests.cs new file mode 100644 index 0000000..887f1f2 --- /dev/null +++ b/Tests/JRTI.Tests/ApiAccessTests.cs @@ -0,0 +1,66 @@ +using JustReadTheInstructions; +using Xunit; + +namespace JRTI.Tests +{ + public class ApiAccessTests + { + [Fact] + public void NewKeysAreValidAndDiffer() + { + var first = ApiAccess.NewKey(); + Assert.True(ApiAccess.IsValidKey(first)); + Assert.NotEqual(first, ApiAccess.NewKey()); + } + + [Theory] + [InlineData(null, false)] + [InlineData("", false)] + [InlineData("ABCDEFGH2", false)] + [InlineData("ABCDEFGHI2", false)] + [InlineData("ABCDEFGHJ2", true)] + public void ValidatesKeys(string key, bool valid) => Assert.Equal(valid, ApiAccess.IsValidKey(key)); + + [Theory] + [InlineData("Bearer ABCDEFGHJ2", null, "ABCDEFGHJ2")] + [InlineData("bearer ABCDEFGHJ2 ", null, "ABCDEFGHJ2")] + [InlineData(null, "ABCDEFGHJ2", "ABCDEFGHJ2")] + [InlineData("Basic xyz", "ABCDEFGHJ2", "ABCDEFGHJ2")] + [InlineData(null, null, null)] + public void ReadsKeyFromHeaderThenQuery(string header, string query, string expected) + => Assert.Equal(expected, ApiAccess.ProvidedKey(header, query)); + + [Theory] + [InlineData("ABCDEFGHJ2", true)] + [InlineData("abcdefghj2", true)] + [InlineData("ABCDEFGHJ3", false)] + [InlineData("ABCDEFGHJ", false)] + [InlineData("ABCDEFGHJ22", false)] + [InlineData(null, false)] + public void ComparesKeys(string provided, bool matches) + => Assert.Equal(matches, ApiAccess.KeyMatches(provided, "ABCDEFGHJ2")); + + [Theory] + [InlineData("http://localhost:5173", true)] + [InlineData("http://127.0.0.1:3000", true)] + [InlineData("http://[::1]:3000", true)] + [InlineData("http://app.localhost", true)] + [InlineData("https://example.com", false)] + [InlineData("http://localhost.example.com", false)] + [InlineData("null", false)] + public void RecognisesLocalhostOrigins(string origin, bool local) + => Assert.Equal(local, ApiAccess.IsLocalhostOrigin(origin)); + + [Theory] + [InlineData(null, null, false)] + [InlineData("none", null, false)] + [InlineData("same-origin", "http://192.168.1.10:8080", false)] + [InlineData("same-site", "http://localhost:5173", false)] + [InlineData("cross-site", "https://evil.example", true)] + [InlineData("cross-site", null, true)] + [InlineData(null, "https://evil.example", true)] + [InlineData(null, "null", true)] + public void BlocksWritesFromOtherSites(string secFetchSite, string origin, bool blocked) + => Assert.Equal(blocked, ApiAccess.IsBlockedCrossSite(secFetchSite, origin, "192.168.1.10:8080")); + } +} diff --git a/Tests/JRTI.Tests/ApiCatalogTests.cs b/Tests/JRTI.Tests/ApiCatalogTests.cs new file mode 100644 index 0000000..3de2a36 --- /dev/null +++ b/Tests/JRTI.Tests/ApiCatalogTests.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using JustReadTheInstructions; +using Xunit; + +namespace JRTI.Tests +{ + public class ApiCatalogTests + { + private const string UpdateVariable = "JRTI_UPDATE_OPENAPI"; + + [Fact] + public void OperationIdsAreUnique() + => Assert.Empty(ApiCatalog.Operations.GroupBy(op => op.Id).Where(g => g.Count() > 1).Select(g => g.Key)); + + [Fact] + public void NoTwoOperationsShareAMethodAndPath() + { + var pairs = ApiCatalog.Operations.SelectMany(op => op.Methods.Select(m => $"{m} {op.Template}")); + Assert.Empty(pairs.GroupBy(p => p).Where(g => g.Count() > 1).Select(g => g.Key)); + } + + [Fact] + public void EveryPathParameterIsDescribed() + { + foreach (var op in ApiCatalog.Operations) + Assert.Equal(op.PathParameterNames.OrderBy(n => n), op.Path.Select(p => p.Name).OrderBy(n => n)); + } + + [Fact] + public void EveryOperationHasAResponse() + => Assert.All(ApiCatalog.Operations, op => Assert.NotNull(op.Response)); + + [Fact] + public void PlainReadsNeverWrite() + => Assert.All(ApiCatalog.Operations.Where(op => op.Method == "GET"), op => Assert.False(op.Writes, op.Id)); + + [Fact] + public void EveryReferencedComponentExists() + { + var document = OpenApiDocument.Build(ApiCatalog.Operations, ApiCatalog.Components); + var references = Regex.Matches(document, "#/components/schemas/(\\w+)") + .Cast().Select(m => m.Groups[1].Value).Distinct(); + Assert.All(references, name => Assert.True(ApiCatalog.Components.ContainsKey(name), name)); + } + + [Fact] + public void PublishedOpenApiDocumentIsCurrent() + { + var path = Path.Combine(RepositoryRoot(), "docs", "openapi.json"); + var expected = OpenApiDocument.Build(ApiCatalog.Operations, ApiCatalog.Components); + + if (Environment.GetEnvironmentVariable(UpdateVariable) == "1") + File.WriteAllText(path, expected); + + Assert.True(File.Exists(path), $"Run the tests once with {UpdateVariable}=1 to write {path}"); + Assert.True(expected == File.ReadAllText(path).Replace("\r\n", "\n"), + $"docs/openapi.json is out of date: run the tests with {UpdateVariable}=1 and commit it"); + } + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "mkdocs.yml"))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("mkdocs.yml not found above the test folder"); + } + } +} diff --git a/Tests/JRTI.Tests/ApiRouterTests.cs b/Tests/JRTI.Tests/ApiRouterTests.cs new file mode 100644 index 0000000..6dfc1bd --- /dev/null +++ b/Tests/JRTI.Tests/ApiRouterTests.cs @@ -0,0 +1,74 @@ +using System.Linq; +using JustReadTheInstructions; +using Xunit; + +namespace JRTI.Tests +{ + public class ApiRouterTests + { + private static readonly ApiRoute[] Routes = + { + Route(new ApiOperation("list", "GET", "/cameras", "")), + Route(new ApiOperation("read", "GET", "/layouts/{layout}", "")), + Route(new ApiOperation("save", "PUT", "/layouts/{layout}", "") { AlsoAccepts = new[] { "POST" } }), + Route(new ApiOperation("record", "POST", "/camera/{id}/recording/{action}", "")), + }; + + private static ApiRoute Route(ApiOperation operation) => new ApiRoute(operation, (ctx, v) => { }); + + [Fact] + public void MatchesLiteralRoute() + { + var outcome = ApiRouter.Resolve(Routes, "GET", "/cameras", out var route, out _, out _); + Assert.Equal(ApiRouter.Outcome.Matched, outcome); + Assert.Equal("list", route.Operation.Id); + } + + [Fact] + public void CapturesParameters() + { + ApiRouter.Resolve(Routes, "POST", "/camera/12/recording/start", out _, out var values, out _); + Assert.Equal("12", values["id"]); + Assert.Equal("start", values["action"]); + } + + [Fact] + public void PicksRouteByMethod() + { + ApiRouter.Resolve(Routes, "PUT", "/layouts/Launch", out var route, out var values, out _); + Assert.Equal("save", route.Operation.Id); + Assert.Equal("Launch", values["layout"]); + } + + [Fact] + public void HeadIsAllowedWhereGetIs() + => Assert.Equal(ApiRouter.Outcome.Matched, ApiRouter.Resolve(Routes, "HEAD", "/cameras", out _, out _, out _)); + + [Fact] + public void WrongMethodListsAllowedMethods() + { + var outcome = ApiRouter.Resolve(Routes, "DELETE", "/layouts/Launch", out _, out _, out var allowed); + Assert.Equal(ApiRouter.Outcome.WrongMethod, outcome); + Assert.Equal(new[] { "GET", "PUT", "POST" }, allowed.ToArray()); + } + + [Theory] + [InlineData("/nope")] + [InlineData("/camera/12/recording")] + [InlineData("/layouts/a/b")] + [InlineData("")] + public void UnknownPathsAreNotFound(string path) + => Assert.Equal(ApiRouter.Outcome.NotFound, ApiRouter.Resolve(Routes, "GET", path, out _, out _, out _)); + + [Theory] + [InlineData("/api/v1/cameras", true, "/cameras")] + [InlineData("/api/v1", true, "/")] + [InlineData("/api/v10/cameras", false, null)] + [InlineData("/cameras", false, null)] + public void StripsVersionPrefix(string path, bool versioned, string rest) + { + Assert.Equal(versioned, ApiRouter.TryStripVersion(path, out var stripped)); + Assert.Equal(rest, stripped); + } + } +} diff --git a/Tests/JRTI.Tests/JRTI.Tests.csproj b/Tests/JRTI.Tests/JRTI.Tests.csproj index 073d574..889b54a 100644 --- a/Tests/JRTI.Tests/JRTI.Tests.csproj +++ b/Tests/JRTI.Tests/JRTI.Tests.csproj @@ -16,6 +16,10 @@ + + + + diff --git a/Tools/check-routes.mjs b/Tools/check-routes.mjs new file mode 100644 index 0000000..26edd50 --- /dev/null +++ b/Tools/check-routes.mjs @@ -0,0 +1,74 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const OPENAPI_FILE = path.join(HERE, '..', 'docs', 'openapi.json'); +const PORT = Number(process.env.CHECK_PORT || 8199); +const BASE = `http://localhost:${PORT}/api/v1`; +const START_TIMEOUT_MS = 60000; +const REQUEST_TIMEOUT_MS = 5000; +const UNKNOWN_ROUTE = 'Unknown route'; + +const SAMPLES = { id: '10', layout: 'RouteCheck', file: 'route-check.mp4', action: 'stop' }; +const BODIES = { saveLayout: '{}', changeCameraSettings: '{}' }; + +function startMock() { + const mock = spawn(process.execPath, [path.join(HERE, 'mock-server.mjs')], { env: { ...process.env, PORT: String(PORT), MOCK_KEY: '' } }); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('mock server did not start')), START_TIMEOUT_MS); + mock.stdout.on('data', (chunk) => { + if (!String(chunk).includes('mock JRTI on')) return; + clearTimeout(timer); + resolve(mock); + }); + mock.on('exit', (code) => reject(new Error(`mock server exited with ${code}`))); + }); +} + +function concretePath(template) { + return template.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(SAMPLES[name] ?? 'x')); +} + +async function call(op) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetch(BASE + concretePath(op.template).replace(/\/$/, ''), { + method: op.method, + body: BODIES[op.id], + headers: BODIES[op.id] ? { 'Content-Type': 'application/json' } : undefined, + signal: controller.signal, + }); + const streaming = /multipart|event-stream|audio/.test(res.headers.get('content-type') ?? ''); + const body = streaming ? '' : await res.text(); + controller.abort(); + return { status: res.status, body }; + } finally { + clearTimeout(timer); + } +} + +const spec = JSON.parse(fs.readFileSync(OPENAPI_FILE, 'utf8')); +const ops = Object.entries(spec.paths).flatMap(([template, methods]) => + Object.entries(methods).map(([method, op]) => ({ id: op.operationId, method: method.toUpperCase(), template }))); + +const mock = await startMock(); +const missing = []; +try { + for (const op of ops) { + const { status, body } = await call(op); + const known = !(status === 404 && body.startsWith(UNKNOWN_ROUTE)); + console.log(`${known ? 'ok ' : 'MISSING'} ${status} ${op.method} ${op.template} (${op.id})`); + if (!known) missing.push(op.id); + } +} finally { + mock.kill(); +} + +if (missing.length) { + console.error(`\nThe mock server has no route for: ${missing.join(', ')}`); + process.exit(1); +} +console.log(`\nAll ${ops.length} API operations answer in the mock server`); diff --git a/Tools/mock-server.mjs b/Tools/mock-server.mjs index 4e37719..e6482f8 100644 --- a/Tools/mock-server.mjs +++ b/Tools/mock-server.mjs @@ -15,6 +15,11 @@ const LOOP_FRAMES = 90; const BOUNDARY = 'jrtiboundary'; const AUDIO_RATE = 48000; const AUDIO_TICK_MS = 20; +const API_PREFIX = '/api/v1'; +const OPENAPI_FILE = path.join(DOCS, 'openapi.json'); +const PLUGIN_DATA = path.join(ROOT, 'GameData', 'JustReadTheInstructions', 'PluginData'); +const MOCK_KEY = process.env.MOCK_KEY?.trim().toUpperCase(); +const PREFLIGHT_MAX_AGE_S = 600; const FEEDS = [ [10, 'screenshot-3.png', 'crop=2320:1305:160:100'], @@ -280,6 +285,67 @@ function sample() { }; } +function openApi() { + return JSON.parse(fs.readFileSync(OPENAPI_FILE, 'utf8')); +} + +function operations() { + return Object.entries(openApi().paths).flatMap(([template, methods]) => Object.entries(methods).map(([method, op]) => ({ + id: op.operationId, method: method.toUpperCase(), template, summary: op.summary, writes: Boolean(op.security), + }))); +} + +function matchesTemplate(template, p) { + const want = template.split('/').filter(Boolean); + const got = p.split('/').filter(Boolean); + return want.length === got.length && want.every((segment, i) => segment.startsWith('{') || segment === got[i]); +} + +function isWrite(method, p) { + const ops = operations().filter((op) => matchesTemplate(op.template, p)); + const exact = ops.find((op) => op.method === method || (method === 'HEAD' && op.method === 'GET')); + return exact ? exact.writes : ops.some((op) => op.writes); +} + +function discovery() { + const routes = operations().map(({ id, method, template, summary, writes }) => ({ + id, methods: [method], path: API_PREFIX + (template === '/' ? '' : template), summary, writes, + })); + return { name: 'Just Read The Instructions', version: '2.5.1.1', api: 1, launchId, features: { inGameRecording: true, codecs: ['h264', 'av1'], controlKeyRequired: Boolean(MOCK_KEY) }, routes }; +} + +function isLocalhostOrigin(origin) { + try { + const { hostname } = new URL(origin); + return ['localhost', '127.0.0.1', '[::1]'].includes(hostname) || hostname.endsWith('.localhost'); + } catch { + return false; + } +} + +function isBlockedCrossSite(req) { + const origin = req.headers.origin; + if (!origin || origin === `http://${req.headers.host}` || isLocalhostOrigin(origin)) return req.headers['sec-fetch-site'] === 'cross-site' && !origin; + return true; +} + +function providedKey(req, url) { + const header = req.headers.authorization ?? ''; + const key = /^bearer /i.test(header) ? header.slice(7) : url.searchParams.get('key'); + return key?.trim().toUpperCase(); +} + +function insideRoot(root, rel) { + const full = path.join(root, rel); + return full.startsWith(path.normalize(root)) ? full : null; +} + +function sendStatic(res, full) { + if (!full || !fs.existsSync(full) || fs.statSync(full).isDirectory()) return text(res, 404, 'Not found'); + res.writeHead(200, { 'Content-Type': types[path.extname(full)] ?? 'application/octet-stream', 'Cache-Control': 'no-cache' }); + fs.createReadStream(full).pipe(res); +} + function listRecordings() { const active = new Set([...cameras.values()].filter((c) => c.recording).map((c) => c.recording.file)); return fs.readdirSync(recordingsDir).filter((f) => /\.(mp4|webm|mkv)$/i.test(f)).map((file) => { @@ -324,10 +390,36 @@ function serveFile(req, res, file, type, download) { const server = http.createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host}`); - const p = url.pathname.replace(/\/+$/, '') || '/'; + const pathname = url.pathname.replace(/\/+$/, '') || '/'; + const versioned = pathname.startsWith(`${API_PREFIX}/`); + const p = versioned ? pathname.slice(API_PREFIX.length) : pathname; const parts = p.split('/').filter(Boolean); + const origin = req.headers.origin; + const cors = Boolean(origin) && isLocalhostOrigin(origin) && origin !== `http://${req.headers.host}`; try { - if (p === '/session') return json(res, { launchId, inGameRecording: true, codecs: ['h264', 'av1'], version: '2.5.1.1', lanUrls: [`http://192.168.1.42:${PORT}/`] }); + if (cors) { + res.setHeader('Access-Control-Allow-Origin', origin); + res.setHeader('Vary', 'Origin'); + } + if (cors && req.method === 'OPTIONS') { + res.writeHead(204, { + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE', + 'Access-Control-Allow-Headers': 'Authorization, Content-Type', + 'Access-Control-Allow-Private-Network': 'true', + 'Access-Control-Max-Age': String(PREFLIGHT_MAX_AGE_S), + }); + return res.end(); + } + if (isWrite(req.method, p)) { + if (isBlockedCrossSite(req)) return text(res, 403, 'Pages from other websites cannot change anything here'); + if (MOCK_KEY && providedKey(req, url) !== MOCK_KEY) { + res.setHeader('WWW-Authenticate', 'Bearer realm="JRTI"'); + return text(res, 401, "This needs the control key shown in the game's JRTI settings"); + } + } + if (pathname === API_PREFIX) return json(res, discovery()); + if (versioned && p === '/openapi.json') return json(res, openApi()); + if (p === '/session') return json(res, { launchId, inGameRecording: true, codecs: ['h264', 'av1'], version: '2.5.1.1', lanUrls: [`http://192.168.1.42:${PORT}/`], controlKeyRequired: Boolean(MOCK_KEY) }); if (p === '/cameras') return json(res, cameraList()); if (p === '/debug/stats') return json(res, sample()); if (p === '/events') return events(req, res); @@ -405,11 +497,18 @@ const server = http.createServer(async (req, res) => { default: return text(res, 404, 'Unknown action'); } } + if (versioned) return text(res, 404, `Unknown route, see ${API_PREFIX} for the list`); + if (parts[0] === 'apps') { + const full = insideRoot(path.join(PLUGIN_DATA, 'Apps'), decodeURIComponent(parts.slice(1).join('/'))); + if (full && fs.existsSync(full) && fs.statSync(full).isDirectory()) { + if (!url.pathname.endsWith('/')) { res.writeHead(302, { Location: `${url.pathname}/` }); return res.end(); } + return sendStatic(res, path.join(full, 'index.html')); + } + return sendStatic(res, full); + } const rel = p === '/' ? 'index.html' : decodeURIComponent(p.slice(1)); - const full = path.join(WEB, rel); - if (!full.startsWith(path.normalize(WEB)) || !fs.existsSync(full) || fs.statSync(full).isDirectory()) return text(res, 404, 'Not found'); - res.writeHead(200, { 'Content-Type': types[path.extname(full)] ?? 'application/octet-stream', 'Cache-Control': 'no-cache' }); - fs.createReadStream(full).pipe(res); + const custom = insideRoot(path.join(PLUGIN_DATA, 'Web'), rel); + sendStatic(res, custom && fs.existsSync(custom) ? custom : insideRoot(WEB, rel)); } catch (err) { console.error(err); if (!res.headersSent) text(res, 500, String(err)); diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..501f90e --- /dev/null +++ b/docs/api.md @@ -0,0 +1,73 @@ +# API + +Everything the web UI does goes through a plain HTTP API, so you can build your own page, a phone app, a desktop app or an overlay on top of the same feeds. Any language with an HTTP client works. + +## Start here + +Open `http://localhost:8080/api/v1` (or your port). It answers with the mod version, the API version, what this game supports and every route with a one-line description: + +```json +{ + "name": "Just Read The Instructions", + "version": "3.3.0.0", + "api": 1, + "launchId": "…", + "features": { "inGameRecording": true, "codecs": ["h264", "av1"], "controlKeyRequired": false }, + "routes": [ + { "id": "listCameras", "methods": ["GET"], "path": "/api/v1/cameras", "summary": "Cameras with their name, viewers, mic, pan and recording state", "writes": false } + ] +} +``` + +The full description, with every request and response field, is an [OpenAPI 3.1 document](openapi.json). The game serves the same file at `/api/v1/openapi.json`. Feed it to a generator such as `openapi-generator` to get a typed client in Rust, Kotlin, Swift, TypeScript or most other languages. + +## What you get + +| Kind | Format | Example | +| --- | --- | --- | +| State | JSON | `GET /api/v1/cameras`, `GET /api/v1/camera//settings` | +| Changes | JSON body | `POST /api/v1/camera//settings` with `{"fov": 40}` | +| Live updates | Server-Sent Events | `GET /api/v1/events` (on-air and layout changes) | +| Video | MJPEG over HTTP | `GET /api/v1/camera//stream`, or one JPEG with `/snapshot` | +| Several feeds at once | One multipart stream | `GET /api/v1/streams?ids=10,11`, each part tagged with an `X-Camera-Id` header | +| Sound | WAV stream | `GET /api/v1/camera//audio` | + +Errors come back with a standard HTTP status and a short plain-text message. A route called with the wrong method answers `405` with an `Allow` header listing the right ones. + +## Versions + +Within `v1`, routes and fields are only added, never renamed or removed, so ignore fields you do not know. Anything that has to break goes to `/api/v2`, with `v1` kept next to it for a while. + +The older short addresses without `/api/v1` (such as `http://localhost:8080/camera//stream` for OBS, or `/program/take/` from a Stream Deck) keep working: they are the same routes, with the same rules. + +## From another device + +The API listens on your network like the web UI, with nothing to set up. To check a flight from your phone while you are away, use a private network such as [Tailscale](https://tailscale.com/) and open the computer's Tailscale address with the port. + +!!! warning "Do not port-forward it" + Without a control key, anyone who can reach the port can watch your cameras, change their settings and start recordings. Forwarding the port on your router puts it on the whole internet. Use a private network such as Tailscale instead. + +### Control key + +Watching is always open. To stop other devices from changing anything, tick **Require a key to control from other devices** in the settings window (see [Settings](settings.md#stream-capture)). From then on, changing camera settings, recording, saving or deleting layouts and switching what is on air need the key, except from the KSP computer itself. + +* In the web UI, open the link from **Copy link** once on each device, or type the key when the page asks. The browser remembers it. +* In your own app, send it as `Authorization: Bearer `, or add `?key=` to the address (handy for Stream Deck buttons). +* **New key** makes a fresh one, which logs every device out. + +A request without the right key gets `401`. Routes that need the key are marked `writes: true` in `/api/v1` and carry a `security` entry in the OpenAPI document. + +## Building a web page + +Web pages from other websites cannot change anything here (they get `403`), so a page you find online cannot start recordings or switch your layouts behind your back. Your own pages work from two places: + +* **The Apps folder.** Put a folder in `GameData/JustReadTheInstructions/PluginData/Apps/`, for example `Apps/my-overlay/index.html`, and open `http://localhost:8080/apps/my-overlay/`. It is served by the game itself, so it reaches the API with no extra setup, from any device, and mod updates never touch it. +* **A development server on your computer.** Pages served from `localhost` or `127.0.0.1` on any port can call the API from the browser, so tools like Vite work while you build. + +A page opened straight from a file (`file://`) cannot change anything: put it in the Apps folder instead. + +## Changing the web UI + +To change one of the bundled pages, copy it from `GameData/JustReadTheInstructions/Web/` into `GameData/JustReadTheInstructions/PluginData/Web/` at the same place, and edit the copy. A file there replaces the shipped one, for example `PluginData/Web/css/styles.css` or `PluginData/Web/images/los.png`. Updates never overwrite it. + +Your copy also stays as it is when the mod updates the original, so a copied page can stop working after an update. Delete the copy to go back to the shipped file. diff --git a/docs/layouts-obs.md b/docs/layouts-obs.md index 128f720..14352a5 100644 --- a/docs/layouts-obs.md +++ b/docs/layouts-obs.md @@ -49,7 +49,7 @@ http://localhost:8080/program/take/Launch http://localhost:8080/program/clear ``` -`/program/clear` puts nothing on air, which shows black. +`/program/clear` puts nothing on air, which shows black. If you turned on the [control key](api.md#control-key), add it to the URL, for example `http://192.168.1.10:8080/program/take/Launch?key=ABCD234567`. The clean feed switches at once: cameras that stay glide to their new place, new ones fade in, removed ones fade out. The on-air layout is remembered by the game (`PluginData/program.txt`). diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 0000000..a0a988c --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,1160 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Just Read The Instructions", + "version": "1" + }, + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + "/": { + "get": { + "operationId": "getApi", + "summary": "Mod version, features and every route", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Discovery" + } + } + } + } + } + } + }, + "/openapi.json": { + "get": { + "operationId": "getOpenApi", + "summary": "This API as an OpenAPI 3.1 document, to generate clients", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, + "/session": { + "get": { + "operationId": "getSession", + "summary": "Game session: launch id, mod version, recording support, codecs, network addresses", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Session" + } + } + } + } + } + } + }, + "/cameras": { + "get": { + "operationId": "listCameras", + "summary": "Cameras with their name, viewers, mic, pan and recording state", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Camera" + } + } + } + } + } + } + } + }, + "/streams": { + "get": { + "operationId": "getStreams", + "summary": "Several cameras in one multipart stream; each part names its camera in an X-Camera-Id header", + "parameters": [ + { + "name": "ids", + "in": "query", + "required": false, + "description": "Camera IDs separated by commas, such as 10,11", + "schema": { + "type": "string" + } + }, + { + "name": "preview", + "in": "query", + "required": false, + "description": "1 for preview-size frames", + "schema": { + "type": "string", + "enum": [ + "1" + ] + } + } + ], + "responses": { + "200": { + "description": "JPEG frames", + "content": { + "multipart/x-mixed-replace": {} + } + } + } + } + }, + "/events": { + "get": { + "operationId": "getEvents", + "summary": "Server-Sent Events: program (the layout on air) and layout (a saved layout changed)", + "responses": { + "200": { + "description": "Events, with a ping comment every 15 seconds", + "content": { + "text/event-stream": {} + } + } + } + } + }, + "/debug/stats": { + "get": { + "operationId": "getDebugStats", + "summary": "Latest performance sample", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + } + }, + "/program": { + "get": { + "operationId": "getProgram", + "summary": "The layout on air", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Program" + } + } + } + } + } + } + }, + "/program/take/{layout}": { + "post": { + "operationId": "takeProgram", + "summary": "Puts a saved layout on air. Also answers GET, for Stream Deck and browser links", + "parameters": [ + { + "name": "layout", + "in": "path", + "required": true, + "description": "Layout name: letters, digits, spaces, - and _ (64 at most)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Program" + } + } + } + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/program/clear": { + "post": { + "operationId": "clearProgram", + "summary": "Takes the program off air. Also answers GET, for links", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Program" + } + } + } + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/layouts": { + "get": { + "operationId": "listLayouts", + "summary": "Saved layouts", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LayoutEntry" + } + } + } + } + } + } + } + }, + "/layouts/{layout}": { + "get": { + "operationId": "getLayout", + "summary": "One saved layout, as saved by the layout page", + "parameters": [ + { + "name": "layout", + "in": "path", + "required": true, + "description": "Layout name: letters, digits, spaces, - and _ (64 at most)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + }, + "put": { + "operationId": "saveLayout", + "summary": "Saves a layout: a JSON object of 64 KB at most. Also answers POST", + "parameters": [ + { + "name": "layout", + "in": "path", + "required": true, + "description": "Layout name: letters, digits, spaces, - and _ (64 at most)", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "responses": { + "204": { + "description": "Saved" + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + }, + "delete": { + "operationId": "deleteLayout", + "summary": "Deletes a layout", + "parameters": [ + { + "name": "layout", + "in": "path", + "required": true, + "description": "Layout name: letters, digits, spaces, - and _ (64 at most)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Deleted" + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/recordings": { + "get": { + "operationId": "listRecordings", + "summary": "Recordings on disk, newest first", + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RecordingFile" + } + } + } + } + } + } + } + }, + "/recordings/{file}": { + "get": { + "operationId": "getRecording", + "summary": "One recording, with byte ranges for seeking", + "parameters": [ + { + "name": "file", + "in": "path", + "required": true, + "description": "File name, as listed by /recordings", + "schema": { + "type": "string" + } + }, + { + "name": "download", + "in": "query", + "required": false, + "description": "1 to save it instead of playing it", + "schema": { + "type": "string", + "enum": [ + "1" + ] + } + } + ], + "responses": { + "200": { + "description": "The video file", + "content": { + "video/mp4": {} + } + } + } + } + }, + "/camera/{id}/snapshot": { + "get": { + "operationId": "getSnapshot", + "summary": "Latest frame", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "JPEG image", + "content": { + "image/jpeg": {} + } + } + } + } + }, + "/camera/{id}/stream": { + "get": { + "operationId": "getStream", + "summary": "MJPEG stream at render size, for OBS, VLC or an img tag", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "JPEG frames", + "content": { + "multipart/x-mixed-replace": {} + } + } + } + } + }, + "/camera/{id}/preview": { + "get": { + "operationId": "getPreview", + "summary": "MJPEG stream at preview size", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "JPEG frames", + "content": { + "multipart/x-mixed-replace": {} + } + } + } + } + }, + "/camera/{id}/audio": { + "get": { + "operationId": "getAudio", + "summary": "Camera sound as an endless WAV stream", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "PCM audio", + "content": { + "audio/wav": {} + } + } + } + } + }, + "/camera/{id}/status": { + "get": { + "operationId": "getCameraStatus", + "summary": "Answers ok while the camera exists", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "ok", + "content": { + "text/plain": {} + } + } + } + } + }, + "/camera/{id}/settings": { + "get": { + "operationId": "getCameraSettings", + "summary": "Image, sound, field of view and pan settings", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CameraSettings" + } + } + } + } + } + }, + "post": { + "operationId": "changeCameraSettings", + "summary": "Changes any of the listed fields and leaves the others alone", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CameraSettingsChange" + } + } + } + }, + "responses": { + "200": { + "description": "Changed" + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/camera/{id}/recording/{action}": { + "post": { + "operationId": "controlRecording", + "summary": "Starts, stops, discards, pauses or resumes the in-game recording", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + }, + { + "name": "action", + "in": "path", + "required": true, + "description": "What to do", + "schema": { + "type": "string", + "enum": [ + "start", + "stop", + "discard", + "pause", + "resume" + ] + } + }, + { + "name": "codec", + "in": "query", + "required": false, + "description": "Codec for start, h264 by default", + "schema": { + "type": "string", + "enum": [ + "h264", + "av1" + ] + } + } + ], + "responses": { + "200": { + "description": "The recording, or null once stopped", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/Recording" + }, + { + "type": "null" + } + ] + } + } + } + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "Sent by a web page from another site" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + } + }, + "components": { + "schemas": { + "Camera": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "streaming": { + "type": "boolean" + }, + "viewerCount": { + "type": "integer" + }, + "snapshotUrl": { + "type": "string" + }, + "streamUrl": { + "type": "string" + }, + "mic": { + "type": "string", + "enum": [ + "game", + "external", + "onboard" + ] + }, + "canPan": { + "type": "boolean" + }, + "track": { + "type": "string", + "enum": [ + "off", + "vessel", + "target" + ] + }, + "recording": { + "oneOf": [ + { + "$ref": "#/components/schemas/Recording" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "name", + "streaming", + "viewerCount", + "snapshotUrl", + "streamUrl", + "mic", + "canPan", + "track", + "recording" + ] + }, + "CameraSettings": { + "type": "object", + "properties": { + "brightness": { + "type": "number" + }, + "contrast": { + "type": "number" + }, + "gamma": { + "type": "number" + }, + "mic": { + "type": "string", + "enum": [ + "game", + "external", + "onboard" + ] + }, + "soundGain": { + "type": "number" + }, + "autoGain": { + "type": "boolean" + }, + "mastering": { + "type": "boolean" + }, + "fov": { + "type": "number" + }, + "fovMin": { + "type": "number" + }, + "fovMax": { + "type": "number" + }, + "fovLimitMin": { + "type": "number" + }, + "fovLimitMax": { + "type": "number" + }, + "pan": { + "$ref": "#/components/schemas/Pan" + } + }, + "required": [ + "brightness", + "contrast", + "gamma", + "mic", + "soundGain", + "autoGain", + "mastering" + ] + }, + "CameraSettingsChange": { + "type": "object", + "properties": { + "brightness": { + "type": "number" + }, + "contrast": { + "type": "number" + }, + "gamma": { + "type": "number" + }, + "fov": { + "type": "number" + }, + "mic": { + "type": "string", + "enum": [ + "game", + "external", + "onboard" + ] + }, + "soundGain": { + "type": "number" + }, + "autoGain": { + "type": "boolean" + }, + "mastering": { + "type": "boolean" + }, + "zoomRate": { + "type": "number" + }, + "panYaw": { + "type": "number" + }, + "panPitch": { + "type": "number" + }, + "panYawRate": { + "type": "number" + }, + "panPitchRate": { + "type": "number" + }, + "track": { + "type": "string", + "enum": [ + "off", + "vessel", + "target" + ] + } + } + }, + "Discovery": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "api": { + "type": "integer" + }, + "launchId": { + "type": "string" + }, + "features": { + "type": "object", + "properties": { + "inGameRecording": { + "type": "boolean" + }, + "codecs": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "h264", + "av1" + ] + } + }, + "controlKeyRequired": { + "type": "boolean" + } + }, + "required": [ + "inGameRecording", + "codecs", + "controlKeyRequired" + ] + }, + "routes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Route" + } + } + }, + "required": [ + "name", + "version", + "api", + "launchId", + "features", + "routes" + ] + }, + "LayoutEntry": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "updated": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "name", + "updated" + ] + }, + "Pan": { + "type": "object", + "properties": { + "yaw": { + "type": "number" + }, + "pitch": { + "type": "number" + }, + "pitchMin": { + "type": "number" + }, + "pitchMax": { + "type": "number" + }, + "track": { + "type": "string", + "enum": [ + "off", + "vessel", + "target" + ] + } + }, + "required": [ + "yaw", + "pitch", + "pitchMin", + "pitchMax", + "track" + ] + }, + "Program": { + "type": "object", + "properties": { + "layout": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "version": { + "type": "integer" + } + }, + "required": [ + "layout", + "version" + ] + }, + "Recording": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "paused": { + "type": "boolean" + }, + "elapsedMs": { + "type": "integer" + }, + "bytes": { + "type": "integer" + }, + "framesWritten": { + "type": "integer" + }, + "framesDropped": { + "type": "integer" + }, + "error": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "file", + "paused", + "elapsedMs", + "bytes", + "framesWritten", + "framesDropped", + "error" + ] + }, + "RecordingFile": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "bytes": { + "type": "integer" + }, + "modified": { + "type": "string", + "format": "date-time" + }, + "recording": { + "type": "boolean" + } + }, + "required": [ + "file", + "bytes", + "modified", + "recording" + ] + }, + "Route": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "methods": { + "type": "array", + "items": { + "type": "string" + } + }, + "path": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "writes": { + "type": "boolean" + } + }, + "required": [ + "id", + "methods", + "path", + "summary", + "writes" + ] + }, + "Session": { + "type": "object", + "properties": { + "launchId": { + "type": "string" + }, + "version": { + "type": "string" + }, + "inGameRecording": { + "type": "boolean" + }, + "codecs": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "h264", + "av1" + ] + } + }, + "lanUrls": { + "type": "array", + "items": { + "type": "string" + } + }, + "controlKeyRequired": { + "type": "boolean" + } + }, + "required": [ + "launchId", + "version", + "inGameRecording", + "codecs", + "lanUrls", + "controlKeyRequired" + ] + } + }, + "securitySchemes": { + "controlKey": { + "type": "http", + "scheme": "bearer", + "description": "Only when the player turns on Require a key. The key can also go in a key query parameter" + } + } + } +} diff --git a/docs/settings.md b/docs/settings.md index d54e391..6078ab4 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -18,6 +18,7 @@ Open it in flight with `Ctrl` + `Alt` + `F8` or `F9`. Everything is saved when y | --- | --- | --- | | Enable web streaming server | On | Turn off to run JRTI with in-game camera windows only: no web UI, browser streaming or recording. Lighter on weak machines. Takes effect when you next enter a flight scene | | Port | `8080` | The web UI and stream port (1024 to 65535). Changing it needs a game restart | +| Require a key to control from other devices | Off | Other devices can still watch, but changing settings, recording and switching layouts need the key shown under it. **Copy link** gives this computer's address with the key, **New key** logs every device out. See [API](api.md#control-key) | | JPEG Quality | `90` | Quality of the MJPEG stream, 1 to 100. Lower is smaller and faster | | Max FPS | `30` | The most renders per second any camera makes, in its window and in streams alike (1 to 120). Each render costs about as much as the game's own view, so lower it if the game slows down | | Render Width and Height | `1280` x `720` | The resolution every camera renders at, and the size of recordings. Applies the next time a camera opens | @@ -45,7 +46,7 @@ If another program already uses the port, JRTI says so on screen and in `KSP.log Settings are saved in `GameData/JustReadTheInstructions/PluginData/settings.cfg`. Defaults live in the mod itself, so updates never reset your choices. -Per-camera sound choices are in `PluginData/camera-sound.cfg`, and saved layouts in `PluginData/Layouts/`. +Per-camera sound choices are in `PluginData/camera-sound.cfg`, and saved layouts in `PluginData/Layouts/`. Your own pages go in `PluginData/Apps/` and changed copies of the web UI in `PluginData/Web/` (see [API](api.md#building-a-web-page)). ## Visual mods diff --git a/mkdocs.yml b/mkdocs.yml index 08048d3..140f54b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -45,6 +45,7 @@ nav: - Recording: recording.md - Settings and mods: settings.md - Troubleshooting: troubleshooting.md + - API: api.md markdown_extensions: - admonition From 5301fc0ad0e67c937138001b67d834ebc370e334 Mon Sep 17 00:00:00 2001 From: RELMYMathieu Date: Tue, 17 Nov 2026 18:31:51 +0100 Subject: [PATCH 2/4] fix: harden the api against dns rebinding, add more context to docs --- CHANGELOG.md | 2 + CONTRIBUTING.md | 2 +- Source/ApiAccess.cs | 42 +++++++- Source/JRTISettings.cs | 3 + Source/JRTIStreamServer.Routes.cs | 25 ++--- Source/JRTIStreamServer.cs | 6 ++ Tests/JRTI.Tests/ApiAccessScenarioTests.cs | 117 +++++++++++++++++++++ Tests/JRTI.Tests/ApiAccessTests.cs | 34 ++++++ Tools/mock-server.mjs | 54 ++++++++-- docs/api.md | 31 +++++- docs/settings.md | 2 + docs/troubleshooting.md | 2 + 12 files changed, 295 insertions(+), 25 deletions(-) create mode 100644 Tests/JRTI.Tests/ApiAccessScenarioTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a17dc8..a8401bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Web pages from other websites can no longer change camera settings, recordings or layouts. Pages served from localhost (development servers) can use the API from the browser +- Allowed names (`AllowedHosts` in `PluginData/settings.cfg`) - the web UI only answers to localhost, IP addresses, the computer's name, Tailscale names and the names listed there, so a website cannot reach it under its own name +- Control key - the KSP computer skips the key only when opened as localhost, not through its network address or a local proxy ## v3.3.0 - 2026-11-11 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 10ea05d..4a23eaf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -74,7 +74,7 @@ The web files in `GameData/JustReadTheInstructions/Web/` are static and need no node Tools/mock-server.mjs ``` -It serves the Web folder on port 8099. Set `MOCK_KEY=ABCD234567` to make it require a control key, as if every request came from another device. +It serves the Web folder on port 8099. Set `MOCK_KEY=ABCD234567` to make it require a control key with the game's rules: `localhost` on this computer never needs it, while its network address (for example `http://192.168.1.10:8099/`, like a phone) and requests through a proxy do. `MOCK_ALLOWED_HOSTS` works like `AllowedHosts`. ## Adding or changing an endpoint diff --git a/Source/ApiAccess.cs b/Source/ApiAccess.cs index d124088..06e4ed4 100644 --- a/Source/ApiAccess.cs +++ b/Source/ApiAccess.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Security.Cryptography; namespace JustReadTheInstructions @@ -8,6 +9,9 @@ public static class ApiAccess private const string KeyAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; public const int KeyLength = 10; public const string BearerPrefix = "Bearer "; + private const string TailscaleSuffix = ".ts.net"; + private static readonly char[] HostListSeparators = { ',', ' ' }; + private static readonly string[] ProxyHeaders = { "X-Forwarded-For", "X-Forwarded-Host", "X-Real-IP", "Forwarded" }; public static string NewKey() { @@ -46,12 +50,34 @@ public static bool KeyMatches(string provided, string expected) } public static bool IsLocalhostOrigin(string origin) + => Uri.TryCreate(origin, UriKind.Absolute, out var uri) && IsLoopback(uri); + + public static bool IsLoopbackHost(string hostHeader) + => TryParseHost(hostHeader, out var uri) && IsLoopback(uri); + + public static bool IsAllowedHost(string hostHeader, string machineName, string allowedHosts) { - if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri)) return false; - return uri.IsLoopback || uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) - || uri.Host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + if (string.IsNullOrEmpty(hostHeader)) return true; + if (!TryParseHost(hostHeader, out var uri)) return false; + if (uri.HostNameType != UriHostNameType.Dns || IsLoopback(uri)) return true; + if (uri.Host.EndsWith(TailscaleSuffix, StringComparison.OrdinalIgnoreCase)) return true; + + var names = (allowedHosts ?? "").Split(HostListSeparators, StringSplitOptions.RemoveEmptyEntries) + .Concat(new[] { machineName, machineName + ".local" }); + return names.Any(name => string.Equals(name, uri.Host, StringComparison.OrdinalIgnoreCase)); } + public static bool IsDirectFromThisComputer(bool connectionIsLocal, string hostHeader, Func header) + => connectionIsLocal && IsLoopbackHost(hostHeader) && ProxyHeaders.All(name => header(name) == null); + + private static bool TryParseHost(string hostHeader, out Uri uri) + => Uri.TryCreate("http://" + hostHeader, UriKind.Absolute, out uri) + && uri.AbsolutePath == "/" && uri.UserInfo.Length == 0 && uri.Query.Length == 0 && uri.Fragment.Length == 0; + + private static bool IsLoopback(Uri uri) + => uri.IsLoopback || uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) + || uri.Host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + public static bool IsSameOrigin(string origin, string requestHost) => Uri.TryCreate(origin, UriKind.Absolute, out var uri) && string.Equals(uri.Authority, requestHost, StringComparison.OrdinalIgnoreCase); @@ -62,5 +88,15 @@ public static bool IsBlockedCrossSite(string secFetchSite, string origin, string return secFetchSite == "cross-site" && origin == null; return true; } + + public enum WriteVerdict { Allowed, OtherWebsite, NeedsKey } + + public static WriteVerdict CheckWrite(bool requireKey, string expectedKey, bool connectionIsLocal, + string hostHeader, string keyQuery, Func header) + { + if (IsBlockedCrossSite(header("Sec-Fetch-Site"), header("Origin"), hostHeader)) return WriteVerdict.OtherWebsite; + if (!requireKey || IsDirectFromThisComputer(connectionIsLocal, hostHeader, header)) return WriteVerdict.Allowed; + return KeyMatches(ProvidedKey(header("Authorization"), keyQuery), expectedKey) ? WriteVerdict.Allowed : WriteVerdict.NeedsKey; + } } } diff --git a/Source/JRTISettings.cs b/Source/JRTISettings.cs index 7d47c6e..759fe31 100644 --- a/Source/JRTISettings.cs +++ b/Source/JRTISettings.cs @@ -39,6 +39,7 @@ public class JRTISettings : MonoBehaviour public static bool AutoStreamCameras { get; internal set; } = false; public static bool RequireControlKey { get; internal set; } = false; public static string ControlKey { get; internal set; } = ""; + public static string AllowedHosts { get; internal set; } = ""; public static float FramePeriod => 1f / Mathf.Max(1, StreamMaxFps); @@ -126,6 +127,7 @@ private static void LoadConfig() AutoStreamCameras = ParseBool(settings, "AutoStreamCameras", AutoStreamCameras); RequireControlKey = ParseBool(settings, "RequireControlKey", RequireControlKey); ControlKey = settings.GetValue("ControlKey") ?? ControlKey; + AllowedHosts = settings.GetValue("AllowedHosts") ?? AllowedHosts; EnableDeferred = ParseBool(settings, "EnableDeferred", EnableDeferred); EnableTUFX = ParseBool(settings, "EnableTUFX", EnableTUFX); @@ -192,6 +194,7 @@ public static bool Save() settings.AddValue("AutoStreamCameras", AutoStreamCameras); settings.AddValue("RequireControlKey", RequireControlKey); settings.AddValue("ControlKey", ControlKey); + settings.AddValue("AllowedHosts", AllowedHosts); settings.AddValue("EnableDeferred", EnableDeferred); settings.AddValue("EnableTUFX", EnableTUFX); diff --git a/Source/JRTIStreamServer.Routes.cs b/Source/JRTIStreamServer.Routes.cs index f8df1dd..085d927 100644 --- a/Source/JRTIStreamServer.Routes.cs +++ b/Source/JRTIStreamServer.Routes.cs @@ -111,20 +111,21 @@ private static void ServePreflight(HttpListenerContext ctx, IReadOnlyList request.Headers[name]); + + switch (verdict) { - ServeError(ctx, 403, "Pages from other websites cannot change anything here"); - return false; + case ApiAccess.WriteVerdict.OtherWebsite: + ServeError(ctx, 403, "Pages from other websites cannot change anything here"); + return false; + case ApiAccess.WriteVerdict.NeedsKey: + ctx.Response.Headers.Add("WWW-Authenticate", "Bearer realm=\"JRTI\""); + ServeError(ctx, 401, "This needs the control key shown in the game's JRTI settings"); + return false; + default: + return true; } - - if (!JRTISettings.RequireControlKey || request.IsLocal) return true; - - var provided = ApiAccess.ProvidedKey(request.Headers["Authorization"], request.QueryString[ControlKeyQuery]); - if (ApiAccess.KeyMatches(provided, JRTISettings.ControlKey)) return true; - - ctx.Response.Headers.Add("WWW-Authenticate", "Bearer realm=\"JRTI\""); - ServeError(ctx, 401, "This needs the control key shown in the game's JRTI settings"); - return false; } private Action ForCamera(Action handler) diff --git a/Source/JRTIStreamServer.cs b/Source/JRTIStreamServer.cs index 2bb17f8..96ba467 100644 --- a/Source/JRTIStreamServer.cs +++ b/Source/JRTIStreamServer.cs @@ -401,6 +401,12 @@ private void HandleRequest(HttpListenerContext ctx) { try { + if (!ApiAccess.IsAllowedHost(ctx.Request.UserHostName, Environment.MachineName, JRTISettings.AllowedHosts)) + { + ServeError(ctx, 403, "This name is not allowed here. Use the computer's IP address, or add the name to AllowedHosts in PluginData/settings.cfg"); + return; + } + var path = ctx.Request.Url.AbsolutePath; var trimmed = path == "/" ? "" : path.TrimEnd('/'); diff --git a/Tests/JRTI.Tests/ApiAccessScenarioTests.cs b/Tests/JRTI.Tests/ApiAccessScenarioTests.cs new file mode 100644 index 0000000..c32a1a4 --- /dev/null +++ b/Tests/JRTI.Tests/ApiAccessScenarioTests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using JustReadTheInstructions; +using Xunit; +using static JustReadTheInstructions.ApiAccess; + +namespace JRTI.Tests +{ + public class ApiAccessScenarioTests + { + private const string Key = "ABCDEFGHJ2"; + private const string MachineName = "GAMEPC"; + + private sealed class Request + { + public bool ConnectionIsLocal; + public string Host; + public string KeyQuery; + public readonly Dictionary Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public Request With(string name, string value) + { + Headers[name] = value; + return this; + } + + public Request WithKeyQuery(string key) + { + KeyQuery = key; + return this; + } + + public WriteVerdict Check(bool requireKey) + { + Assert.True(IsAllowedHost(Host, MachineName, ""), $"{Host} should be an allowed name"); + return CheckWrite(requireKey, Key, ConnectionIsLocal, Host, KeyQuery, name => Headers.TryGetValue(name, out var v) ? v : null); + } + } + + private static Request BrowserPage(bool connectionIsLocal, string host) + => new Request { ConnectionIsLocal = connectionIsLocal, Host = host } + .With("Origin", $"http://{host}").With("Sec-Fetch-Site", "same-origin"); + + private static Request KspComputerAtLocalhost() => BrowserPage(true, "localhost:8080"); + private static Request KspComputerAtItsNetworkAddress() => BrowserPage(true, "192.168.1.10:8080"); + private static Request PhoneOnWifi() => BrowserPage(false, "192.168.1.10:8080"); + private static Request PhoneOnTailscaleIp() => BrowserPage(false, "100.68.55.4:8080"); + + private static Request PhoneThroughTailscaleServe() + => BrowserPage(true, "gamepc.tail1234.ts.net").With("X-Forwarded-For", "100.101.102.103"); + + private static Request StreamDeckOnAnotherComputer() => new Request { ConnectionIsLocal = false, Host = "192.168.1.10:8080" }; + + private static Request OtherWebsiteInThePhonesBrowser() + => new Request { ConnectionIsLocal = false, Host = "192.168.1.10:8080" } + .With("Origin", "https://evil.example").With("Sec-Fetch-Site", "cross-site"); + + private static Request ViteDevServerOnTheKspComputer() + => new Request { ConnectionIsLocal = true, Host = "localhost:8080" } + .With("Origin", "http://localhost:5173").With("Sec-Fetch-Site", "same-site"); + + [Fact] + public void WithTheKeyOffEveryDeviceMayChangeThings() + { + Assert.Equal(WriteVerdict.Allowed, PhoneOnWifi().Check(requireKey: false)); + Assert.Equal(WriteVerdict.Allowed, PhoneOnTailscaleIp().Check(requireKey: false)); + Assert.Equal(WriteVerdict.Allowed, PhoneThroughTailscaleServe().Check(requireKey: false)); + Assert.Equal(WriteVerdict.Allowed, StreamDeckOnAnotherComputer().Check(requireKey: false)); + } + + [Fact] + public void OtherWebsitesAreBlockedWithOrWithoutTheKey() + { + Assert.Equal(WriteVerdict.OtherWebsite, OtherWebsiteInThePhonesBrowser().Check(requireKey: false)); + Assert.Equal(WriteVerdict.OtherWebsite, OtherWebsiteInThePhonesBrowser().Check(requireKey: true)); + Assert.Equal(WriteVerdict.OtherWebsite, OtherWebsiteInThePhonesBrowser().With("Authorization", $"Bearer {Key}").Check(requireKey: true)); + } + + [Fact] + public void TheKspComputerAtLocalhostNeverNeedsTheKey() + { + Assert.Equal(WriteVerdict.Allowed, KspComputerAtLocalhost().Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, ViteDevServerOnTheKspComputer().Check(requireKey: true)); + } + + [Fact] + public void TheKspComputerAtItsNetworkAddressNeedsTheKey() + { + Assert.Equal(WriteVerdict.NeedsKey, KspComputerAtItsNetworkAddress().Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, KspComputerAtItsNetworkAddress().With("Authorization", $"Bearer {Key}").Check(requireKey: true)); + } + + [Fact] + public void PhonesNeedTheKey() + { + Assert.Equal(WriteVerdict.NeedsKey, PhoneOnWifi().Check(requireKey: true)); + Assert.Equal(WriteVerdict.NeedsKey, PhoneOnTailscaleIp().Check(requireKey: true)); + Assert.Equal(WriteVerdict.NeedsKey, PhoneOnWifi().With("Authorization", "Bearer ABCDEFGHJ3").Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, PhoneOnWifi().With("Authorization", $"Bearer {Key}").Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, PhoneOnTailscaleIp().With("Authorization", $"Bearer {Key.ToLowerInvariant()}").Check(requireKey: true)); + } + + [Fact] + public void TailscaleServeDoesNotCountAsTheKspComputer() + { + Assert.Equal(WriteVerdict.NeedsKey, PhoneThroughTailscaleServe().Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, PhoneThroughTailscaleServe().With("Authorization", $"Bearer {Key}").Check(requireKey: true)); + } + + [Fact] + public void StreamDeckLinksCarryTheKeyInTheAddress() + { + Assert.Equal(WriteVerdict.NeedsKey, StreamDeckOnAnotherComputer().Check(requireKey: true)); + Assert.Equal(WriteVerdict.Allowed, StreamDeckOnAnotherComputer().WithKeyQuery(Key).Check(requireKey: true)); + } + } +} diff --git a/Tests/JRTI.Tests/ApiAccessTests.cs b/Tests/JRTI.Tests/ApiAccessTests.cs index 887f1f2..68177e6 100644 --- a/Tests/JRTI.Tests/ApiAccessTests.cs +++ b/Tests/JRTI.Tests/ApiAccessTests.cs @@ -51,6 +51,40 @@ public void ComparesKeys(string provided, bool matches) public void RecognisesLocalhostOrigins(string origin, bool local) => Assert.Equal(local, ApiAccess.IsLocalhostOrigin(origin)); + [Theory] + [InlineData(null, true)] + [InlineData("localhost:8080", true)] + [InlineData("127.0.0.1:8080", true)] + [InlineData("[::1]:8080", true)] + [InlineData("192.168.1.10:8080", true)] + [InlineData("100.64.0.7", true)] + [InlineData("gamepc:8080", true)] + [InlineData("GamePC.local:8080", true)] + [InlineData("gamepc.tail1234.ts.net", true)] + [InlineData("cams.example.org:8080", true)] + [InlineData("other.lan", true)] + [InlineData("ts.net.evil.example", false)] + [InlineData("evil.example:8080", false)] + [InlineData("gamepc.evil.example:8080", false)] + [InlineData("127.0.0.1.evil.example", false)] + [InlineData("evil.example/@127.0.0.1", false)] + [InlineData("user@127.0.0.1", false)] + public void AllowsOnlyKnownHostNames(string host, bool allowed) + => Assert.Equal(allowed, ApiAccess.IsAllowedHost(host, "GAMEPC", "cams.example.org, other.lan")); + + [Theory] + [InlineData(true, "localhost:8080", null, true)] + [InlineData(true, "127.0.0.1:8080", null, true)] + [InlineData(true, "[::1]:8080", null, true)] + [InlineData(false, "localhost:8080", null, false)] + [InlineData(true, "192.168.1.10:8080", null, false)] + [InlineData(true, "gamepc.tail1234.ts.net", null, false)] + [InlineData(true, null, null, false)] + [InlineData(true, "localhost:8080", "X-Forwarded-For", false)] + [InlineData(true, "localhost:8080", "Forwarded", false)] + public void SkipsTheKeyOnlyForDirectLocalRequests(bool connectionIsLocal, string host, string proxyHeader, bool local) + => Assert.Equal(local, ApiAccess.IsDirectFromThisComputer(connectionIsLocal, host, name => name == proxyHeader ? "203.0.113.5" : null)); + [Theory] [InlineData(null, null, false)] [InlineData("none", null, false)] diff --git a/Tools/mock-server.mjs b/Tools/mock-server.mjs index e6482f8..51ff768 100644 --- a/Tools/mock-server.mjs +++ b/Tools/mock-server.mjs @@ -1,5 +1,7 @@ import http from 'node:http'; import fs from 'node:fs'; +import os from 'node:os'; +import net from 'node:net'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; @@ -20,6 +22,9 @@ const OPENAPI_FILE = path.join(DOCS, 'openapi.json'); const PLUGIN_DATA = path.join(ROOT, 'GameData', 'JustReadTheInstructions', 'PluginData'); const MOCK_KEY = process.env.MOCK_KEY?.trim().toUpperCase(); const PREFLIGHT_MAX_AGE_S = 600; +const MOCK_ALLOWED_HOSTS = (process.env.MOCK_ALLOWED_HOSTS ?? '').split(/[, ]+/).filter(Boolean).map((h) => h.toLowerCase()); +const PROXY_HEADERS = ['x-forwarded-for', 'x-forwarded-host', 'x-real-ip', 'forwarded']; +const TAILSCALE_SUFFIX = '.ts.net'; const FEEDS = [ [10, 'screenshot-3.png', 'crop=2320:1305:160:100'], @@ -193,19 +198,18 @@ function writePart(res, jpeg, id) { res.write('\r\n'); } -function stream(req, res, ids, preview) { +function stream(req, res, ids, preview, tagged) { const cams = ids.map((id) => cameras.get(id)).filter((c) => c?.online); if (cams.length === 0) return text(res, 404, 'No matching cameras'); res.writeHead(200, { 'Content-Type': `multipart/x-mixed-replace; boundary=${BOUNDARY}`, 'Cache-Control': 'no-cache' }); const key = preview ? 'previewClients' : 'streamClients'; for (const c of cams) c[key]++; - const multi = ids.length > 1 || req.url.startsWith('/streams'); const timer = setInterval(() => { let any = false; for (const c of cams) { if (!c.online) continue; any = true; - writePart(res, frameFor(c.id), multi ? c.id : null); + writePart(res, frameFor(c.id), tagged ? c.id : null); } if (!any) { clearInterval(timer); res.end(); } }, 1000 / FPS); @@ -323,9 +327,46 @@ function isLocalhostOrigin(origin) { } } +function hostName(hostHeader) { + try { + return new URL(`http://${hostHeader}`).hostname.replace(/^\[|\]$/g, '').toLowerCase(); + } catch { + return null; + } +} + +function isLoopbackName(name) { + return name === 'localhost' || name.endsWith('.localhost') || name === '::1' || /^127\./.test(name); +} + +function isAllowedHost(hostHeader) { + if (!hostHeader) return true; + const name = hostName(hostHeader); + if (!name) return false; + if (net.isIP(name) || isLoopbackName(name) || name.endsWith(TAILSCALE_SUFFIX)) return true; + const machine = os.hostname().toLowerCase(); + return [...MOCK_ALLOWED_HOSTS, machine, `${machine}.local`].includes(name); +} + +function isDirectFromThisComputer(req) { + const remote = req.socket.remoteAddress?.replace(/^::ffff:/, '') ?? ''; + const local = req.socket.localAddress?.replace(/^::ffff:/, '') ?? ''; + const name = hostName(req.headers.host ?? ''); + return (remote === local || isLoopbackName(remote)) && Boolean(name) && isLoopbackName(name) + && PROXY_HEADERS.every((header) => !req.headers[header]); +} + +function isSameOrigin(origin, hostHeader) { + try { + return new URL(origin).host.toLowerCase() === (hostHeader ?? '').toLowerCase(); + } catch { + return false; + } +} + function isBlockedCrossSite(req) { const origin = req.headers.origin; - if (!origin || origin === `http://${req.headers.host}` || isLocalhostOrigin(origin)) return req.headers['sec-fetch-site'] === 'cross-site' && !origin; + if (!origin || isSameOrigin(origin, req.headers.host) || isLocalhostOrigin(origin)) return req.headers['sec-fetch-site'] === 'cross-site' && !origin; return true; } @@ -397,6 +438,7 @@ const server = http.createServer(async (req, res) => { const origin = req.headers.origin; const cors = Boolean(origin) && isLocalhostOrigin(origin) && origin !== `http://${req.headers.host}`; try { + if (!isAllowedHost(req.headers.host)) return text(res, 403, "This name is not allowed here. Use the computer's IP address, or add the name to AllowedHosts in PluginData/settings.cfg"); if (cors) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); @@ -412,7 +454,7 @@ const server = http.createServer(async (req, res) => { } if (isWrite(req.method, p)) { if (isBlockedCrossSite(req)) return text(res, 403, 'Pages from other websites cannot change anything here'); - if (MOCK_KEY && providedKey(req, url) !== MOCK_KEY) { + if (MOCK_KEY && !isDirectFromThisComputer(req) && providedKey(req, url) !== MOCK_KEY) { res.setHeader('WWW-Authenticate', 'Bearer realm="JRTI"'); return text(res, 401, "This needs the control key shown in the game's JRTI settings"); } @@ -434,7 +476,7 @@ const server = http.createServer(async (req, res) => { } return text(res, 404, 'Use GET /program, /program/take/ or /program/clear'); } - if (p === '/streams') return stream(req, res, (url.searchParams.get('ids') ?? '').split(',').map(Number), url.searchParams.get('preview') === '1'); + if (p === '/streams') return stream(req, res, (url.searchParams.get('ids') ?? '').split(',').map(Number), url.searchParams.get('preview') === '1', true); if (parts[0] === 'mock' && parts[1] === 'toggle') { const cam = cameras.get(Number(parts[2])); if (cam) cam.online = !cam.online; diff --git a/docs/api.md b/docs/api.md index 501f90e..4b5a275 100644 --- a/docs/api.md +++ b/docs/api.md @@ -44,12 +44,12 @@ The older short addresses without `/api/v1` (such as `http://localhost:8080/came The API listens on your network like the web UI, with nothing to set up. To check a flight from your phone while you are away, use a private network such as [Tailscale](https://tailscale.com/) and open the computer's Tailscale address with the port. -!!! warning "Do not port-forward it" - Without a control key, anyone who can reach the port can watch your cameras, change their settings and start recordings. Forwarding the port on your router puts it on the whole internet. Use a private network such as Tailscale instead. +!!! warning "Do not put it on the internet" + Without a control key, anyone who can reach the port can watch your cameras, change their settings and start recordings. Forwarding the port on your router puts it on the whole internet, and so does **Tailscale Funnel**. Plain Tailscale, or `tailscale serve`, only reaches your own devices: use that instead. ### Control key -Watching is always open. To stop other devices from changing anything, tick **Require a key to control from other devices** in the settings window (see [Settings](settings.md#stream-capture)). From then on, changing camera settings, recording, saving or deleting layouts and switching what is on air need the key, except from the KSP computer itself. +Watching is always open. To stop other devices from changing anything, tick **Require a key to control from other devices** in the settings window (see [Settings](settings.md#stream-capture)). From then on, changing camera settings, recording, saving or deleting layouts and switching what is on air need the key, except on the KSP computer itself when the page is opened as `localhost` or `127.0.0.1`. Through its network address, or through a proxy such as `tailscale serve`, the KSP computer needs the key like any other device. * In the web UI, open the link from **Copy link** once on each device, or type the key when the page asks. The browser remembers it. * In your own app, send it as `Authorization: Bearer `, or add `?key=` to the address (handy for Stream Deck buttons). @@ -57,6 +57,28 @@ Watching is always open. To stop other devices from changing anything, tick **Re A request without the right key gets `401`. Routes that need the key are marked `writes: true` in `/api/v1` and carry a `security` entry in the OpenAPI document. +### What stays open + +The key only protects changes. Anyone who can reach the port can still: + +* watch and listen to every streaming camera, +* play and download your recordings, +* read the layouts, what is on air, the performance numbers and the computer's network addresses (from `/session`). + +So keep the port on networks you trust, even with the key on. + +Without the key, one more thing is possible: in an old browser, a page from another website could open `/program/take/` or `/program/clear` and switch what is on air. Current Chrome, Edge, Firefox and Safari block this. Turn on the key if that matters to you. + +### Opening it by name + +The game answers to `localhost`, to any IP address, to the computer's own name (`my-pc` or `my-pc.local`) and to Tailscale names (ending in `.ts.net`). Any other name gets `403`, so a website cannot point its own name at your computer to reach the feeds. + +To use another name, add it to `AllowedHosts` in `GameData/JustReadTheInstructions/PluginData/settings.cfg` and restart the game. Separate several names with commas: + +```text +AllowedHosts = cams.example.org +``` + ## Building a web page Web pages from other websites cannot change anything here (they get `403`), so a page you find online cannot start recordings or switch your layouts behind your back. Your own pages work from two places: @@ -66,6 +88,9 @@ Web pages from other websites cannot change anything here (they get `403`), so a A page opened straight from a file (`file://`) cannot change anything: put it in the Apps folder instead. +!!! warning "Apps have full control" + A page in the Apps folder is served by the game like the bundled web UI, so it can do everything the web UI does, including using the key a browser has remembered. Only add apps you trust, as you would a mod. + ## Changing the web UI To change one of the bundled pages, copy it from `GameData/JustReadTheInstructions/Web/` into `GameData/JustReadTheInstructions/PluginData/Web/` at the same place, and edit the copy. A file there replaces the shipped one, for example `PluginData/Web/css/styles.css` or `PluginData/Web/images/los.png`. Updates never overwrite it. diff --git a/docs/settings.md b/docs/settings.md index 6078ab4..cddf82e 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -46,6 +46,8 @@ If another program already uses the port, JRTI says so on screen and in `KSP.log Settings are saved in `GameData/JustReadTheInstructions/PluginData/settings.cfg`. Defaults live in the mod itself, so updates never reset your choices. +One setting is only in the file: `AllowedHosts`, the extra names the web UI answers to besides `localhost`, IP addresses, the computer's name and Tailscale names. See [API](api.md#opening-it-by-name). + Per-camera sound choices are in `PluginData/camera-sound.cfg`, and saved layouts in `PluginData/Layouts/`. Your own pages go in `PluginData/Apps/` and changed copies of the web UI in `PluginData/Web/` (see [API](api.md#building-a-web-page)). ## Visual mods diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 05c63cc..1f567f6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -10,6 +10,8 @@ JRTI's page is `http://localhost:8080/` unless you changed the port. If the page JRTI usually warns you about this on screen when the game opens, and writes it to `KSP.log`. To fix it, pick another **Port** in JRTI's settings (`Ctrl` + `Alt` + `F8`), then restart the game. +If the page says the name is not allowed, open it by IP address or add the name to `AllowedHosts` (see [API](api.md#opening-it-by-name)). + If it works on the KSP computer but not from another device, use the network address shown at the bottom of the web UI instead of `localhost`, and check that the computer's firewall lets the game accept connections. On Windows, allow `KSP_x64.exe` through Windows Defender Firewall (Windows Security, Firewall & network protection, Allow an app through firewall, Allow another app), making sure the rule covers your network's Private profile. Or open the port from an administrator command prompt, replacing `8080` with your port: ```text From 269dbc0cf747ec4ab04f3a70b537bf500bc5d5e9 Mon Sep 17 00:00:00 2001 From: RELMYMathieu Date: Wed, 25 Nov 2026 23:32:08 +0100 Subject: [PATCH 3/4] refact: api touchups pre-merge, regen openapi schema --- CHANGELOG.md | 13 +- .../JustReadTheInstructions/Web/js/viewer.js | 3 +- Source/ApiCatalog.cs | 62 ++++- Source/ApiSchema.cs | 7 +- Source/JRTIStreamServer.GameRecording.cs | 21 +- Source/JRTIStreamServer.Http.cs | 6 +- Source/JRTIStreamServer.Layouts.cs | 5 +- Source/JRTIStreamServer.Routes.cs | 2 + Tests/JRTI.Tests/ApiCatalogTests.cs | 11 + Tools/check-routes.mjs | 2 +- Tools/mock-server.mjs | 34 ++- docs/api.md | 20 +- docs/openapi.json | 231 +++++++++++++++++- 13 files changed, 359 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a8401bb..3278988 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,17 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Web API (`/api/v1`) - every web UI route is also served under `/api/v1`, and `/api/v1` lists them all with the mod version and features, so other apps and pages can build on the same feeds. The old addresses keep working -- OpenAPI document (`/api/v1/openapi.json`, docs site) - every route with its request and response fields, to generate clients in any language -- Control key (Settings, Stream / Capture) - optional: other devices can still watch, but need the key to change settings, record or switch layouts. Copy link opens the web UI on another device with the key remembered -- Your own pages (`PluginData/Apps/`) - a folder there opens at `/apps//`, served by the game and kept across updates -- Web UI changes that survive updates (`PluginData/Web/`) - a file there replaces the shipped one of the same path - -### Changed - -- Web pages from other websites can no longer change camera settings, recordings or layouts. Pages served from localhost (development servers) can use the API from the browser -- Allowed names (`AllowedHosts` in `PluginData/settings.cfg`) - the web UI only answers to localhost, IP addresses, the computer's name, Tailscale names and the names listed there, so a website cannot reach it under its own name -- Control key - the KSP computer skips the key only when opened as localhost, not through its network address or a local proxy +- Web API (`/api/v1`) - This allows you to make your own apps, pages and overlays on the same JRTI feeds as the default proposed interface, with an optional control key for other devices if need be. Pages from other websites can no longer change anything, as a security measure. See the API page of the docs for more information +- Your can now make your own pages and styles (`PluginData/Apps/`, `PluginData/Web/`) ## v3.3.0 - 2026-11-11 diff --git a/GameData/JustReadTheInstructions/Web/js/viewer.js b/GameData/JustReadTheInstructions/Web/js/viewer.js index 0b998a4..6ab033b 100644 --- a/GameData/JustReadTheInstructions/Web/js/viewer.js +++ b/GameData/JustReadTheInstructions/Web/js/viewer.js @@ -111,7 +111,8 @@ function main() { if (recordingBusy) return; recordingBusy = true; try { - recording = await gameRecording(cameraId, action, action === 'start' ? selectedGameCodec() : undefined); + const result = await gameRecording(cameraId, action, action === 'start' ? selectedGameCodec() : undefined); + recording = action === 'stop' ? null : result; if (action === 'stop') toast('Recording saved on the KSP computer'); } catch { toast(`Could not ${action} the recording`); diff --git a/Source/ApiCatalog.cs b/Source/ApiCatalog.cs index 1ce5e00..79712ab 100644 --- a/Source/ApiCatalog.cs +++ b/Source/ApiCatalog.cs @@ -45,6 +45,7 @@ public sealed class ApiOperation public string Method { get; } public string Template { get; } public string Summary { get; } + public string Description { get; set; } public string[] AlsoAccepts { get; set; } = new string[0]; public bool Writes { get; set; } public bool VersionedOnly { get; set; } @@ -108,8 +109,10 @@ public static class ApiCatalog new ApiField("name", String), new ApiField("streaming", Boolean), new ApiField("viewerCount", Integer), - new ApiField("snapshotUrl", String), - new ApiField("streamUrl", String), + new ApiField("snapshotUrl", String, description: "Latest JPEG frame"), + new ApiField("videoUrl", String, description: "MJPEG stream at render size"), + new ApiField("previewUrl", String, description: "MJPEG stream at preview size"), + new ApiField("streamUrl", String, description: "The viewer page for people, not the video: use videoUrl for the stream"), new ApiField("mic", Mic), new ApiField("canPan", Boolean), new ApiField("track", Track), @@ -162,6 +165,13 @@ public static class ApiCatalog ["Program"] = Object( new ApiField("layout", Nullable(String)), new ApiField("version", Integer)), + ["StoppedRecording"] = Object( + new ApiField("file", String), + new ApiField("saved", Boolean, description: "False when discarded"), + new ApiField("framesWritten", Integer), + new ApiField("framesDropped", Integer)), + ["LayoutEvent"] = Object( + new ApiField("name", String, description: "The layout that was saved or deleted")), ["LayoutEntry"] = Object( new ApiField("name", String), new ApiField("updated", DateTime)), @@ -192,7 +202,12 @@ public static class ApiCatalog Response = ApiResponse.Binary("multipart/x-mixed-replace", "JPEG frames"), }, new ApiOperation("getEvents", "GET", "/events", "Server-Sent Events: program (the layout on air) and layout (a saved layout changed)") - { Response = ApiResponse.Binary("text/event-stream", "Events, with a ping comment every 15 seconds") }, + { + Description = "Each message is either event: program, whose data is a Program, sent once on connect and on every change, " + + "or event: layout, whose data is a LayoutEvent, sent when a saved layout is saved or deleted. " + + "A comment line keeps the connection open every 15 seconds.", + Response = ApiResponse.Binary("text/event-stream", "Events"), + }, new ApiOperation("getDebugStats", "GET", "/debug/stats", "Latest performance sample") { Response = ApiResponse.Json(AnyObject) }, new ApiOperation("getProgram", "GET", "/program", "The layout on air") @@ -202,7 +217,11 @@ public static class ApiCatalog new ApiOperation("clearProgram", "POST", "/program/clear", "Takes the program off air. Also answers GET, for links") { AlsoAccepts = new[] { "GET" }, Writes = true, Response = ApiResponse.Json(Ref("Program")) }, new ApiOperation("listLayouts", "GET", "/layouts", "Saved layouts") - { Response = ApiResponse.Json(ArrayOf(Ref("LayoutEntry"))) }, + { + Description = "Sorted by name, ignoring case and comparing character codes, so the order is the same everywhere. " + + "The web UI's Shift+1 to 9 take the layouts in this order.", + Response = ApiResponse.Json(ArrayOf(Ref("LayoutEntry"))), + }, new ApiOperation("getLayout", "GET", "/layouts/{layout}", "One saved layout, as saved by the layout page") { Path = new[] { LayoutName }, Response = ApiResponse.Json(AnyObject) }, new ApiOperation("saveLayout", "PUT", "/layouts/{layout}", "Saves a layout: a JSON object of 64 KB at most. Also answers POST") @@ -230,13 +249,32 @@ public static class ApiCatalog new ApiOperation("getCameraSettings", "GET", "/camera/{id}/settings", "Image, sound, field of view and pan settings") { Path = new[] { CameraId }, Response = ApiResponse.Json(Ref("CameraSettings")) }, new ApiOperation("changeCameraSettings", "POST", "/camera/{id}/settings", "Changes any of the listed fields and leaves the others alone") - { Writes = true, Path = new[] { CameraId }, Body = Ref("CameraSettingsChange"), Response = ApiResponse.Empty(200, "Changed") }, - new ApiOperation("controlRecording", "POST", "/camera/{id}/recording/{action}", "Starts, stops, discards, pauses or resumes the in-game recording") { Writes = true, - Path = new[] { CameraId, new ApiParameter("action", Enum("start", "stop", "discard", "pause", "resume"), "What to do") }, + Path = new[] { CameraId }, + Body = Ref("CameraSettingsChange"), + Description = "Values out of range are clamped and unknown fields are ignored. A field of view change shows in the answer from the next frame on.", + Response = ApiResponse.Json(Ref("CameraSettings"), "The settings after the change"), + }, + new ApiOperation("stopRecording", "POST", "/camera/{id}/recording/stop", "Stops and saves the in-game recording") + { + Writes = true, + Path = new[] { CameraId }, + Description = "The file is finished a moment later and then appears in /recordings with its size.", + Response = ApiResponse.Json(Nullable(Ref("StoppedRecording")), "The stopped recording, or null when nothing was recording"), + }, + new ApiOperation("discardRecording", "POST", "/camera/{id}/recording/discard", "Stops the in-game recording and deletes the file") + { + Writes = true, + Path = new[] { CameraId }, + Response = ApiResponse.Json(Nullable(Ref("StoppedRecording")), "The discarded recording, or null when nothing was recording"), + }, + new ApiOperation("controlRecording", "POST", "/camera/{id}/recording/{action}", "Starts, pauses or resumes the in-game recording") + { + Writes = true, + Path = new[] { CameraId, new ApiParameter("action", Enum("start", "pause", "resume"), "What to do") }, Query = new[] { new ApiParameter("codec", Codec, "Codec for start, h264 by default") }, - Response = ApiResponse.Json(Nullable(Ref("Recording")), "The recording, or null once stopped"), + Response = ApiResponse.Json(Nullable(Ref("Recording")), "The recording, or null when none is running"), }, }; @@ -265,6 +303,9 @@ public static string Build(IEnumerable operations, IReadOnlyDictio return Json.Pretty(json.ToString()); } + private const string ReadForbidden = "The address used a name the game does not answer to (see AllowedHosts)"; + private const string WriteForbidden = ReadForbidden + ", or the request came from a web page on another website"; + private static string OperationJson(ApiOperation op) { var parameters = op.Path.Select(p => ParameterJson(p, "path", true)) @@ -273,11 +314,12 @@ private static string OperationJson(ApiOperation op) var json = new StringBuilder($"{Quote(op.Method.ToLowerInvariant())}:{{"); json.Append($"\"operationId\":{Quote(op.Id)},\"summary\":{Quote(op.Summary)}"); + if (op.Description != null) json.Append($",\"description\":{Quote(op.Description)}"); if (parameters.Count > 0) json.Append($",\"parameters\":[{string.Join(",", parameters)}]"); if (op.Body != null) json.Append($",\"requestBody\":{{\"required\":true,\"content\":{{\"application/json\":{{\"schema\":{op.Body}}}}}}}"); json.Append($",\"responses\":{{{ResponseJson(op.Response)}"); - if (op.Writes) - json.Append(",\"401\":{\"description\":\"The control key is required and missing or wrong\"},\"403\":{\"description\":\"Sent by a web page from another site\"}"); + if (op.Writes) json.Append(",\"401\":{\"description\":\"The control key is required and missing or wrong\"}"); + json.Append($",\"403\":{{\"description\":{Quote(op.Writes ? WriteForbidden : ReadForbidden)}}}"); json.Append('}'); if (op.Writes) json.Append(",\"security\":[{},{\"controlKey\":[]}]"); return json.Append('}').ToString(); diff --git a/Source/ApiSchema.cs b/Source/ApiSchema.cs index 6805aa7..274c3bc 100644 --- a/Source/ApiSchema.cs +++ b/Source/ApiSchema.cs @@ -10,10 +10,10 @@ public sealed class ApiField public ApiSchema Schema { get; } public bool Required { get; } - public ApiField(string name, ApiSchema schema, bool required = true) + public ApiField(string name, ApiSchema schema, bool required = true, string description = null) { Name = name; - Schema = schema; + Schema = description == null ? schema : schema.WithDescription(description); Required = required; } } @@ -31,6 +31,9 @@ public sealed class ApiSchema public static readonly ApiSchema DateTime = new ApiSchema("{\"type\":\"string\",\"format\":\"date-time\"}"); public static readonly ApiSchema AnyObject = new ApiSchema("{\"type\":\"object\",\"additionalProperties\":true}"); + public ApiSchema WithDescription(string description) + => new ApiSchema($"{{\"description\":{Quote(description)},{_json.Substring(1)}"); + public static ApiSchema Ref(string component) => new ApiSchema($"{{\"$ref\":\"#/components/schemas/{component}\"}}"); public static ApiSchema ArrayOf(ApiSchema items) => new ApiSchema($"{{\"type\":\"array\",\"items\":{items._json}}}"); diff --git a/Source/JRTIStreamServer.GameRecording.cs b/Source/JRTIStreamServer.GameRecording.cs index 92bd705..56ed6d0 100644 --- a/Source/JRTIStreamServer.GameRecording.cs +++ b/Source/JRTIStreamServer.GameRecording.cs @@ -19,8 +19,6 @@ private static void HandleGameRecording(HttpListenerContext ctx, int cameraId, C switch (action) { case "start": StartGameRecording(ctx, cameraId, state); break; - case "stop": StopGameRecording(ctx, state, discard: false); break; - case "discard": StopGameRecording(ctx, state, discard: true); break; case "pause": state.Recorder?.Pause(); ServeText(ctx, RecordingJson(state), "application/json"); break; case "resume": state.Recorder?.Resume(); ServeText(ctx, RecordingJson(state), "application/json"); break; default: ServeError(ctx, 404, "Unknown recording action"); break; @@ -76,14 +74,21 @@ private static void StartGameRecording(HttpListenerContext ctx, int cameraId, Ca private static void StopGameRecording(HttpListenerContext ctx, CameraStreamState state, bool discard) { var recorder = state.TakeRecorder(); - if (recorder != null) + if (recorder == null) { - if (discard) recorder.Discard(); - else recorder.Stop(); - Debug.Log($"[JRTI-Stream]: In-game recording {(discard ? "discarded" : "saved")}: {recorder.FilePath} " + - $"({recorder.FramesWritten} frames, {recorder.FramesDropped} dropped)"); + ServeText(ctx, "null", "application/json"); + return; } - ServeText(ctx, RecordingJson(state), "application/json"); + + if (discard) recorder.Discard(); + else recorder.Stop(); + Debug.Log($"[JRTI-Stream]: In-game recording {(discard ? "discarded" : "saved")}: {recorder.FilePath} " + + $"({recorder.FramesWritten} frames, {recorder.FramesDropped} dropped)"); + + ServeText(ctx, + $"{{\"file\":\"{EscapeJson(Path.GetFileName(recorder.FilePath))}\",\"saved\":{(discard ? "false" : "true")}," + + $"\"framesWritten\":{recorder.FramesWritten},\"framesDropped\":{recorder.FramesDropped}}}", + "application/json"); } private static string UniquePath(string requested) diff --git a/Source/JRTIStreamServer.Http.cs b/Source/JRTIStreamServer.Http.cs index 12ab6ce..6185130 100644 --- a/Source/JRTIStreamServer.Http.cs +++ b/Source/JRTIStreamServer.Http.cs @@ -111,7 +111,8 @@ private void ServeCameraList(HttpListenerContext ctx) int id = kv.Key; string name = kv.Value.DisplayName ?? id.ToString(); sb.Append($"{{\"id\":{id},\"name\":\"{EscapeJson(name)}\",\"streaming\":true,\"viewerCount\":{kv.Value.MjpegClientCount},") - .Append($"\"snapshotUrl\":\"/camera/{id}/snapshot\",\"streamUrl\":\"/viewer.html?id={id}\",\"mic\":\"{CameraMics.Id(kv.Value.Mic)}\",") + .Append($"\"snapshotUrl\":\"{ApiRouter.VersionPrefix}/camera/{id}/snapshot\",\"videoUrl\":\"{ApiRouter.VersionPrefix}/camera/{id}/stream\",") + .Append($"\"previewUrl\":\"{ApiRouter.VersionPrefix}/camera/{id}/preview\",\"streamUrl\":\"/viewer.html?id={id}\",\"mic\":\"{CameraMics.Id(kv.Value.Mic)}\",") .Append($"\"canPan\":{(kv.Value.Aim.CanPan ? "true" : "false")},\"track\":\"{CameraTracks.Id(kv.Value.Aim.Track)}\",") .Append($"\"recording\":{RecordingJson(kv.Value)}}}"); first = false; @@ -289,8 +290,7 @@ private static void UpdateCameraSettings(HttpListenerContext ctx, CameraStreamSt state.Mastering = mastering; UpdateAim(body, state.Aim); - ctx.Response.StatusCode = 200; - ctx.Response.Close(); + ServeCameraSettings(ctx, state); } private static void ServeCameraSettings(HttpListenerContext ctx, CameraStreamState state) diff --git a/Source/JRTIStreamServer.Layouts.cs b/Source/JRTIStreamServer.Layouts.cs index 24ec456..3abae42 100644 --- a/Source/JRTIStreamServer.Layouts.cs +++ b/Source/JRTIStreamServer.Layouts.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; @@ -34,8 +35,8 @@ private static void ServeLayoutList(HttpListenerContext ctx) { if (Directory.Exists(LayoutsRoot)) { - var files = Directory.GetFiles(LayoutsRoot, "*.json"); - Array.Sort(files, StringComparer.OrdinalIgnoreCase); + var files = Directory.GetFiles(LayoutsRoot, "*.json") + .OrderBy(Path.GetFileNameWithoutExtension, StringComparer.OrdinalIgnoreCase); foreach (var file in files) { var updated = File.GetLastWriteTimeUtc(file).ToString("o", CultureInfo.InvariantCulture); diff --git a/Source/JRTIStreamServer.Routes.cs b/Source/JRTIStreamServer.Routes.cs index 085d927..27cf282 100644 --- a/Source/JRTIStreamServer.Routes.cs +++ b/Source/JRTIStreamServer.Routes.cs @@ -46,6 +46,8 @@ public partial class JRTIStreamServer ["getCameraStatus"] = ForCamera((ctx, id, state, _) => ServeText(ctx, "ok", "text/plain")), ["getCameraSettings"] = ForCamera((ctx, id, state, _) => ServeCameraSettings(ctx, state)), ["changeCameraSettings"] = ForCamera((ctx, id, state, _) => UpdateCameraSettings(ctx, state)), + ["stopRecording"] = ForCamera((ctx, id, state, _) => StopGameRecording(ctx, state, discard: false)), + ["discardRecording"] = ForCamera((ctx, id, state, _) => StopGameRecording(ctx, state, discard: true)), ["controlRecording"] = ForCamera((ctx, id, state, v) => HandleGameRecording(ctx, id, state, v["action"])), }; diff --git a/Tests/JRTI.Tests/ApiCatalogTests.cs b/Tests/JRTI.Tests/ApiCatalogTests.cs index 3de2a36..22ea122 100644 --- a/Tests/JRTI.Tests/ApiCatalogTests.cs +++ b/Tests/JRTI.Tests/ApiCatalogTests.cs @@ -46,6 +46,17 @@ public void EveryReferencedComponentExists() Assert.All(references, name => Assert.True(ApiCatalog.Components.ContainsKey(name), name)); } + [Theory] + [InlineData("/camera/10/recording/stop", "stopRecording")] + [InlineData("/camera/10/recording/discard", "discardRecording")] + [InlineData("/camera/10/recording/start", "controlRecording")] + public void RecordingActionsReachTheirOwnRoute(string path, string expected) + { + var routes = ApiCatalog.Operations.Select(op => new ApiRoute(op, (ctx, v) => { })); + ApiRouter.Resolve(routes, "POST", path, out var route, out _, out _); + Assert.Equal(expected, route.Operation.Id); + } + [Fact] public void PublishedOpenApiDocumentIsCurrent() { diff --git a/Tools/check-routes.mjs b/Tools/check-routes.mjs index 26edd50..073e01d 100644 --- a/Tools/check-routes.mjs +++ b/Tools/check-routes.mjs @@ -11,7 +11,7 @@ const START_TIMEOUT_MS = 60000; const REQUEST_TIMEOUT_MS = 5000; const UNKNOWN_ROUTE = 'Unknown route'; -const SAMPLES = { id: '10', layout: 'RouteCheck', file: 'route-check.mp4', action: 'stop' }; +const SAMPLES = { id: '10', layout: 'RouteCheck', file: 'route-check.mp4', action: 'pause' }; const BODIES = { saveLayout: '{}', changeCameraSettings: '{}' }; function startMock() { diff --git a/Tools/mock-server.mjs b/Tools/mock-server.mjs index 51ff768..ecd833e 100644 --- a/Tools/mock-server.mjs +++ b/Tools/mock-server.mjs @@ -25,6 +25,8 @@ const PREFLIGHT_MAX_AGE_S = 600; const MOCK_ALLOWED_HOSTS = (process.env.MOCK_ALLOWED_HOSTS ?? '').split(/[, ]+/).filter(Boolean).map((h) => h.toLowerCase()); const PROXY_HEADERS = ['x-forwarded-for', 'x-forwarded-host', 'x-real-ip', 'forwarded']; const TAILSCALE_SUFFIX = '.ts.net'; +const MOD_VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'GameData', 'JustReadTheInstructions', 'JustReadTheInstructions.version'), 'utf8')).VERSION; +const SETTING_RANGES = { brightness: [-1, 1], contrast: [0, 3], gamma: [0.1, 5], soundGain: [-24, 24] }; const FEEDS = [ [10, 'screenshot-3.png', 'crop=2320:1305:160:100'], @@ -188,7 +190,7 @@ function recordingInfo(cam) { function cameraList() { return [...cameras.values()].filter((c) => c.online).map((c) => ({ id: c.id, name: c.name, streaming: true, viewerCount: c.streamClients, - snapshotUrl: `/camera/${c.id}/snapshot`, streamUrl: `/viewer.html?id=${c.id}`, mic: c.settings.mic, canPan: Boolean(c.pan), track: c.pan?.track ?? 'off', recording: recordingInfo(c), + snapshotUrl: `${API_PREFIX}/camera/${c.id}/snapshot`, videoUrl: `${API_PREFIX}/camera/${c.id}/stream`, previewUrl: `${API_PREFIX}/camera/${c.id}/preview`, streamUrl: `/viewer.html?id=${c.id}`, mic: c.settings.mic, canPan: Boolean(c.pan), track: c.pan?.track ?? 'off', recording: recordingInfo(c), })); } @@ -315,7 +317,7 @@ function discovery() { const routes = operations().map(({ id, method, template, summary, writes }) => ({ id, methods: [method], path: API_PREFIX + (template === '/' ? '' : template), summary, writes, })); - return { name: 'Just Read The Instructions', version: '2.5.1.1', api: 1, launchId, features: { inGameRecording: true, codecs: ['h264', 'av1'], controlKeyRequired: Boolean(MOCK_KEY) }, routes }; + return { name: 'Just Read The Instructions', version: MOD_VERSION, api: 1, launchId, features: { inGameRecording: true, codecs: ['h264', 'av1'], controlKeyRequired: Boolean(MOCK_KEY) }, routes }; } function isLocalhostOrigin(origin) { @@ -387,6 +389,23 @@ function sendStatic(res, full) { fs.createReadStream(full).pipe(res); } +function compareIgnoringCase(a, b) { + const left = a.toUpperCase(); + const right = b.toUpperCase(); + return left < right ? -1 : left > right ? 1 : 0; +} + +function settingsJson(cam) { + return cam.pan ? { ...cam.settings, pan: panJson(cam.pan) } : cam.settings; +} + +function applySettings(cam, changes) { + for (const [key, value] of Object.entries(changes)) { + const range = SETTING_RANGES[key]; + cam.settings[key] = range && typeof value === 'number' ? clamp(value, range[0], range[1]) : value; + } +} + function listRecordings() { const active = new Set([...cameras.values()].filter((c) => c.recording).map((c) => c.recording.file)); return fs.readdirSync(recordingsDir).filter((f) => /\.(mp4|webm|mkv)$/i.test(f)).map((file) => { @@ -402,8 +421,10 @@ function gameRecording(res, cam, action, codec) { cam.recording = { file, startedAt: Date.now(), paused: false, codec }; fs.writeFileSync(path.join(recordingsDir, file), Buffer.alloc(1024)); } else if (action === 'stop' || action === 'discard') { + const stopped = cam.recording && { file: cam.recording.file, saved: action === 'stop', framesWritten: Math.floor((Date.now() - cam.recording.startedAt) / 33), framesDropped: 0 }; if (cam.recording && action === 'discard') fs.rmSync(path.join(recordingsDir, cam.recording.file), { force: true }); cam.recording = null; + return json(res, stopped ?? null); } else if (action === 'pause' && cam.recording && !cam.recording.paused) { Object.assign(cam.recording, { paused: true, pausedAt: Date.now() }); } else if (action === 'resume' && cam.recording?.paused) { @@ -461,7 +482,7 @@ const server = http.createServer(async (req, res) => { } if (pathname === API_PREFIX) return json(res, discovery()); if (versioned && p === '/openapi.json') return json(res, openApi()); - if (p === '/session') return json(res, { launchId, inGameRecording: true, codecs: ['h264', 'av1'], version: '2.5.1.1', lanUrls: [`http://192.168.1.42:${PORT}/`], controlKeyRequired: Boolean(MOCK_KEY) }); + if (p === '/session') return json(res, { launchId, inGameRecording: true, codecs: ['h264', 'av1'], version: MOD_VERSION, lanUrls: [`http://192.168.1.42:${PORT}/`], controlKeyRequired: Boolean(MOCK_KEY) }); if (p === '/cameras') return json(res, cameraList()); if (p === '/debug/stats') return json(res, sample()); if (p === '/events') return events(req, res); @@ -483,7 +504,7 @@ const server = http.createServer(async (req, res) => { return json(res, { online: cam?.online }); } if (parts[0] === 'layouts') { - if (parts.length === 1) return json(res, [...layouts].map(([name, v]) => ({ name, updated: v.updated })).sort((a, b) => a.name.localeCompare(b.name))); + if (parts.length === 1) return json(res, [...layouts].map(([name, v]) => ({ name, updated: v.updated })).sort((a, b) => compareIgnoringCase(a.name, b.name))); const name = decodeURIComponent(parts[1]); if (!/^[\p{L}\p{N} _-]{1,64}$/u.test(name)) return text(res, 400, 'Invalid layout name'); if (req.method === 'GET') { @@ -531,10 +552,9 @@ const server = http.createServer(async (req, res) => { const { panYaw, panPitch, panYawRate, panPitchRate, track, zoomRate, ...rest } = JSON.parse(await readBody(req)); applyPan(cam.pan, { panYaw, panPitch, panYawRate, panPitchRate, track }); if (zoomRate != null) Object.assign(cam, { zoomRate: clamp(zoomRate, -1, 1), zoomUntil: Date.now() + PAN_RATE_HOLD_MS }); - Object.assign(cam.settings, rest); - res.writeHead(200); return res.end(); + applySettings(cam, rest); } - return json(res, cam.pan ? { ...cam.settings, pan: panJson(cam.pan) } : cam.settings); + return json(res, settingsJson(cam)); case 'recording': return gameRecording(res, cam, parts[3], url.searchParams.get('codec')); default: return text(res, 404, 'Unknown action'); } diff --git a/docs/api.md b/docs/api.md index 4b5a275..688a9a0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -32,7 +32,25 @@ The full description, with every request and response field, is an [OpenAPI 3.1 | Several feeds at once | One multipart stream | `GET /api/v1/streams?ids=10,11`, each part tagged with an `X-Camera-Id` header | | Sound | WAV stream | `GET /api/v1/camera//audio` | -Errors come back with a standard HTTP status and a short plain-text message. A route called with the wrong method answers `405` with an `Allow` header listing the right ones. +Each camera in `/cameras` carries its own addresses: `videoUrl` (the MJPEG stream), `previewUrl` (the same, smaller) and `snapshotUrl` (one JPEG). `streamUrl` is the viewer page meant for people, not the video. + +### Good to know + +* **Changing settings** answers with all the settings after the change. Values out of range are clamped (a brightness of 5 comes back as 1) and unknown fields are ignored, so read the answer to see what was applied. A field of view change shows from the next frame on. +* **Stopping a recording** (`POST /api/v1/camera//recording/stop`, or `/discard` to delete it) answers with the file name and frame counts, or `null` when nothing was recording. The file is finished a moment later and then shows in `/recordings` with its size. +* **Saved layouts** in `/layouts` are sorted by name, ignoring case. The web UI's `Shift` + `1` to `9` use this order, so a new layout can shift the numbers of the ones after it. +* **Events** from `/events` come in two kinds: `program`, with what is on air (sent once when you connect and on every change), and `layout`, with the `name` of a layout that was saved or deleted. A comment line every 15 seconds keeps the connection open. + +### Errors + +Errors come back with a standard HTTP status and a short plain-text message: + +| Status | Means | +| --- | --- | +| `401` | A change needs the [control key](#control-key) and it is missing or wrong | +| `403` | The address uses a name the game does not answer to (see [Opening it by name](#opening-it-by-name)), on any route. On changes, it can also mean the request came from a web page on another website | +| `404` | Unknown route, camera or layout | +| `405` | Wrong method: the `Allow` header lists the right ones | ## Versions diff --git a/docs/openapi.json b/docs/openapi.json index a0a988c..19264eb 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -24,6 +24,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -43,6 +46,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -61,6 +67,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -82,6 +91,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -119,6 +131,9 @@ "content": { "multipart/x-mixed-replace": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -127,12 +142,16 @@ "get": { "operationId": "getEvents", "summary": "Server-Sent Events: program (the layout on air) and layout (a saved layout changed)", + "description": "Each message is either event: program, whose data is a Program, sent once on connect and on every change, or event: layout, whose data is a LayoutEvent, sent when a saved layout is saved or deleted. A comment line keeps the connection open every 15 seconds.", "responses": { "200": { - "description": "Events, with a ping comment every 15 seconds", + "description": "Events", "content": { "text/event-stream": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -152,6 +171,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -170,6 +192,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -204,7 +229,7 @@ "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -234,7 +259,7 @@ "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -249,6 +274,7 @@ "get": { "operationId": "listLayouts", "summary": "Saved layouts", + "description": "Sorted by name, ignoring case and comparing character codes, so the order is the same everywhere. The web UI's Shift+1 to 9 take the layouts in this order.", "responses": { "200": { "description": "JSON", @@ -262,6 +288,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -292,6 +321,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } }, @@ -328,7 +360,7 @@ "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -360,7 +392,7 @@ "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -388,6 +420,9 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -425,6 +460,9 @@ "content": { "video/mp4": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -450,6 +488,9 @@ "content": { "image/jpeg": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -475,6 +516,9 @@ "content": { "multipart/x-mixed-replace": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -500,6 +544,9 @@ "content": { "multipart/x-mixed-replace": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -525,6 +572,9 @@ "content": { "audio/wav": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -550,6 +600,9 @@ "content": { "text/plain": {} } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } } @@ -579,12 +632,16 @@ } } } + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts)" } } }, "post": { "operationId": "changeCameraSettings", "summary": "Changes any of the listed fields and leaves the others alone", + "description": "Values out of range are clamped and unknown fields are ignored. A field of view change shows in the answer from the next frame on.", "parameters": [ { "name": "id", @@ -608,13 +665,117 @@ }, "responses": { "200": { - "description": "Changed" + "description": "The settings after the change", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CameraSettings" + } + } + } }, "401": { "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/camera/{id}/recording/stop": { + "post": { + "operationId": "stopRecording", + "summary": "Stops and saves the in-game recording", + "description": "The file is finished a moment later and then appears in /recordings with its size.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The stopped recording, or null when nothing was recording", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/StoppedRecording" + }, + { + "type": "null" + } + ] + } + } + } + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" + } + }, + "security": [ + {}, + { + "controlKey": [] + } + ] + } + }, + "/camera/{id}/recording/discard": { + "post": { + "operationId": "discardRecording", + "summary": "Stops the in-game recording and deletes the file", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Camera ID, as listed by /cameras", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The discarded recording, or null when nothing was recording", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/StoppedRecording" + }, + { + "type": "null" + } + ] + } + } + } + }, + "401": { + "description": "The control key is required and missing or wrong" + }, + "403": { + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -628,7 +789,7 @@ "/camera/{id}/recording/{action}": { "post": { "operationId": "controlRecording", - "summary": "Starts, stops, discards, pauses or resumes the in-game recording", + "summary": "Starts, pauses or resumes the in-game recording", "parameters": [ { "name": "id", @@ -648,8 +809,6 @@ "type": "string", "enum": [ "start", - "stop", - "discard", "pause", "resume" ] @@ -671,7 +830,7 @@ ], "responses": { "200": { - "description": "The recording, or null once stopped", + "description": "The recording, or null when none is running", "content": { "application/json": { "schema": { @@ -691,7 +850,7 @@ "description": "The control key is required and missing or wrong" }, "403": { - "description": "Sent by a web page from another site" + "description": "The address used a name the game does not answer to (see AllowedHosts), or the request came from a web page on another website" } }, "security": [ @@ -721,9 +880,19 @@ "type": "integer" }, "snapshotUrl": { + "description": "Latest JPEG frame", + "type": "string" + }, + "videoUrl": { + "description": "MJPEG stream at render size", + "type": "string" + }, + "previewUrl": { + "description": "MJPEG stream at preview size", "type": "string" }, "streamUrl": { + "description": "The viewer page for people, not the video: use videoUrl for the stream", "type": "string" }, "mic": { @@ -762,6 +931,8 @@ "streaming", "viewerCount", "snapshotUrl", + "videoUrl", + "previewUrl", "streamUrl", "mic", "canPan", @@ -957,6 +1128,18 @@ "updated" ] }, + "LayoutEvent": { + "type": "object", + "properties": { + "name": { + "description": "The layout that was saved or deleted", + "type": "string" + } + }, + "required": [ + "name" + ] + }, "Pan": { "type": "object", "properties": { @@ -1147,6 +1330,30 @@ "lanUrls", "controlKeyRequired" ] + }, + "StoppedRecording": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "saved": { + "description": "False when discarded", + "type": "boolean" + }, + "framesWritten": { + "type": "integer" + }, + "framesDropped": { + "type": "integer" + } + }, + "required": [ + "file", + "saved", + "framesWritten", + "framesDropped" + ] } }, "securitySchemes": { From 9705812d34aa70603f2409fdfac997e4e9263d3e Mon Sep 17 00:00:00 2001 From: RELMYMathieu Date: Thu, 26 Nov 2026 00:25:41 +0100 Subject: [PATCH 4/4] fix: few more cleanup touches --- CHANGELOG.md | 2 +- Source/ApiAccess.cs | 17 +++++++++-------- Source/ApiCatalog.cs | 4 +--- Source/ApiRoute.cs | 2 +- Source/JRTISettingsGUI.cs | 4 ++-- Source/JRTIStreamServer.cs | 2 +- Tests/JRTI.Tests/ApiAccessScenarioTests.cs | 3 +-- Tests/JRTI.Tests/ApiAccessTests.cs | 17 +++++++++++++++-- Tests/JRTI.Tests/ApiRouterTests.cs | 8 ++++++++ Tools/mock-server.mjs | 11 +++++------ docs/api.md | 6 +++--- docs/settings.md | 2 +- 12 files changed, 48 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3278988..cd43dcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Web API (`/api/v1`) - This allows you to make your own apps, pages and overlays on the same JRTI feeds as the default proposed interface, with an optional control key for other devices if need be. Pages from other websites can no longer change anything, as a security measure. See the API page of the docs for more information -- Your can now make your own pages and styles (`PluginData/Apps/`, `PluginData/Web/`) +- Your own pages and styles (`PluginData/Apps/`, `PluginData/Web/`) - you can now make your own pages and styles, kept across updates ## v3.3.0 - 2026-11-11 diff --git a/Source/ApiAccess.cs b/Source/ApiAccess.cs index 06e4ed4..848d465 100644 --- a/Source/ApiAccess.cs +++ b/Source/ApiAccess.cs @@ -9,7 +9,7 @@ public static class ApiAccess private const string KeyAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; public const int KeyLength = 10; public const string BearerPrefix = "Bearer "; - private const string TailscaleSuffix = ".ts.net"; + private static readonly string[] PrivateNameSuffixes = { ".ts.net", ".local", ".lan", ".home", ".home.arpa", ".internal", ".localdomain" }; private static readonly char[] HostListSeparators = { ',', ' ' }; private static readonly string[] ProxyHeaders = { "X-Forwarded-For", "X-Forwarded-Host", "X-Real-IP", "Forwarded" }; @@ -41,7 +41,7 @@ public static string ProvidedKey(string authorizationHeader, string keyQuery) public static bool KeyMatches(string provided, string expected) { - if (provided == null || expected == null) return false; + if (provided == null || !IsValidKey(expected)) return false; provided = provided.ToUpperInvariant(); int difference = provided.Length ^ expected.Length; for (int i = 0; i < expected.Length; i++) @@ -55,18 +55,19 @@ public static bool IsLocalhostOrigin(string origin) public static bool IsLoopbackHost(string hostHeader) => TryParseHost(hostHeader, out var uri) && IsLoopback(uri); - public static bool IsAllowedHost(string hostHeader, string machineName, string allowedHosts) + public static bool IsAllowedHost(string hostHeader, string allowedHosts) { if (string.IsNullOrEmpty(hostHeader)) return true; if (!TryParseHost(hostHeader, out var uri)) return false; - if (uri.HostNameType != UriHostNameType.Dns || IsLoopback(uri)) return true; - if (uri.Host.EndsWith(TailscaleSuffix, StringComparison.OrdinalIgnoreCase)) return true; + if (uri.HostNameType != UriHostNameType.Dns || IsLoopback(uri) || IsPrivateName(uri.Host)) return true; - var names = (allowedHosts ?? "").Split(HostListSeparators, StringSplitOptions.RemoveEmptyEntries) - .Concat(new[] { machineName, machineName + ".local" }); - return names.Any(name => string.Equals(name, uri.Host, StringComparison.OrdinalIgnoreCase)); + return (allowedHosts ?? "").Split(HostListSeparators, StringSplitOptions.RemoveEmptyEntries) + .Any(name => string.Equals(name, uri.Host, StringComparison.OrdinalIgnoreCase)); } + private static bool IsPrivateName(string host) + => host.IndexOf('.') < 0 || PrivateNameSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)); + public static bool IsDirectFromThisComputer(bool connectionIsLocal, string hostHeader, Func header) => connectionIsLocal && IsLoopbackHost(hostHeader) && ProxyHeaders.All(name => header(name) == null); diff --git a/Source/ApiCatalog.cs b/Source/ApiCatalog.cs index 79712ab..ad69a7a 100644 --- a/Source/ApiCatalog.cs +++ b/Source/ApiCatalog.cs @@ -277,8 +277,6 @@ public static class ApiCatalog Response = ApiResponse.Json(Nullable(Ref("Recording")), "The recording, or null when none is running"), }, }; - - public static ApiOperation Find(string id) => Operations.First(op => op.Id == id); } public static class OpenApiDocument @@ -342,7 +340,7 @@ private static string ResponseJson(ApiResponse response) } } - public static class Json + public static class Json { public static string Pretty(string json) { diff --git a/Source/ApiRoute.cs b/Source/ApiRoute.cs index 1cd1992..8a5f2c9 100644 --- a/Source/ApiRoute.cs +++ b/Source/ApiRoute.cs @@ -31,7 +31,7 @@ public ApiRoute(ApiOperation operation, Action } public bool Allows(string method) - => Methods.Contains(method) || (method == "HEAD" && Methods.Contains("GET")); + => Methods.Contains(method) || (method == "HEAD" && Methods.Contains("GET") && !Operation.Writes); public RouteValues Match(string[] path) { diff --git a/Source/JRTISettingsGUI.cs b/Source/JRTISettingsGUI.cs index 5c6a701..769e1c2 100644 --- a/Source/JRTISettingsGUI.cs +++ b/Source/JRTISettingsGUI.cs @@ -478,8 +478,8 @@ private void DrawControlKey() GUILayout.BeginHorizontal(); GUILayout.Label($"Key: {JRTISettings.ControlKey}", _labelStyle); - var link = JRTIStreamServer.Instance?.LinkWithControlKey(); - if (link != null && GUILayout.Button("Copy link", _buttonStyle)) GUIUtility.systemCopyBuffer = link; + if (GUILayout.Button("Copy link", _buttonStyle)) + GUIUtility.systemCopyBuffer = JRTIStreamServer.Instance?.LinkWithControlKey() ?? GUIUtility.systemCopyBuffer; if (GUILayout.Button("New key", _buttonStyle)) { JRTISettings.ControlKey = ApiAccess.NewKey(); diff --git a/Source/JRTIStreamServer.cs b/Source/JRTIStreamServer.cs index 96ba467..bee99a7 100644 --- a/Source/JRTIStreamServer.cs +++ b/Source/JRTIStreamServer.cs @@ -401,7 +401,7 @@ private void HandleRequest(HttpListenerContext ctx) { try { - if (!ApiAccess.IsAllowedHost(ctx.Request.UserHostName, Environment.MachineName, JRTISettings.AllowedHosts)) + if (!ApiAccess.IsAllowedHost(ctx.Request.UserHostName, JRTISettings.AllowedHosts)) { ServeError(ctx, 403, "This name is not allowed here. Use the computer's IP address, or add the name to AllowedHosts in PluginData/settings.cfg"); return; diff --git a/Tests/JRTI.Tests/ApiAccessScenarioTests.cs b/Tests/JRTI.Tests/ApiAccessScenarioTests.cs index c32a1a4..17afff0 100644 --- a/Tests/JRTI.Tests/ApiAccessScenarioTests.cs +++ b/Tests/JRTI.Tests/ApiAccessScenarioTests.cs @@ -9,7 +9,6 @@ namespace JRTI.Tests public class ApiAccessScenarioTests { private const string Key = "ABCDEFGHJ2"; - private const string MachineName = "GAMEPC"; private sealed class Request { @@ -32,7 +31,7 @@ public Request WithKeyQuery(string key) public WriteVerdict Check(bool requireKey) { - Assert.True(IsAllowedHost(Host, MachineName, ""), $"{Host} should be an allowed name"); + Assert.True(IsAllowedHost(Host, ""), $"{Host} should be an allowed name"); return CheckWrite(requireKey, Key, ConnectionIsLocal, Host, KeyQuery, name => Headers.TryGetValue(name, out var v) ? v : null); } } diff --git a/Tests/JRTI.Tests/ApiAccessTests.cs b/Tests/JRTI.Tests/ApiAccessTests.cs index 68177e6..2f39768 100644 --- a/Tests/JRTI.Tests/ApiAccessTests.cs +++ b/Tests/JRTI.Tests/ApiAccessTests.cs @@ -40,6 +40,13 @@ public void ReadsKeyFromHeaderThenQuery(string header, string query, string expe public void ComparesKeys(string provided, bool matches) => Assert.Equal(matches, ApiAccess.KeyMatches(provided, "ABCDEFGHJ2")); + [Theory] + [InlineData("", "")] + [InlineData("", null)] + [InlineData("anything", "")] + public void NothingMatchesAMissingKey(string provided, string expected) + => Assert.False(ApiAccess.KeyMatches(provided, expected)); + [Theory] [InlineData("http://localhost:5173", true)] [InlineData("http://127.0.0.1:3000", true)] @@ -61,8 +68,14 @@ public void RecognisesLocalhostOrigins(string origin, bool local) [InlineData("gamepc:8080", true)] [InlineData("GamePC.local:8080", true)] [InlineData("gamepc.tail1234.ts.net", true)] + [InlineData("my-gaming-desktop-2024:8080", true)] + [InlineData("gamepc.lan:8080", true)] + [InlineData("gamepc.home.arpa", true)] + [InlineData("nas.internal", true)] + [InlineData("gamepc.localdomain", true)] [InlineData("cams.example.org:8080", true)] - [InlineData("other.lan", true)] + [InlineData("gamepc.fritz.box", false)] + [InlineData("evil.lan.example", false)] [InlineData("ts.net.evil.example", false)] [InlineData("evil.example:8080", false)] [InlineData("gamepc.evil.example:8080", false)] @@ -70,7 +83,7 @@ public void RecognisesLocalhostOrigins(string origin, bool local) [InlineData("evil.example/@127.0.0.1", false)] [InlineData("user@127.0.0.1", false)] public void AllowsOnlyKnownHostNames(string host, bool allowed) - => Assert.Equal(allowed, ApiAccess.IsAllowedHost(host, "GAMEPC", "cams.example.org, other.lan")); + => Assert.Equal(allowed, ApiAccess.IsAllowedHost(host, "cams.example.org")); [Theory] [InlineData(true, "localhost:8080", null, true)] diff --git a/Tests/JRTI.Tests/ApiRouterTests.cs b/Tests/JRTI.Tests/ApiRouterTests.cs index 6dfc1bd..8e070eb 100644 --- a/Tests/JRTI.Tests/ApiRouterTests.cs +++ b/Tests/JRTI.Tests/ApiRouterTests.cs @@ -12,8 +12,16 @@ public class ApiRouterTests Route(new ApiOperation("read", "GET", "/layouts/{layout}", "")), Route(new ApiOperation("save", "PUT", "/layouts/{layout}", "") { AlsoAccepts = new[] { "POST" } }), Route(new ApiOperation("record", "POST", "/camera/{id}/recording/{action}", "")), + Route(new ApiOperation("take", "POST", "/program/take/{layout}", "") { AlsoAccepts = new[] { "GET" }, Writes = true }), }; + [Fact] + public void HeadNeverRunsAWrite() + { + Assert.Equal(ApiRouter.Outcome.Matched, ApiRouter.Resolve(Routes, "GET", "/program/take/Launch", out _, out _, out _)); + Assert.Equal(ApiRouter.Outcome.WrongMethod, ApiRouter.Resolve(Routes, "HEAD", "/program/take/Launch", out _, out _, out _)); + } + private static ApiRoute Route(ApiOperation operation) => new ApiRoute(operation, (ctx, v) => { }); [Fact] diff --git a/Tools/mock-server.mjs b/Tools/mock-server.mjs index ecd833e..92d36db 100644 --- a/Tools/mock-server.mjs +++ b/Tools/mock-server.mjs @@ -1,6 +1,5 @@ import http from 'node:http'; import fs from 'node:fs'; -import os from 'node:os'; import net from 'node:net'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; @@ -24,7 +23,7 @@ const MOCK_KEY = process.env.MOCK_KEY?.trim().toUpperCase(); const PREFLIGHT_MAX_AGE_S = 600; const MOCK_ALLOWED_HOSTS = (process.env.MOCK_ALLOWED_HOSTS ?? '').split(/[, ]+/).filter(Boolean).map((h) => h.toLowerCase()); const PROXY_HEADERS = ['x-forwarded-for', 'x-forwarded-host', 'x-real-ip', 'forwarded']; -const TAILSCALE_SUFFIX = '.ts.net'; +const PRIVATE_NAME_SUFFIXES = ['.ts.net', '.local', '.lan', '.home', '.home.arpa', '.internal', '.localdomain']; const MOD_VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'GameData', 'JustReadTheInstructions', 'JustReadTheInstructions.version'), 'utf8')).VERSION; const SETTING_RANGES = { brightness: [-1, 1], contrast: [0, 3], gamma: [0.1, 5], soundGain: [-24, 24] }; @@ -345,9 +344,8 @@ function isAllowedHost(hostHeader) { if (!hostHeader) return true; const name = hostName(hostHeader); if (!name) return false; - if (net.isIP(name) || isLoopbackName(name) || name.endsWith(TAILSCALE_SUFFIX)) return true; - const machine = os.hostname().toLowerCase(); - return [...MOCK_ALLOWED_HOSTS, machine, `${machine}.local`].includes(name); + if (net.isIP(name) || isLoopbackName(name) || !name.includes('.') || PRIVATE_NAME_SUFFIXES.some((suffix) => name.endsWith(suffix))) return true; + return MOCK_ALLOWED_HOSTS.includes(name); } function isDirectFromThisComputer(req) { @@ -380,7 +378,8 @@ function providedKey(req, url) { function insideRoot(root, rel) { const full = path.join(root, rel); - return full.startsWith(path.normalize(root)) ? full : null; + const base = path.normalize(root + path.sep); + return full === path.normalize(root) || full.startsWith(base) ? full : null; } function sendStatic(res, full) { diff --git a/docs/api.md b/docs/api.md index 688a9a0..f82d7ae 100644 --- a/docs/api.md +++ b/docs/api.md @@ -67,7 +67,7 @@ The API listens on your network like the web UI, with nothing to set up. To chec ### Control key -Watching is always open. To stop other devices from changing anything, tick **Require a key to control from other devices** in the settings window (see [Settings](settings.md#stream-capture)). From then on, changing camera settings, recording, saving or deleting layouts and switching what is on air need the key, except on the KSP computer itself when the page is opened as `localhost` or `127.0.0.1`. Through its network address, or through a proxy such as `tailscale serve`, the KSP computer needs the key like any other device. +Watching is always open. To stop other devices from changing anything, tick **Require a key to control from other devices** in the settings window (see [Settings](settings.md#stream-capture)). From then on, changing camera settings, recording, saving or deleting layouts and switching what is on air need the key, except on the KSP computer itself when the page is opened as `localhost`, `127.0.0.1` or `[::1]`. Through its network address, or through a proxy such as `tailscale serve`, the KSP computer needs the key like any other device. * In the web UI, open the link from **Copy link** once on each device, or type the key when the page asks. The browser remembers it. * In your own app, send it as `Authorization: Bearer `, or add `?key=` to the address (handy for Stream Deck buttons). @@ -89,9 +89,9 @@ Without the key, one more thing is possible: in an old browser, a page from anot ### Opening it by name -The game answers to `localhost`, to any IP address, to the computer's own name (`my-pc` or `my-pc.local`) and to Tailscale names (ending in `.ts.net`). Any other name gets `403`, so a website cannot point its own name at your computer to reach the feeds. +The game answers to `localhost`, to any IP address, to names without a dot (such as the computer's own name, `my-pc`) and to names that only exist on a private network: ending in `.local`, `.lan`, `.home`, `.home.arpa`, `.internal`, `.localdomain` or Tailscale's `.ts.net`. Any other name gets `403`, so a website cannot point its own name at your computer to reach the feeds. -To use another name, add it to `AllowedHosts` in `GameData/JustReadTheInstructions/PluginData/settings.cfg` and restart the game. Separate several names with commas: +To use another name, for example one your router gives out such as `my-pc.fritz.box`, add it to `AllowedHosts` in `GameData/JustReadTheInstructions/PluginData/settings.cfg` and restart the game. Separate several names with commas: ```text AllowedHosts = cams.example.org diff --git a/docs/settings.md b/docs/settings.md index cddf82e..d6d4c0b 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -46,7 +46,7 @@ If another program already uses the port, JRTI says so on screen and in `KSP.log Settings are saved in `GameData/JustReadTheInstructions/PluginData/settings.cfg`. Defaults live in the mod itself, so updates never reset your choices. -One setting is only in the file: `AllowedHosts`, the extra names the web UI answers to besides `localhost`, IP addresses, the computer's name and Tailscale names. See [API](api.md#opening-it-by-name). +One setting is only in the file: `AllowedHosts`, the extra names the web UI answers to besides `localhost`, IP addresses, the computer's name and private network names such as `.local`, `.lan` or Tailscale's `.ts.net`. See [API](api.md#opening-it-by-name). Per-camera sound choices are in `PluginData/camera-sound.cfg`, and saved layouts in `PluginData/Layouts/`. Your own pages go in `PluginData/Apps/` and changed copies of the web UI in `PluginData/Web/` (see [API](api.md#building-a-web-page)).