diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c25ef1..33a10e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,11 +78,8 @@ jobs: - run: cargo test --locked # The real artefacts: the library and the app, release wasm. Skia comes prebuilt (build.sh). - # A `v*` tag also publishes the app as a tarball on the GitHub release. build: runs-on: ubuntu-latest - permissions: - contents: write steps: - uses: actions/checkout@v7 with: @@ -112,18 +109,30 @@ jobs: with: name: punktfunk-web path: apps/web/dist/ - - name: Release - if: startsWith(github.ref, 'refs/tags/v') - env: + + # A `v*` tag publishes the app as a tarball on the GitHub release, once every check has passed. + release: + needs: [build, web, check, server] + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + name: punktfunk-web + path: dist + - env: GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} run: | tarball="punktfunk-client-web-${GITHUB_REF_NAME}.tar.gz" - tar -czf "$tarball" -C apps/web/dist . + tar -czf "$tarball" -C dist . gh release create "$GITHUB_REF_NAME" "$tarball" --verify-tag --generate-notes # The container: the server compiled natively on each architecture's runner, the client from the - # build job. Pushed to git.unom.io from main (`edge`) and from v* tags (`X.Y.Z` and `latest`); - # pull requests build it without pushing. Pushing needs the UNOM_REGISTRY_USER and + # build job. Each architecture is pushed by digest, with no tag, and `manifest` names this run's + # two. Pull requests build it without pushing. Pushing needs the UNOM_REGISTRY_USER and # UNOM_REGISTRY_TOKEN secrets, a Gitea token with package write. image: # Every check, not only the build: an image is what people run. @@ -143,10 +152,6 @@ jobs: with: name: punktfunk-web path: apps/web/dist - - name: Channel - run: | - if [[ "$GITHUB_REF" == refs/tags/v* ]]; then echo "CHANNEL=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" - else echo "CHANNEL=edge" >> "$GITHUB_ENV"; fi - uses: docker/setup-buildx-action@v4 - if: env.PUSH == 'true' uses: docker/login-action@v4 @@ -154,16 +159,31 @@ jobs: registry: git.unom.io username: ${{ secrets.UNOM_REGISTRY_USER }} password: ${{ secrets.UNOM_REGISTRY_TOKEN }} - - uses: docker/build-push-action@v7 + # No tag: another run could move a shared one before `manifest` reads it. + - id: build + uses: docker/build-push-action@v7 with: context: . platforms: linux/${{ matrix.arch }} - push: ${{ env.PUSH == 'true' }} - tags: ${{ env.IMAGE }}:${{ env.CHANNEL }}-${{ matrix.arch }} + outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=${{ env.PUSH }} cache-from: type=gha,scope=server-${{ matrix.arch }} cache-to: type=gha,mode=max,scope=server-${{ matrix.arch }} + - if: env.PUSH == 'true' + env: + DIGEST: ${{ steps.build.outputs.digest }} + ARCH: ${{ matrix.arch }} + run: mkdir -p digest && echo "$DIGEST" > "digest/$ARCH" + - if: env.PUSH == 'true' + uses: actions/upload-artifact@v7 + with: + name: digest-${{ matrix.arch }} + path: digest/ + if-no-files-found: error + retention-days: 1 - # One tag for both architectures. + # One tag over this run's two digests. `edge` moves only while this commit is still main's + # head, so an older run that finishes last leaves it alone. A tag `vX.Y.Z` gets `X.Y.Z`, and + # `latest` too unless it is a prerelease (`-` in the version). manifest: needs: image if: github.event_name == 'push' @@ -172,6 +192,12 @@ jobs: IMAGE: git.unom.io/unom/punktfunk-client-web TOKEN: ${{ secrets.UNOM_REGISTRY_TOKEN }} steps: + - if: env.TOKEN != '' + uses: actions/download-artifact@v8 + with: + pattern: digest-* + path: digest + merge-multiple: true - if: env.TOKEN != '' uses: docker/login-action@v4 with: @@ -180,10 +206,20 @@ jobs: password: ${{ secrets.UNOM_REGISTRY_TOKEN }} - uses: docker/setup-buildx-action@v4 - if: env.TOKEN != '' + env: + GH_TOKEN: ${{ github.token }} run: | + images=("$IMAGE@$(cat digest/amd64)" "$IMAGE@$(cat digest/arm64)") if [[ "$GITHUB_REF" == refs/tags/v* ]]; then - channel="${GITHUB_REF_NAME#v}"; tags=(-t "$IMAGE:$channel" -t "$IMAGE:latest") + version="${GITHUB_REF_NAME#v}" + tags=(-t "$IMAGE:$version") + [[ "$version" == *-* ]] || tags+=(-t "$IMAGE:latest") else - channel=edge; tags=(-t "$IMAGE:edge") + head="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq .object.sha)" + if [[ "$head" != "$GITHUB_SHA" ]]; then + echo "main is at $head now; its own run moves edge" + exit 0 + fi + tags=(-t "$IMAGE:edge") fi - docker buildx imagetools create "${tags[@]}" "$IMAGE:$channel-amd64" "$IMAGE:$channel-arm64" + docker buildx imagetools create "${tags[@]}" "${images[@]}" diff --git a/README.md b/README.md index 05f9fd1..7e04702 100644 --- a/README.md +++ b/README.md @@ -232,8 +232,9 @@ Rust owns the protocol; TypeScript owns the browser. The library owns everything **`server`** — `punktfunk-client-web-server`: the built client, `/config.json`, `/h//…` proxied to each host's management API, pinned, and `/w/`, which carries a session over a -WebSocket where the network blocks UDP. Behind a reverse proxy, keep the Host header; the bridge -sees only the proxy's address. `Dockerfile` and `deploy/` package it. +WebSocket where the network blocks UDP. Behind a reverse proxy, pass the Host header through with +its port (nginx: `proxy_set_header Host $http_host;`) and send `X-Forwarded-For`, which names the +visitor to each host. `Dockerfile` and `deploy/` package it. **`apps/web`** diff --git a/apps/web/src/app.ts b/apps/web/src/app.ts index 1992977..78d529c 100644 --- a/apps/web/src/app.ts +++ b/apps/web/src/app.ts @@ -45,6 +45,7 @@ import { wakeFailed, wakingLine, } from "@punktfunk/stream"; +import { type Configured, readConfig, type ServerConfig } from "./config.ts"; import { ConsoleUi } from "./ui/console.ts"; import { noop, WebShell } from "./ui/shell.tsx"; import type { HostCard, HostTools, ProfileCard, Screen, Tab, Ui } from "./ui/types.ts"; @@ -113,7 +114,7 @@ class App { private runningId: string | undefined; /** The running title is this device's launch, which End game may end. */ private runningEndable = false; - /** What the host said when End game last ran from the library. */ + /** What the host said when End game last ran from the library, until the next stream. */ private endNotice: string | undefined; /** The title this device launched that the live stream plays, asked for when the menu opens. */ private streamGame: { appId: string; title: string } | null = null; @@ -122,7 +123,8 @@ class App { /** When the live stream began, while its exit hint is up; `0` once the hint is gone. */ private hintSince = 0; private hintTimer = 0; - private wasStreaming = false; + /** The engine state the last render drew: each edge below is against it. */ + private lastKind: EngineState["kind"] = "idle"; private streamNoticeTimer = 0; /** The origin whose running title is being polled. */ private pollingFor: string | null = null; @@ -143,6 +145,9 @@ class App { /** A connect link the page opened with, until it is answered, and the title it asked for. */ private link: { target: string | HostTarget; fp?: string; launch?: string } | null = null; private launchOnReady: string | null = null; + /** The fingerprint a followed link pinned its host to. Every reconnect to that host carries it + * until the page is idle again. */ + private pin: { origin: string; fp: string } | null = null; /** The settings page, or its dialog over a live stream. */ private settingsOpen = false; /** The quick menu over a live picture; closed whenever the stream is not. */ @@ -156,6 +161,12 @@ class App { private gate: Gate | null = null; /** A Switch profile asked for a host that was not connected: it opens once the host is ready. */ private switchOnReady: string | null = null; + /** The hosts the page's own server proxies, by the API origin the engine keys them under. */ + private readonly configured: Map; + /** Whether that server also proxies a host typed here by its IP address. */ + private viaServer: boolean; + /** When the server's list may be asked for again after it turned the read away; `0`: not owed. */ + private configAgainAt = 0; constructor( private readonly engine: Engine, @@ -163,11 +174,10 @@ class App { /** The web shell, rather than the gamepad console: only it has tabs to keep. */ private readonly web: boolean, private readonly uiCanvas: HTMLCanvasElement, - /** The hosts the page's own server proxies, by the API origin the engine keys them under. */ - private readonly configured: Map, - /** Whether that server also proxies a host typed here by its IP address. */ - private readonly viaServer: boolean, + server: ServerConfig, ) { + this.configured = server.listed; + this.viaServer = server.viaServer; // A login's pass covers another host: the server now tells this browser its address and wake. onPass(() => void this.refreshConfigured()); ui.mount({ @@ -190,7 +200,7 @@ class App { // Otherwise a stream a card asked for is still what the retry is for. if (this.dropped) this.resumeOnReady = this.dropped; this.dropped = null; - if ("origin" in s && s.origin) void engine.connect(this.targetOf(s.origin)); + if ("origin" in s && s.origin) this.reconnect(s.origin); }, // Leaving the profile gate goes back to the host, not away from it. back: () => (this.gate ? this.cancelGate() : engine.disconnect()), @@ -204,7 +214,7 @@ class App { hostAction: (id) => void this.hostAction(id), endGame: () => void this.endGame(), sendLog: () => void this.sendLog(), - wake: (origin) => void this.wake(origin), + wake: (origin) => this.wake(origin), disconnect: (quit) => { this.menuOpen = false; engine.leave(quit); @@ -250,6 +260,11 @@ class App { engine.setStatsTier(on ? (start === "off" ? "normal" : start) : "off"); }, }); + // The server turned its list away: say so, and ask again on a later redraw of the hosts. + if (server.wait) { + this.configAgainAt = Date.now() + server.wait * 1000; + ui.notify(sentence(TOO_MANY), "error"); + } this.applyPrefs(); this.watchSize(); if (packaged()) this.watchSleep(); @@ -269,6 +284,8 @@ class App { /** Facts in, words out. */ private render(s: EngineState): void { + const was = this.lastKind; + this.lastKind = s.kind; // The gate waits on its host's `ready`; anything else ends the wait, and a connect that // ended short of it drops the Switch profile it was for. if (this.gate && (s.kind !== "ready" || s.origin !== this.gate.origin)) this.gate = null; @@ -279,7 +296,7 @@ class App { } // The exit hint: armed on the edge into a stream, dropped by its timer or the stream's end. const streaming = s.kind === "streaming"; - if (streaming && !this.wasStreaming && this.prefs.exitHint) { + if (streaming && was !== "streaming" && this.prefs.exitHint) { this.hintSince = Date.now(); clearTimeout(this.hintTimer); this.hintTimer = window.setTimeout(() => { @@ -288,8 +305,14 @@ class App { }, EXIT_HINT_MS); } else if (!streaming) { this.hintSince = 0; + clearTimeout(this.hintTimer); + } + // A stream that ends takes the settings dialog over it along: how it ended is what to show. + // One that drops is what "Try again" brings back. + if (live(was) && !live(s.kind)) { + this.settingsOpen = false; + if (s.kind === "error") this.dropped = this.lastPlay; } - this.wasStreaming = streaming; if (this.settingsOpen) { return this.show({ kind: "settings", values: this.prefs, streaming: s.kind === "streaming" }); } @@ -304,12 +327,13 @@ class App { this.launchOnReady = null; this.resumeOnReady = null; this.dropped = null; + this.pin = null; return this.web && this.tab === "library" ? this.showLibrary() : this.home(); case "bad-address": // The field stays in front: what was typed is wrong and this is where it is fixed. this.adding = true; this.tab = "hosts"; - return this.home(sentence(s.message)); + return this.home(); case "reaching": return this.show({ kind: "connecting", origin: s.origin, phase: "reaching" }); case "blocked": { @@ -342,7 +366,7 @@ class App { // The host closes after the ceremony, as it does for native clients; streaming is a // fresh connection. const origin = s.origin; - setTimeout(() => void this.engine.connect(this.targetOf(origin)), 300); + setTimeout(() => this.reconnect(origin), 300); return; } case "pair-refused": @@ -407,15 +431,11 @@ class App { }); case "error": { this.windowed(); - // Was a stream live, or starting, when this happened? Then trying again resumes it. - const was = this.screen; - const streamed = was.kind === "streaming" || (was.kind === "connecting" && was.phase === "starting"); - if (streamed) this.dropped = this.lastPlay; return this.show({ kind: "error", head: s.skew ? "This host speaks a different version" - : streamed + : this.dropped ? "The stream stopped" : "Something went wrong", text: s.skew @@ -428,8 +448,8 @@ class App { } // --- the tabs -------------------------------------------------------------------------- - /** A sidebar entry. A flow left half-way — a PIN, a certificate, an error — is cancelled; the - * library's own connection is kept, since it is what the Library tab shows. */ + /** A sidebar entry. A flow left half-way — a PIN, a certificate, an error, the profile gate — + * is cancelled; the library's own connection is kept, since it is what the Library tab shows. */ private navigate(tab: Tab): void { const s = this.engine.current; if (tab === "settings") { @@ -439,6 +459,7 @@ class App { this.settingsOpen = false; this.tab = tab; this.link = null; + this.gate = null; if (FLOWS.has(s.kind) && !(this.quiet && tab === "library")) { this.quiet = false; this.engine.disconnect(); @@ -478,10 +499,14 @@ class App { } // --- the host list --------------------------------------------------------------------- - private home(error?: string): void { + private home(): void { // A link waiting for its answer stays in front of the probes that redraw this list. if (this.link) return; + if (this.configAgainAt && Date.now() >= this.configAgainAt) void this.refreshConfigured(); const cards = this.cards(); + // A mistyped address stays said while the engine holds it, whatever redraws the list. + const s = this.engine.current; + const error = s.kind === "bad-address" ? sentence(s.message) : undefined; this.show({ kind: "home", hosts: cards, @@ -492,10 +517,17 @@ class App { void this.probe(cards.map((h) => h.origin)); } - /** The server's list again, as a pass holder sees it. */ + /** The server's list again: as a pass holder sees it, or once a turned-away read may retry. */ private async refreshConfigured(): Promise { - const again = await configuredHosts(); + this.configAgainAt = 0; + const again = await readConfig(serverFetch(), location.href); + if (!again) return; + if (again.wait) { + this.configAgainAt = Date.now() + again.wait * 1000; + return; + } for (const [origin, c] of again.listed) this.configured.set(origin, c); + this.viaServer = again.viaServer; this.redrawLists(); } @@ -631,7 +663,19 @@ class App { this.link = null; if (!yes || !link) return this.home(); this.launchOnReady = link.launch ?? null; - void this.engine.connect(link.target, link.fp ? { expectFingerprint: link.fp } : {}); + const origin = typeof link.target === "string" ? originOf(link.target) : link.target.api.replace(/\/+$/, ""); + this.pin = link.fp ? { origin, fp: link.fp } : null; + void this.engine.connect(link.target, this.pinned(origin)); + } + + /** Reach `origin` again: a retry, or the connection after a pairing. */ + private reconnect(origin: string): void { + void this.engine.connect(this.targetOf(origin), this.pinned(origin)); + } + + /** What a connect to `origin` must check: the fingerprint a link pinned it to, if any. */ + private pinned(origin: string): { expectFingerprint?: string } { + return this.pin?.origin === origin ? { expectFingerprint: this.pin.fp } : {}; } /** A link to this host, pinned to its fingerprint when this browser has paired with it. The @@ -650,18 +694,20 @@ class App { /** * Wake a host through the page's server, which sits on its network where a browser cannot send * a magic packet. Then ask after it every few seconds, as it boots, until it answers or a minute - * has gone. + * has gone. `false` when no packet went out: refused or failed, which the page has said. */ - private async wake(origin: string): Promise { + private async wake(origin: string): Promise { const url = this.configured.get(origin)?.wake; - if (!url || this.waking.has(origin)) return; + if (!url) return false; + if (this.waking.has(origin)) return true; this.waking.add(origin); this.redrawLists(); try { const r = await serverFetch()(url, { method: "POST" }); if (r.status === 403 || r.status === 429) { const why = r.status === 429 ? sentence(TOO_MANY) : `Only a browser paired with ${this.nameOf(origin)} can wake it from this page.`; - return this.ui.notify(why, "error"); + this.ui.notify(why, "error"); + return false; } if (!r.ok) throw new Error(`wake refused (${r.status})`); let up = false; @@ -672,9 +718,11 @@ class App { up = now === "ok"; } if (!up) this.ui.notify(`${this.nameOf(origin)} didn't answer within a minute of waking. It may still be starting.`, "error"); + return true; } catch (e) { console.warn("punktfunk: wake", e); this.ui.notify(`Couldn't wake ${this.nameOf(origin)} — this page's server didn't send the wake packet.`, "error"); + return false; } finally { this.waking.delete(origin); this.redrawLists(); @@ -682,14 +730,18 @@ class App { } /** Forget a host. From the trust screen this is "forget and pair again", so the reconnect - * follows — with the stored fingerprint gone, the next connection is a first one. */ + * follows — with the stored fingerprint gone, the next connection is a first one, held to + * the fingerprint of a link that brought it here. */ private forget(origin: string): void { const reconnect = this.screen.kind === "trust" && this.screen.origin === origin; this.reachCache.delete(origin); if (this.libraryFor === origin) this.clearLibrary(); + const pin = this.pin; this.engine.forget(origin); - if (reconnect) void this.engine.connect(this.targetOf(origin)); - else this.redrawLists(); + if (!reconnect) return this.redrawLists(); + // Forgetting disconnects, which drops a link's pin; pairing again is still held to it. + this.pin = pin; + this.reconnect(origin); } // --- the library --------------------------------------------------------------------- @@ -703,10 +755,12 @@ class App { if (this.libraryFor !== s.origin) return; this.entries = entries; this.libraryError = undefined; + this.libraryAt = Date.now(); } catch (e) { if (this.libraryFor !== s.origin) return; + // A failure keeps no clock: opening the host again asks again. + this.libraryAt = 0; if (e instanceof VersionSkew) { - this.libraryLoading = false; return this.show({ kind: "error", head: "This host speaks a different version", @@ -717,11 +771,7 @@ class App { // dead end. this.libraryError = e instanceof Error ? e.message : String(e); } finally { - if (this.libraryFor === s.origin) { - this.libraryLoading = false; - // A failure keeps no clock: opening the host again asks again. - if (!this.libraryError) this.libraryAt = Date.now(); - } + if (this.libraryFor === s.origin) this.libraryLoading = false; } this.redrawLibrary(); // Art after the grid, per entry: the grid should appear before its covers do. @@ -888,9 +938,12 @@ class App { return this.render(this.engine.current); } const host = this.shelfHost(); + const shelf = this.libraryFor; const [id, title] = [this.runningId, this.running]; if (!host || !id || !title) return; const outcome = await host.endGame(id); + // Another shelf opened meanwhile: the answer is not about its titles. + if (this.libraryFor !== shelf) return; this.endNotice = gameEndNotice(outcome, title); if (gameGone(outcome)) { this.running = undefined; @@ -1045,6 +1098,7 @@ class App { private dial(entry?: LibraryEntry, profile?: string): void { this.gate = null; + this.endNotice = undefined; this.lastPlay = { ...(entry ? { entry } : {}), ...(profile ? { profile } : {}) }; this.engine.startStream({ ...this.streamOptions(), ...(entry ? { launch: entry } : {}), ...(profile ? { profile } : {}) }); } @@ -1187,6 +1241,9 @@ class App { } } +/** A stream live or on its way: what a settings dialog sits over, and what a drop ends. */ +const live = (kind: EngineState["kind"]): boolean => kind === "streaming" || kind === "starting"; + /** A stream asked for: the title (unset: the desktop), and the profile the console picked. */ interface Play { entry?: LibraryEntry; @@ -1259,21 +1316,17 @@ function sentence(message: string): string { * `https://` that `originOf` put there. */ const bare = (origin: string): string => origin.replace(/^https:\/\//, ""); -/** The stream mode from the canvas: device pixels capped at 2×, and always even. +/** The stream mode from the canvas's box: device pixels capped at 2×, and always even. * * H.264/HEVC are 4:2:0 — one chroma sample per 2×2 luma block — so a codec has no valid chroma * grid for an odd width or height, and the host refuses one. The window is whatever size it is, - * so round each dimension down to even here rather than send the host something it must reject. */ + * so round each dimension down to even here rather than send the host something it must reject. + * Measured only: the console sizes the canvas's buffer itself, and a write here would clear the + * frame it just drew. */ function size(canvas: HTMLCanvasElement): [number, number] { const dpr = Math.min(window.devicePixelRatio || 1, 2); const even = (px: number) => Math.max(2, Math.floor(px) & ~1); - const w = even(canvas.clientWidth * dpr); - const h = even(canvas.clientHeight * dpr); - if (canvas.width !== w || canvas.height !== h) { - canvas.width = w; - canvas.height = h; - } - return [w, h]; + return [even(canvas.clientWidth * dpr), even(canvas.clientHeight * dpr)]; } /** @@ -1326,39 +1379,6 @@ function routeOf(address: string): HostTarget | null { return plane ? { api: address.replace(/\/+$/, ""), plane, bridge: `wa/${ipPort}` } : null; } -/** A host from the page server's `config.json`. `wake` is its wake URL when the server can. */ -interface Configured extends HostTarget { - name: string; - wake?: string; -} - -/** - * The hosts `punktfunk-client-web-server` proxies, from its `config.json`. Any other server has - * none (a dev server answers `index.html`, which does not parse), and the page falls back to - * addresses typed here. - */ -async function configuredHosts(): Promise<{ listed: Map; viaServer: boolean }> { - try { - const r = await serverFetch()("./config.json", { cache: "no-store" }); - const c = (await r.json()) as { - hosts?: Array<{ name: string; api: string; plane?: string; wake?: string; bridge?: string }>; - add?: boolean; - }; - const listed = new Map( - (c.hosts ?? []).map((h): [string, Configured] => { - const api = new URL(h.api, location.href).href.replace(/\/+$/, ""); - const wake = h.wake ? new URL(h.wake, location.href).href : undefined; - const bridge = h.bridge ? { bridge: h.bridge } : {}; - const plane = h.plane ? { plane: h.plane } : {}; - return [api, { api, ...plane, name: h.name, ...(wake ? { wake } : {}), ...bridge }]; - }), - ); - return { listed, viaServer: c.add === true }; - } catch { - return { listed: new Map(), viaServer: false }; - } -} - /** Set by `vite.config.ts` when the dev server proxies a host; absent in a build. */ declare const __PF_TRANSPORT_HOST__: string | undefined; @@ -1374,9 +1394,9 @@ try { uiCanvas, ...(__PF_TRANSPORT_HOST__ ? { transportHost: __PF_TRANSPORT_HOST__ } : {}), }); - const server = await configuredHosts(); + const server = (await readConfig(serverFetch(), location.href)) ?? { listed: new Map(), viaServer: false }; const ui = pickUi(engine, uiCanvas); - new App(engine, ui, ui instanceof WebShell, uiCanvas, server.listed, server.viaServer); + new App(engine, ui, ui instanceof WebShell, uiCanvas, server); } catch (e) { // Before there is an engine there is no interface to say this on; the one sheet the page // carries for exactly this case does. diff --git a/apps/web/src/config.test.ts b/apps/web/src/config.test.ts new file mode 100644 index 0000000..3de1d56 --- /dev/null +++ b/apps/web/src/config.test.ts @@ -0,0 +1,38 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { readConfig } from "./config.ts"; + +const PAGE = "https://pf.example/web/"; +const answer = (r: Response) => (async () => r) as unknown as typeof fetch; + +test("the list resolves against the page, and a host without a plane keeps none", async () => { + const body = { hosts: [{ name: "desk", api: "h/desk", bridge: "w/desk", wake: "wake/desk" }], add: true }; + const c = await readConfig(answer(Response.json(body)), PAGE); + assert.equal(c?.viaServer, true); + assert.equal(c?.wait, undefined); + const desk = c?.listed.get("https://pf.example/web/h/desk"); + assert.deepEqual(desk, { + api: "https://pf.example/web/h/desk", + name: "desk", + wake: "https://pf.example/web/wake/desk", + bridge: "w/desk", + }); + assert.equal(desk !== undefined && "plane" in desk, false); +}); + +test("a 429 is the page's own server: it proxies, and the list is owed after Retry-After", async () => { + const busy = new Response("Too many requests", { status: 429, headers: { "retry-after": "3" } }); + const c = await readConfig(answer(busy), PAGE); + assert.deepEqual({ size: c?.listed.size, viaServer: c?.viaServer, wait: c?.wait }, { size: 0, viaServer: true, wait: 3 }); + const bare = await readConfig(answer(new Response("", { status: 429 })), PAGE); + assert.equal(bare?.wait, 60); +}); + +test("a server without config.json, or no answer, is no page server", async () => { + const html = new Response("", { headers: { "content-type": "text/html" } }); + assert.equal(await readConfig(answer(html), PAGE), null); + const down = (async () => { + throw new TypeError("network"); + }) as unknown as typeof fetch; + assert.equal(await readConfig(down, PAGE), null); +}); diff --git a/apps/web/src/config.ts b/apps/web/src/config.ts new file mode 100644 index 0000000..c43906e --- /dev/null +++ b/apps/web/src/config.ts @@ -0,0 +1,49 @@ +// What the page's own server says in `config.json`: the hosts it proxies, and whether it also +// proxies a host typed here by its IP address. Apart from `app.ts` so a test can read it. + +import type { HostTarget } from "@punktfunk/stream"; + +/** A host from the page server's `config.json`. `wake` is its wake URL when the server can. */ +export interface Configured extends HostTarget { + name: string; + wake?: string; +} + +export interface ServerConfig { + listed: Map; + /** The server also proxies a host typed here by its IP address. */ + viaServer: boolean; + /** The server turned the read away (`429`): seconds until it may be asked again. */ + wait?: number; +} + +/** + * Read `config.json` through `fetch`, resolving its routes against `page`. `null` is a server + * without one: a dev server answers `index.html`, which does not parse. A `429` is the page's + * own server metering a stranger, so it proxies, and its list is owed. + */ +export async function readConfig(fetch: typeof globalThis.fetch, page: string): Promise { + try { + const r = await fetch(new URL("config.json", page).href, { cache: "no-store" }); + if (r.status === 429) { + const wait = Number(r.headers.get("retry-after")); + return { listed: new Map(), viaServer: true, wait: wait > 0 ? wait : 60 }; + } + const c = (await r.json()) as { + hosts?: Array<{ name: string; api: string; plane?: string; wake?: string; bridge?: string }>; + add?: boolean; + }; + const listed = new Map( + (c.hosts ?? []).map((h): [string, Configured] => { + const api = new URL(h.api, page).href.replace(/\/+$/, ""); + const wake = h.wake ? new URL(h.wake, page).href : undefined; + const bridge = h.bridge ? { bridge: h.bridge } : {}; + const plane = h.plane ? { plane: h.plane } : {}; + return [api, { api, ...plane, name: h.name, ...(wake ? { wake } : {}), ...bridge }]; + }), + ); + return { listed, viaServer: c.add === true }; + } catch { + return null; + } +} diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css index 252f44e..747ac27 100644 --- a/apps/web/src/styles.css +++ b/apps/web/src/styles.css @@ -81,6 +81,10 @@ /* `EDGE_INSET` from pf-console-ui's theme.rs: the distance anything keeps from the screen edge. The one metric the console shell and this one share. */ --pf-inset: 24px; + /* The same inset from a side edge, clear of a phone's notch in landscape: the page is + `viewport-fit=cover`, so it draws under it. */ + --pf-inset-left: max(var(--pf-inset), env(safe-area-inset-left)); + --pf-inset-right: max(var(--pf-inset), env(safe-area-inset-right)); } /* Map the palette to Tailwind colour/util tokens — both the shadcn vocabulary and @unom/ui's, diff --git a/apps/web/src/ui/console-hosts.test.ts b/apps/web/src/ui/console-hosts.test.ts new file mode 100644 index 0000000..adb697b --- /dev/null +++ b/apps/web/src/ui/console-hosts.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { hostRow, originFor } from "./console-hosts.ts"; +import type { HostCard } from "./types.ts"; + +/** The rows as `ConsoleUi.pushHosts` builds them, and its key → origin map. */ +function rows(cards: HostCard[]) { + const all = cards.map((h) => hostRow(h, h.fingerprint)); + return { all, origins: new Map(all.map((r, i) => [r.key, cards[i]!.origin])) }; +} + +test("hosts the page's server lists without a plane each get their own row", () => { + const cards: HostCard[] = [ + { origin: "https://page.example/h/desk", name: "desk" }, + { origin: "https://page.example/h/den", name: "den" }, + ]; + const { all, origins } = rows(cards); + assert.notEqual(all[0]!.key, all[1]!.key); + assert.notEqual(all[0]!.addr, all[1]!.addr); + // A Pair names the key; a Launch for an unpaired host names only the address. + for (const [i, h] of cards.entries()) { + assert.equal(originFor(origins, cards, all[i]!.key, ""), h.origin); + assert.equal(originFor(origins, cards, "", all[i]!.addr), h.origin); + } +}); + +test("a host with a plane, and one dialled directly, keep their address", () => { + const cards: HostCard[] = [ + { origin: "https://page.example/h/desk", name: "desk", plane: "192.168.1.20" }, + { origin: "https://192.168.1.31:47990", name: "deck" }, + ]; + const { all, origins } = rows(cards); + assert.equal(all[0]!.addr, "192.168.1.20"); + assert.equal(all[1]!.addr, "192.168.1.31"); + assert.equal(all[1]!.key, "192.168.1.31:47990"); + assert.equal(originFor(origins, cards, "", "192.168.1.20"), cards[0]!.origin); +}); + +test("a paired row is keyed by its fingerprint", () => { + const cards: HostCard[] = [{ origin: "https://page.example/h/desk", name: "desk", fingerprint: "ab".repeat(32) }]; + const { all, origins } = rows(cards); + assert.equal(all[0]!.key, "ab".repeat(32)); + assert.equal(all[0]!.paired, true); + assert.equal(originFor(origins, cards, "ab".repeat(32), ""), cards[0]!.origin); +}); diff --git a/apps/web/src/ui/console-hosts.ts b/apps/web/src/ui/console-hosts.ts new file mode 100644 index 0000000..fc888f7 --- /dev/null +++ b/apps/web/src/ui/console-hosts.ts @@ -0,0 +1,50 @@ +// A known host as the console's Home draws it, and back: the row the page pushes, and the origin +// a row's key or address names when the console raises a command for it. + +import type { ConsoleHostRow } from "@punktfunk/stream"; +import type { HostCard } from "./types.ts"; + +/** Where a row says its host is: its plane address, else its own hostname. A host the page's + * server routes without telling its plane is its route, which no two hosts share. */ +export function hostAddr(h: HostCard): string { + const url = new URL(h.origin); + return h.plane ?? (url.pathname === "/" ? url.hostname : h.origin); +} + +/** The console's row for `h`, pinned to `fp` when this browser paired with it. */ +export function hostRow(h: HostCard, fp: string | undefined): ConsoleHostRow { + const addr = hostAddr(h); + const mgmt = Number(new URL(h.origin).port) || 47990; + return { + key: fp ?? `${addr}:${mgmt}`, + id: h.origin, + name: h.label ?? h.name ?? addr, + addr, + port: 9778, + fp_hex: fp ?? "", + paired: !!fp, + saved: true, + online: h.reach === "ok", + mgmt_port: mgmt, + can_wake: !!h.wake && h.reach !== "ok", + last_used: h.seen ? Math.floor(h.seen / 1000) : null, + os: "", + pin: null, + bound_preset: null, + profile: h.profile ?? null, + }; +} + +/** The origin a console key or address stands for: `origins` maps each row's key to its origin, + * and `cards` are the rows' hosts. */ +export function originFor( + origins: ReadonlyMap, + cards: readonly HostCard[], + key: string, + addr: string, +): string | undefined { + const byKey = origins.get(key); + if (byKey) return byKey; + for (const [k, o] of origins) if (k.startsWith(`${addr}:`)) return o; + return cards.find((h) => hostAddr(h) === addr)?.origin; +} diff --git a/apps/web/src/ui/console.ts b/apps/web/src/ui/console.ts index 185027c..201679f 100644 --- a/apps/web/src/ui/console.ts +++ b/apps/web/src/ui/console.ts @@ -37,6 +37,7 @@ import { tvBack, } from "@punktfunk/stream"; import { FrameMeter, type Row, type Step, Sweep, table } from "./console-cost.ts"; +import { hostRow, originFor } from "./console-hosts.ts"; import { coverBytes } from "./cover.ts"; import type { Actions, HostCard, Screen, Ui } from "./types.ts"; @@ -102,8 +103,9 @@ const RED_KEY = 403; * measuring page prices it once more: a remote with no spare key still gets every screen. */ const QUIET_MS = 15_000; -/** The screens the console cannot draw; everything else is the console's. */ -const WEB_SCREENS = new Set(["accept", "trust", "link", "streaming"]); +/** The screens the console cannot draw, and the page's settings sheet, which the web shell's + * sidebar and stream overlay open and only it can close; everything else is the console's. */ +const WEB_SCREENS = new Set(["accept", "trust", "link", "streaming", "settings"]); /** How long the console waits on a `FetchProfiles` answer before it dials without one * (`pf_console_ui` `PROFILES_WAIT`). */ @@ -130,6 +132,9 @@ export class ConsoleUi implements Ui { /** The web shell was told to stand aside for a launch hold over the stream. */ private held = false; private screen: Screen | null = null; + /** The last screen `follow` saw. The settings sheet is no step of a flow, so the screen after + * it follows the one before it: a stream it opened over still ends. */ + private followed: Screen | null = null; /** Host rows by the key the console knows them by, and the origin each stands for. */ private origins = new Map(); private hosts: HostCard[] = []; @@ -286,10 +291,16 @@ export class ConsoleUi implements Ui { this.screen = screen; // A page-level change of screen counts as a move, as a key does. if (was?.kind !== screen.kind) this.inputAt = performance.now(); - const web = (WEB_SCREENS.has(screen.kind) && !this.held) || !this.started; - this.fallback.render(web ? screen : { kind: "console" }); - if (!this.started) return; - this.follow(was, screen); + this.fallback.render(this.shellScreen(screen)); + if (!this.started || screen.kind === "settings") return; + this.follow(this.followed, screen); + this.followed = screen; + } + + /** What the web shell draws for `screen`: one of its own sheets while no launch hold covers + * it, every screen before the console is up, and otherwise nothing. */ + private shellScreen(screen: Screen): Screen { + return (WEB_SCREENS.has(screen.kind) && !this.held) || !this.started ? screen : { kind: "console" }; } destroy(): void { @@ -359,11 +370,12 @@ export class ConsoleUi implements Ui { } if (drew) this.cost(now - before, now, width, height); this.state = this.engine.console.state(); - // A launch hold covers the stream until the game is up: the page's own overlay waits. + // A launch hold covers the stream until the game is up: the page's own overlay waits. A + // hold that ends short of the stream (cancelled, failed) leaves a console screen. const holding = !!(this.state & CONSOLE_STATE.HOLDS_LAUNCH); if (holding !== this.held && this.screen) { this.held = holding; - this.fallback.render(holding ? { kind: "console" } : this.screen); + this.fallback.render(this.shellScreen(this.screen)); } const showing = this.showing(); // The canvas takes the pointer only while the console is on it; over a stream the pointer @@ -531,8 +543,8 @@ export class ConsoleUi implements Ui { } this.imeText = field.text; this.ime.value = field.text; - // A PIN or a port wants the number pad; an address wants the dot beside the digits. - this.ime.inputMode = field.digits ? "numeric" : "decimal"; + // A PIN or a port wants the number pad; a name, a title or an address the full keyboard. + this.ime.inputMode = field.digits ? "numeric" : "text"; this.ime.focus(); this.ime.setSelectionRange(field.text.length, field.text.length); } @@ -613,6 +625,8 @@ export class ConsoleUi implements Ui { this.hosts = s.hosts; this.pushHosts(); if (s.error) this.fetchFailed("The host did not answer", s.error); + // Home only with the engine on no host: what the console asked for will not follow. + this.dropPending(); if (was?.kind === "streaming" || (this.dialled && was?.kind !== "home")) { this.dialled = false; c.phase(3); @@ -651,6 +665,7 @@ export class ConsoleUi implements Ui { return; case "error": this.dialled = false; + this.dropPending(); this.fetchFailed(s.head, s.text); c.phase(2, `${s.head}. ${s.text}`); this.pushPair("Idle"); @@ -660,6 +675,15 @@ export class ConsoleUi implements Ui { } } + /** Forget the steps waiting on a connect that ended, so a later visit to that host does not + * play, pair or knock unasked. */ + private dropPending(): void { + this.pendingPlay = null; + this.profilesAsk = null; + this.pendingPin = null; + this.pendingKnock = null; + } + /** The shelf the console is waiting on could not be reached: say so on it, with a retry. */ private fetchFailed(title: string, body: string): void { if (!this.fetching) return; @@ -768,42 +792,18 @@ export class ConsoleUi implements Ui { const known = new Map(this.engine.knownHosts().map((h) => [h.origin, h])); this.origins.clear(); const rows = this.hosts.map((h) => { - const row = this.rowOf(h, known.get(h.origin)?.fingerprint ?? h.fingerprint); + const row = hostRow(h, known.get(h.origin)?.fingerprint ?? h.fingerprint); this.origins.set(row.key, h.origin); return row; }); this.engine.console.push(CONSOLE_PUSH.HOSTS, rows); } - private rowOf(h: HostCard, fp: string | undefined): ConsoleHostRow { - const url = new URL(h.origin); - const addr = h.plane ?? url.hostname; - const mgmt = Number(url.port) || 47990; - return { - key: fp ?? `${addr}:${mgmt}`, - id: h.origin, - name: h.label ?? h.name ?? addr, - addr, - port: 9778, - fp_hex: fp ?? "", - paired: !!fp, - saved: true, - online: h.reach === "ok", - mgmt_port: mgmt, - can_wake: !!h.wake && h.reach !== "ok", - last_used: h.seen ? Math.floor(h.seen / 1000) : null, - os: "", - pin: null, - bound_preset: null, - profile: h.profile ?? null, - }; - } - /** The row for an origin, from the home list or, for one only just added, from what the * engine knows. */ private row(origin: string): ConsoleHostRow { const card = this.hosts.find((h) => h.origin === origin) ?? ({ origin } as HostCard); - return this.rowOf(card, this.fingerprint(origin)); + return hostRow(card, this.fingerprint(origin)); } private fingerprint(origin: string): string | undefined { @@ -840,10 +840,7 @@ export class ConsoleUi implements Ui { return; } if (a === "CancelConnect") { - this.pendingPlay = null; - this.profilesAsk = null; - this.pendingPin = null; - this.pendingKnock = null; + this.dropPending(); this.dialled = false; // A request for access is withdrawn, so a late approval admits nothing. if (this.engine.current.kind === "awaiting-approval") this.actions?.cancelRequest(); @@ -1045,7 +1042,8 @@ export class ConsoleUi implements Ui { } /** Wake a host and keep the console's wake card current: seconds while the page's own wake - * polls it, then online (the console connects by itself if asked to) or timed out. */ + * polls it, then online (the console connects by itself if asked to) or timed out. A wake + * that never went out takes the card down; the page's toast says why. */ private startWake(req: ConsoleReq, key: string, origin: string, then: boolean): void { this.endWake(false); const name = this.hosts.find((h) => h.origin === origin)?.name ?? key; @@ -1063,8 +1061,11 @@ export class ConsoleUi implements Ui { if (online && !then) window.setTimeout(() => this.endWake(true), 1500); } }; - this.waking = { req, key, origin, name, then, since, timer: window.setInterval(tick, 1000) }; - this.actions?.wake(origin); + const waking = { req, key, origin, name, then, since, timer: window.setInterval(tick, 1000) }; + this.waking = waking; + void this.actions?.wake(origin).then((sent) => { + if (!sent && this.waking === waking) this.endWake(true); + }); tick(); } @@ -1076,10 +1077,7 @@ export class ConsoleUi implements Ui { /** The origin a console key or address stands for. */ private originOf(key: string, addr: string): string | undefined { - const byKey = this.origins.get(key); - if (byKey) return byKey; - for (const [k, o] of this.origins) if (k.startsWith(`${addr}:`)) return o; - return this.hosts.find((h) => (h.plane ?? new URL(h.origin).hostname) === addr)?.origin; + return originFor(this.origins, this.hosts, key, addr); } } @@ -1088,7 +1086,6 @@ export class ConsoleUi implements Ui { function imeField(): HTMLInputElement { const input = document.createElement("input"); input.type = "text"; - input.inputMode = "decimal"; input.autocomplete = "off"; input.tabIndex = -1; input.setAttribute("aria-hidden", "true"); diff --git a/apps/web/src/ui/cover.ts b/apps/web/src/ui/cover.ts index 0494c3d..df2d9dc 100644 --- a/apps/web/src/ui/cover.ts +++ b/apps/web/src/ui/cover.ts @@ -75,6 +75,8 @@ export async function coverBytes(blob: Blob): Promise { const { width: w, height: h } = bitmap; scratch ??= new OffscreenCanvas(COVER_W, COVER_H).getContext("2d", { willReadFrequently: true }); if (!scratch) return null; + // The scratch still holds the last cover, which a transparent one would show through. + scratch.clearRect(0, 0, w, h); scratch.drawImage(bitmap, 0, 0); bitmap.close(); return bmp(w, h, scratch.getImageData(0, 0, w, h).data); diff --git a/apps/web/src/ui/frame.tsx b/apps/web/src/ui/frame.tsx index c0800b2..dbd47cd 100644 --- a/apps/web/src/ui/frame.tsx +++ b/apps/web/src/ui/frame.tsx @@ -55,8 +55,9 @@ export function Frame({ return (
{/* Pinned at viewport height; the page beside it scrolls. `overflow-y-auto` lets the nav - itself scroll on a very short viewport rather than push Console mode off the bottom. */} -