From 579f150e012573e554d53d07610fb840242aaec7 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:01:06 +0100 Subject: [PATCH 1/4] feat(api): add /api/app-info handshake for native clients A native client needs to know which server-side features exist before it offers them. GET /api/app-info rides the normal /api auth gate and returns the package name, version and API level, never credentials or settings. --- app/api/app-info/route.ts | 17 +++++++++++++++++ lib/app-info-route.test.mjs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 app/api/app-info/route.ts create mode 100644 lib/app-info-route.test.mjs diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 000000000..8086f068f --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,17 @@ +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, + }); +} diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs new file mode 100644 index 000000000..1e4835673 --- /dev/null +++ b/lib/app-info-route.test.mjs @@ -0,0 +1,21 @@ +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 and its version", 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); +}); From eecd570838ed194900fa38eea4de511326bbe291 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:04:58 +0100 Subject: [PATCH 2/4] feat(events): let a connection choose its heartbeat (15-110 s) A native client keeps its radio asleep for the whole idle heartbeat, so a per-connection interval is a battery win without touching the shared browser stream. GET /api/events?heartbeat= accepts 15-110 s and falls back to the 30 s default for anything else; capabilities advertise it as heartbeatParam. --- app/api/app-info/route.ts | 3 +++ app/api/events/route.ts | 5 +++-- lib/app-info-route.test.mjs | 3 ++- lib/event-stream-hub.test.mjs | 30 ++++++++++++++++++++++++++++-- lib/event-stream-hub.ts | 16 ++++++++++++++-- 5 files changed, 50 insertions(+), 7 deletions(-) diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts index 8086f068f..aa9a2099b 100644 --- a/app/api/app-info/route.ts +++ b/app/api/app-info/route.ts @@ -13,5 +13,8 @@ export function GET() { 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 index 1e4835673..3699dd5c1 100644 --- a/lib/app-info-route.test.mjs +++ b/lib/app-info-route.test.mjs @@ -11,11 +11,12 @@ const jiti = createJiti(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 and its version", async () => { +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..6d985e79f 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,29 @@ 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(); +}); 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. From 0da2255955900af9bf3e75c738e74a11f3a31e8b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:05:02 +0100 Subject: [PATCH 3/4] docs(changelog): app-info handshake and per-connection heartbeat --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..50c1adb70 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 package name, 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. From ae33fff2f015dcab6bc162f2a909b1117782fee8 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:48:33 +0100 Subject: [PATCH 4/4] docs: name the app-info identity and cover the new paths The handshake answers `name: "ompweb"`, which is not the npm package name; the changelog now says so. Two coverage gaps from review: the proxy test asserts `/api/app-info` sits behind the password gate, and a route-level test sends `?heartbeat=60` and proves the keep-alive is not the fixed 30 s default. --- CHANGELOG.md | 2 +- lib/event-stream-hub.test.mjs | 24 ++++++++++++++++++++++++ lib/web-auth.test.mjs | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c1adb70..a9f77a48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added -- **A handshake for native clients.** `GET /api/app-info` answers with the package name, 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. +- **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 diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 6d985e79f..44d83df3d 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -503,3 +503,27 @@ test("a connection created with a custom interval emits its keep-alive at that i 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/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()}` }, }));