Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<seconds>` (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.
Expand Down
20 changes: 20 additions & 0 deletions app/api/app-info/route.ts
Original file line number Diff line number Diff line change
@@ -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,
},
});
}
5 changes: 3 additions & 2 deletions app/api/events/route.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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",
Expand Down
22 changes: 22 additions & 0 deletions lib/app-info-route.test.mjs
Original file line number Diff line number Diff line change
@@ -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 });
});
54 changes: 52 additions & 2 deletions lib/event-stream-hub.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 } });
Expand Down Expand Up @@ -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" } });
Expand Down Expand Up @@ -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();
}
});
16 changes: 14 additions & 2 deletions lib/event-stream-hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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=<seconds>` 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 =
Expand Down Expand Up @@ -77,7 +89,7 @@ export class EventStreamConnection {
private readonly subscriptions = new Map<string, Subscription>();
private readonly signal: AbortSignal | undefined;

constructor(signal?: AbortSignal) {
constructor(signal?: AbortSignal, heartbeatMs: number = HEARTBEAT_MS) {
this.signal = signal;
this.stream = new ReadableStream<Uint8Array>({
start: (controller) => {
Expand All @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions lib/web-auth.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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()}` },
}));
Expand Down