Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .github/workflows/api.yml
Original file line number Diff line number Diff line change
@@ -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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ 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`) - 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 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

### Added
Expand Down
21 changes: 20 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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

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

Expand Down
8 changes: 8 additions & 0 deletions GameData/JustReadTheInstructions/Web/README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>/ and
open at http://localhost:8080/apps/<name>/. See the API page of the docs.


RECORDINGS
----------

Expand Down
14 changes: 11 additions & 3 deletions GameData/JustReadTheInstructions/Web/js/api.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
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' });
if (!res.ok) throw new Error(`${what} fetch failed: ${res.status}`);
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;
}
Expand Down
4 changes: 2 additions & 2 deletions GameData/JustReadTheInstructions/Web/js/camera-card.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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',
Expand Down
39 changes: 21 additions & 18 deletions GameData/JustReadTheInstructions/Web/js/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
42 changes: 42 additions & 0 deletions GameData/JustReadTheInstructions/Web/js/control-key.js
Original file line number Diff line number Diff line change
@@ -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();
2 changes: 1 addition & 1 deletion GameData/JustReadTheInstructions/Web/js/layout-tray.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()}`;
}
}
1 change: 0 additions & 1 deletion GameData/JustReadTheInstructions/Web/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ function restoreKnownCameras() {
id,
name,
streaming: false,
snapshotUrl: `/camera/${id}/snapshot`,
streamUrl: `/viewer.html?id=${id}`,
});
card.markDestroyed();
Expand Down
2 changes: 1 addition & 1 deletion GameData/JustReadTheInstructions/Web/js/session.js
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
5 changes: 3 additions & 2 deletions GameData/JustReadTheInstructions/Web/js/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
Expand Down Expand Up @@ -170,7 +171,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;
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
103 changes: 103 additions & 0 deletions Source/ApiAccess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using System;
using System.Linq;
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 ";
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" };

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 || !IsValidKey(expected)) 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)
=> 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 allowedHosts)
{
if (string.IsNullOrEmpty(hostHeader)) return true;
if (!TryParseHost(hostHeader, out var uri)) return false;
if (uri.HostNameType != UriHostNameType.Dns || IsLoopback(uri) || IsPrivateName(uri.Host)) return true;

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<string, string> 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);

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;
}

public enum WriteVerdict { Allowed, OtherWebsite, NeedsKey }

public static WriteVerdict CheckWrite(bool requireKey, string expectedKey, bool connectionIsLocal,
string hostHeader, string keyQuery, Func<string, string> 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;
}
}
}
Loading
Loading