diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..a9f77a48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **A handshake for native clients.** `GET /api/app-info` answers with the app name `ompweb` (not the npm package name `@kahme247/ompweb`), version, API level and which server-side capabilities exist. It carries no configuration and no credentials (it sits behind the normal auth gate), and it lets a client tell "not an ompweb server" from "server too old" from "OK" instead of probing endpoints. A native client can also ask for its own keep-alive interval with `GET /api/events?heartbeat=` (15-110 s; any other value keeps the 30 s default). The interval belongs to that connection only, so the browser's shared stream is unchanged, and a phone's radio can sleep for the whole idle interval. + ### Fixes & Improvements - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 000000000..aa9a2099b --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,20 @@ +import { NextResponse } from "next/server"; +import packageJson from "../../../package.json"; + +export const dynamic = "force-dynamic"; + +/** + * Capability handshake for native clients. Rides the normal /api auth gate; it + * carries the package version and which server-side features exist, never any + * credential or configuration value. + */ +export function GET() { + return NextResponse.json({ + name: "ompweb", + version: packageJson.version, + api: 1, + capabilities: { + heartbeatParam: true, + }, + }); +} diff --git a/app/api/events/route.ts b/app/api/events/route.ts index c36a33a7d..ba321565a 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; +import { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; export const dynamic = "force-dynamic"; @@ -10,7 +10,8 @@ const MAX_REQUEST_BYTES = 16 * 1024; // GET /api/events — the browser's single multiplexed live-event stream. // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request) { - const connection = new EventStreamConnection(req.signal); + const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); + const connection = new EventStreamConnection(req.signal, heartbeat * 1000); return new Response(connection.stream, { headers: { "Content-Type": "text/event-stream", diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs new file mode 100644 index 000000000..3699dd5c1 --- /dev/null +++ b/lib/app-info-route.test.mjs @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const route = await jiti.import("../app/api/app-info/route.ts"); +const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + +test("app-info identifies ompweb, its version and the heartbeat capability", async () => { + const response = await route.GET(); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.name, "ompweb"); + assert.equal(body.version, pkg.version); + assert.equal(body.api, 1); + assert.deepEqual(body.capabilities, { heartbeatParam: true }); +}); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index c929c832f..44d83df3d 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -11,7 +11,7 @@ const jiti = createJiti(import.meta.url, { "@/": new URL("../", import.meta.url).pathname, }, }); -const { EventStreamConnection, getEventStreamConnection } = await jiti.import("./event-stream-hub.ts"); +const { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } = await jiti.import("./event-stream-hub.ts"); const route = await jiti.import("../app/api/events/route.ts"); const { AgentSessionWrapper } = await jiti.import("./rpc-manager.ts"); const idleSnapshot = () => ({ cursor: { streamId: "test-stream", sequence: 0 } }); @@ -241,7 +241,7 @@ test("slow consumer receives a coalesced message_update on resume without a new try { await subscribeSession(connection, reader, "s1", "test-sess-resume"); // Consumer stalled: v1/v2 fill the queue, v3 is coalesced. Only a resumed - // pull() can deliver it — no heartbeat yet, no new event. + // pull() can deliver it — no heartbeat yet, no new event. session.emit({ type: "message_update", message: { id: "m1", content: "v1" } }); session.emit({ type: "message_update", message: { id: "m1", content: "v2" } }); session.emit({ type: "message_update", message: { id: "m1", content: "v3" } }); @@ -477,3 +477,53 @@ test("file channel enforces the allow-list and reports content changes", { timeo assert.equal(change.data.type, "change"); assert.equal(change.data.size, 7); }); + +test("the per-connection heartbeat is clamped to a safe range", () => { + assert.equal(parseHeartbeatSeconds("15"), 15); + assert.equal(parseHeartbeatSeconds("110"), 110); + assert.equal(parseHeartbeatSeconds(" 60 "), 60); + // Anything a client cannot be trusted with keeps the 30 s default. + for (const value of [null, undefined, "", "14", "111", "0", "-5", "15.5", "abc", "1e3"]) { + assert.equal(parseHeartbeatSeconds(value), 30, String(value)); + } +}); + +test("a connection created with a custom interval emits its keep-alive at that interval", async () => { + const connection = new EventStreamConnection(undefined, 40); + const reader = connection.stream.getReader(); + const hello = await readFrame(reader); + assert.equal(hello.data.type, "hello"); + const started = Date.now(); + const heartbeat = await Promise.race([ + reader.read(), + new Promise((_, reject) => setTimeout(() => reject(new Error("no heartbeat within 2 s")), 2000)), + ]); + const elapsed = Date.now() - started; + assert.equal(decoder.decode(heartbeat.value), ":\n\n"); + assert.ok(elapsed < 1000, `heartbeat arrived after ${elapsed} ms`); + connection.close(); +}); + +test("GET honours the heartbeat query parameter", async (t) => { + // Only the keep-alive interval is faked; readFrame's own watchdog stays real. + t.mock.timers.enable({ apis: ["setInterval"] }); + const ac = new AbortController(); + const res = route.GET(new Request("http://localhost/api/events?heartbeat=60", { signal: ac.signal })); + const reader = res.body.getReader(); + try { + assert.equal((await readFrame(reader)).data.type, "hello"); + let keepAliveArrived = false; + const keepAlive = reader.read().then((chunk) => { + keepAliveArrived = true; + return chunk; + }); + t.mock.timers.tick(30_000); + await setImmediate(); + assert.equal(keepAliveArrived, false, "no keep-alive before the requested 60 s"); + t.mock.timers.tick(30_000); + assert.equal(decoder.decode((await keepAlive).value), ":\n\n"); + } finally { + ac.abort(); + t.mock.timers.reset(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 32be7067d..e7df75f4f 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -18,7 +18,19 @@ import { // the browser's shared worker. // Heartbeat keeps the socket alive through proxies (Next.js idles ~120-150s). +// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; +export const MIN_HEARTBEAT_SECONDS = 15; +export const MAX_HEARTBEAT_SECONDS = 110; + +/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ +export function parseHeartbeatSeconds(value: string | null | undefined): number { + if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; + const seconds = Number(value.trim()); + if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; + return seconds; +} + const encoder = new TextEncoder(); export type SubscribeResult = @@ -77,7 +89,7 @@ export class EventStreamConnection { private readonly subscriptions = new Map(); private readonly signal: AbortSignal | undefined; - constructor(signal?: AbortSignal) { + constructor(signal?: AbortSignal, heartbeatMs: number = HEARTBEAT_MS) { this.signal = signal; this.stream = new ReadableStream({ start: (controller) => { @@ -86,7 +98,7 @@ export class EventStreamConnection { this.control({ type: "hello", connectionId: this.id }); this.heartbeat = setInterval(() => { if (this.flushAll()) this.write(":\n\n"); - }, HEARTBEAT_MS); + }, heartbeatMs); }, // A slow consumer resumed reading: deliver coalesced updates now rather // than waiting for the next event or heartbeat. diff --git a/lib/web-auth.test.mjs b/lib/web-auth.test.mjs index dfb96d979..15acc5f92 100644 --- a/lib/web-auth.test.mjs +++ b/lib/web-auth.test.mjs @@ -170,6 +170,11 @@ test("redirects browser requests to the password screen and blocks unauthenticat const apiResponse = proxy(new NextRequest("http://localhost:30177/api/sessions")); assert.equal(apiResponse.status, 401); + // The handshake endpoint is documented as sitting behind the normal auth + // gate; an exemption for just this path must not pass the suite. + const appInfoResponse = proxy(new NextRequest("http://localhost:30177/api/app-info")); + assert.equal(appInfoResponse.status, 401); + const signedInResponse = proxy(new NextRequest("http://localhost:30177/", { headers: { cookie: `omp_web_session=${createWebSession()}` }, }));