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
35 changes: 30 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,48 @@ them over mDNS, and one typed by its IP address goes through the server too. On
video goes from the host to the browser directly; only the host's management API passes through
the container, on the page's own origin, which is what Safari needs.

Two other shapes, in [`deploy/`](deploy): behind a reverse proxy that already has a certificate
(`compose.proxy.yaml`), and on a tailnet with Tailscale's certificate, which also lets you play
away from home (`compose.tailscale.yaml`).
Three other shapes, in [`deploy/`](deploy): behind a reverse proxy that already has a certificate
(`compose.proxy.yaml`), on a tailnet with Tailscale's certificate (`compose.tailscale.yaml`), and
at your own domain with Caddy in front (`compose.public.yaml`). The last two let you play away
from home.

| Setting | Default | |
|---|---|---|
| `LISTEN` | `0.0.0.0:8443` | |
| `TLS` | `self-signed` | `self-signed`, `off` behind a proxy, or `cert.pem,key.pem` |
| `TLS_NAMES` | | Domains the page is opened at. It answers only to these, IP addresses and names no public DNS holds (`localhost`, `desk`, `.local`, `.home.arpa`, `.internal`); with your own certificate and none listed, to any name. The self-signed certificate covers them too |
| `TLS_NAMES` | | The names and addresses you open the page at, which the self-signed certificate covers. The page answers only to these, IP addresses and names no public DNS holds (`localhost`, `desk`, `.local`, `.home.arpa`, `.internal`); with your own certificate and none listed, to any name |
| `PUNKTFUNK_HOSTS` | | Hosts mDNS cannot find: `name=address[:port][#fingerprint]`, comma-separated |
| `DISCOVER` | on | `0` turns the mDNS browse off |
| `ADD_HOSTS` | on | `0` stops the page reaching a host typed by address. Set it when the page is reachable from outside your network |
| `ADD_HOSTS` | on | `0` stops the page reaching a host typed by its address. Either way, the server relays to a typed address only once a Punktfunk host has proven itself there |

The server pins every host before trusting it, as the native clients do: by the fingerprint it
was listed with, the one it announces, or the one it presented first (`/data/pins.json`). It adds
no credential of its own; the browser's device key stays the only one.

## From outside your network

Tailscale is the simplest way. Put this machine and your hosts on a tailnet, and the page opens
wherever your devices are on the tailnet. It takes two files from [`deploy/`](deploy),
`compose.tailscale.yaml` and `tailscale-serve.json`, side by side. Before the first start, set
`TLS_NAMES` in the compose file to the page's tailnet name, and `PUNKTFUNK_HOSTS` to your hosts
by their tailnet addresses, since hosts don't announce themselves across a tailnet.

Without Tailscale, give the page a domain with a real certificate. `compose.public.yaml` puts
Caddy in front, which gets and renews the certificate for you:

```sh
DOMAIN=play.example.com docker compose -f compose.public.yaml up -d
```

Point the domain at your home's address and forward TCP 80 and 443 on your router to this machine.
Keep the hosts' own ports closed: a browser outside your network streams through the server.

Forwarding the port of the self-signed setup does not work. From the internet, a browser can't
tell a self-made certificate from an impostor's, so the server shows a browser at a public
address a page that says so instead of the client.

A browser that isn't paired with a host is rate-limited and can't wake that host.

## Trust, and the one step it costs you

Served by the container, a page reaches its hosts on its own origin and none of this section's
Expand Down
29 changes: 23 additions & 6 deletions apps/web/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
type LibraryEntry,
type ListedProfile,
linkFor,
onPass,
packaged,
type PageLink,
pageLog,
Expand All @@ -35,9 +36,11 @@ import {
reachTarget,
SEAT_POLL_MS,
seatGate,
serverFetch,
type Settings,
settings,
statusOf,
TOO_MANY,
VersionSkew,
wakeFailed,
wakingLine,
Expand Down Expand Up @@ -165,6 +168,8 @@ class App {
/** Whether that server also proxies a host typed here by its IP address. */
private readonly viaServer: boolean,
) {
// A login's pass covers another host: the server now tells this browser its address and wake.
onPass(() => void this.refreshConfigured());
ui.mount({
connect: (address) => {
this.adding = false;
Expand Down Expand Up @@ -487,6 +492,13 @@ class App {
void this.probe(cards.map((h) => h.origin));
}

/** The server's list again, as a pass holder sees it. */
private async refreshConfigured(): Promise<void> {
const again = await configuredHosts();
for (const [origin, c] of again.listed) this.configured.set(origin, c);
this.redrawLists();
}

/** Every host this page knows: the server's first, under the name it gives them; then the ones
* typed here. Each with what a probe last said about it. */
private cards(): HostCard[] {
Expand All @@ -496,7 +508,7 @@ class App {
...known.get(origin),
origin,
name: c.name,
plane: c.plane,
...(c.plane ? { plane: c.plane } : {}),
...(c.wake ? { wake: c.wake, waking: this.waking.has(origin) } : {}),
})),
...[...known.values()].filter((h) => !this.configured.has(h.origin)),
Expand Down Expand Up @@ -539,7 +551,7 @@ class App {
if (known) {
const { origin: _old, ...record } = known;
hosts.forget(address);
hosts.remember(routed.api, { ...record, plane: routed.plane });
hosts.remember(routed.api, { ...record, ...(routed.plane ? { plane: routed.plane } : {}) });
}
return routed;
}
Expand Down Expand Up @@ -646,7 +658,11 @@ class App {
this.waking.add(origin);
this.redrawLists();
try {
const r = await fetch(url, { method: "POST" });
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");
}
if (!r.ok) throw new Error(`wake refused (${r.status})`);
let up = false;
for (let tries = 0; tries < 20 && !up; tries++) {
Expand Down Expand Up @@ -1323,17 +1339,18 @@ interface Configured extends HostTarget {
*/
async function configuredHosts(): Promise<{ listed: Map<string, Configured>; viaServer: boolean }> {
try {
const r = await fetch("./config.json", { cache: "no-store" });
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 }>;
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 } : {};
return [api, { api, plane: h.plane, name: h.name, ...(wake ? { wake } : {}), ...bridge }];
const plane = h.plane ? { plane: h.plane } : {};
return [api, { api, ...plane, name: h.name, ...(wake ? { wake } : {}), ...bridge }];
}),
);
return { listed, viaServer: c.add === true };
Expand Down
7 changes: 4 additions & 3 deletions deploy/compose.proxy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
# proxy's certificate, so no browser warns. Point the proxy at http://<this machine>:8080.
#
# The page's origin is your proxy's domain: add it to each host's Browser origins (console,
# Streaming, advanced), or leave that list empty to allow any page.
# Streaming, advanced). A browser on a domain that isn't listed there has to pair with a PIN.
#
# On networks that block UDP the page streams through this server. The host then sees every
# such stream as coming from the proxy's address, so it treats it as local.
# The server tells each host who the visitor is, from the X-Forwarded-For or Forwarded header the
# proxy adds (nginx: `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`). A proxy
# that sends neither leaves every visitor unknown, which a host treats as the internet.
services:
punktfunk-web:
image: git.unom.io/unom/punktfunk-client-web:latest
Expand Down
50 changes: 50 additions & 0 deletions deploy/compose.public.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# The browser client at your own domain, with a real certificate, reachable from anywhere.
#
# DOMAIN=play.example.com docker compose -f compose.public.yaml up -d
# open https://play.example.com
#
# Point the domain at your home's public address and forward TCP 80 and 443 on the router to this
# machine; Caddy gets and renews the certificate on its own. Keep the hosts' own ports closed on
# the router: a browser outside your network streams through this server, never straight to a host.
services:
caddy:
image: caddy:2
restart: unless-stopped
# Listens on 80 and 443 of this machine.
network_mode: host
configs:
- source: caddyfile
target: /etc/caddy/Caddyfile
volumes:
- caddy-data:/data
- caddy-config:/config

punktfunk-web:
image: git.unom.io/unom/punktfunk-client-web:latest
restart: unless-stopped
# The host's network, so the server finds hosts over mDNS and can wake them. It listens on
# loopback only: everything from outside comes through Caddy.
network_mode: host
environment:
TLS: "off"
LISTEN: 127.0.0.1:8080
TLS_NAMES: ${DOMAIN:?set DOMAIN to the page's domain}
# Hosts mDNS cannot find: name=address[:port][#fingerprint], comma-separated.
# PUNKTFUNK_HOSTS: desk=192.168.1.21
volumes:
- punktfunk-web:/data

# Caddy passes the browser's Host header through and sets X-Forwarded-For itself, over whatever
# the browser sent. HSTS belongs here, where the name is the page's own.
configs:
caddyfile:
content: |
${DOMAIN} {
header Strict-Transport-Security "max-age=31536000"
reverse_proxy 127.0.0.1:8080
}

volumes:
caddy-data:
caddy-config:
punktfunk-web:
3 changes: 3 additions & 0 deletions deploy/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
# docker compose up -d
# open https://<this machine>:8443 and accept its certificate once
#
# The self-made certificate is for your own network. A browser at a public address gets a page
# saying so and nothing else; from outside, use compose.tailscale.yaml or compose.public.yaml.
#
# Each host also needs Browser streaming on (its console, Streaming settings) and UDP 9778 open:
# video goes from the host to the browser directly, never through this container.
services:
Expand Down
20 changes: 18 additions & 2 deletions packages/stream/src/carrier/frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,28 @@
// 2 host → browser one whole unidirectional stream
// 3 both u32 close code, then the UTF-8 reason
// 4 both ping: f64 sender ms; pong: the same f64, then u32 the bridge's RTT in µs
// 5 browser → host first: the 32-byte pass, for the paired pool
// 6 browser → host first, empty: a browser without a pass for this host, asking to pair

export const TAG = { DATAGRAM: 0, CONTROL: 1, UNI: 2, CLOSE: 3, PING: 4 } as const;
export const TAG = { DATAGRAM: 0, CONTROL: 1, UNI: 2, CLOSE: 3, PING: 4, PASS: 5, PAIR: 6 } as const;

export type Frame =
| { tag: typeof TAG.DATAGRAM | typeof TAG.CONTROL | typeof TAG.UNI; bytes: Uint8Array }
| { tag: typeof TAG.CLOSE; code: number; reason: string }
| { tag: typeof TAG.PING; sentMs: number; bridgeRttUs?: number };
| { tag: typeof TAG.PING; sentMs: number; bridgeRttUs?: number }
| { tag: typeof TAG.PASS; pass: Uint8Array }
| { tag: typeof TAG.PAIR };

export function encode(f: Frame): Uint8Array<ArrayBuffer> {
switch (f.tag) {
case TAG.PASS: {
const out = new Uint8Array(33);
out[0] = f.tag;
out.set(f.pass, 1);
return out;
}
case TAG.PAIR:
return new Uint8Array([f.tag]);
case TAG.CLOSE: {
const reason = new TextEncoder().encode(f.reason);
const out = new Uint8Array(5 + reason.length);
Expand Down Expand Up @@ -59,6 +71,10 @@ export function decode(msg: Uint8Array): Frame | null {
if (msg.length === 9) return { tag, sentMs: view.getFloat64(1) };
if (msg.length === 13) return { tag, sentMs: view.getFloat64(1), bridgeRttUs: view.getUint32(9) };
return null;
case TAG.PASS:
return msg.length === 33 ? { tag, pass: msg.subarray(1) } : null;
case TAG.PAIR:
return msg.length === 1 ? { tag } : null;
default:
return null;
}
Expand Down
20 changes: 16 additions & 4 deletions packages/stream/src/carrier/ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ function fakeFeed() {
}

/** A carrier whose socket has opened, the socket, and what reached the feed. */
async function opened(t: TestContext) {
async function opened(t: TestContext, pass: Uint8Array | null = null) {
t.mock.timers.enable({ apis: ["setInterval"] });
const { feed, got } = fakeFeed();
const carrier = new WsCarrier(feed, "wss://page.example/w/abc?port=9778&hash=00");
const carrier = new WsCarrier(feed, "wss://page.example/w/abc?port=9778&hash=00", pass);
const opening = carrier.open();
const ws = FakeSocket.last;
ws.open();
Expand All @@ -72,14 +72,26 @@ test("the bridge URL is the page server's own, with the plane's port and hash",
assert.equal(bridgeUrl("wa/192.168.1.21:47990", 9784, hash, "http://localhost:5173/"), `ws://localhost:5173/wa/192.168.1.21:47990?port=9784&hash=${hash}`);
});

test("a browser without a pass asks to pair before anything else", async (t) => {
const { ws } = await opened(t);
assert.deepEqual(ws.sent[0], { tag: TAG.PAIR });
});

test("a browser with a pass for the host shows it before anything else", async (t) => {
const pass = new Uint8Array(32).fill(7);
const { ws } = await opened(t, pass);
assert.deepEqual(ws.sent[0], { tag: TAG.PASS, pass });
assert.equal(ws.sent.filter((f) => f.tag === TAG.PASS || f.tag === TAG.PAIR).length, 1);
});

test("an open bridge opens the control stream with its type byte first", async (t) => {
const { carrier, ws, got } = await opened(t);
assert.equal(ws.binaryType, "arraybuffer");
assert.deepEqual(got, ["ready"]);
assert.deepEqual(ws.sent[0], { tag: TAG.CONTROL, bytes: new Uint8Array([0]) });
assert.deepEqual(ws.sent[1], { tag: TAG.CONTROL, bytes: new Uint8Array([0]) });
carrier.sendControl(new Uint8Array([7, 8]));
assert.equal(carrier.sendDatagram(new Uint8Array([1])), true);
assert.deepEqual(ws.sent.slice(1), [
assert.deepEqual(ws.sent.slice(2), [
{ tag: TAG.CONTROL, bytes: new Uint8Array([7, 8]) },
{ tag: TAG.DATAGRAM, bytes: new Uint8Array([1]) },
]);
Expand Down
5 changes: 5 additions & 0 deletions packages/stream/src/carrier/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export class WsCarrier implements Carrier {
constructor(
private readonly feed: Feed,
private readonly url: string,
/** This browser's pass when it covers the host: the paired pool. Without one, the pairing
* pool, which reaches only the plane the host published. */
private readonly pass: Uint8Array | null = null,
) {}

open(): Promise<void> {
Expand All @@ -42,6 +45,8 @@ export class WsCarrier implements Carrier {
ws.onopen = () => {
if (this.ws !== ws) return;
this.live = true;
// First, before anything else: which of the bridge's two pools this session is for.
this.send(this.pass ? { tag: TAG.PASS, pass: this.pass } : { tag: TAG.PAIR });
this.ping = setInterval(() => this.send({ tag: TAG.PING, sentMs: performance.now() }), PING_MS);
this.openControl();
resolve();
Expand Down
13 changes: 9 additions & 4 deletions packages/stream/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { type TunnelFetch, tunnelFetch } from "./tunnel.ts";
import { type Feed, wasmFeed } from "./carrier/feed.ts";
import { WtCarrier } from "./carrier/wt.ts";
import { bridgeUrl, WsCarrier } from "./carrier/ws.ts";
import { passFor } from "./pass.ts";

export type { AudioSnapshot, AudioState } from "./audio.ts";
export type { MicState } from "./mic.ts";
Expand Down Expand Up @@ -431,7 +432,7 @@ export class Engine {
this.planeHost =
typeof address === "string"
? (this.opts.transportHost ?? new URL(origin).hostname)
: address.plane;
: (address.plane ?? "");
this.set({ kind: "reaching", origin });

const tunnel = typeof address === "object" && address.tunnel === true;
Expand Down Expand Up @@ -497,7 +498,8 @@ export class Engine {
}
if (stale()) return;
}
pf.hosts.remember(origin, typeof this.target === "object" && this.target ? { plane: this.target.plane } : {});
const plane = typeof this.target === "object" ? this.target?.plane : undefined;
pf.hosts.remember(origin, plane ? { plane } : {});
// Every management call from here rides the plane, pinned to the hash just verified. The
// tunnel is dialled by the first call, not now: the key may still say this host is unpaired.
if (tunnel) {
Expand Down Expand Up @@ -1052,7 +1054,10 @@ export class Engine {
const port = this.seatPlane?.port ?? this.plane.port;
const hash = this.seatPlane?.certHash ?? this.plane.cert_hash_sha256;
const pin = this.opts.carrier;
const wt = pin === "wt" || (!pin && "WebTransport" in globalThis && carrierHint.get(this.origin) !== "ws");
// No plane address: a stranger outside the server's network, whom only the bridge carries.
const wt =
this.planeHost !== "" &&
(pin === "wt" || (!pin && "WebTransport" in globalThis && carrierHint.get(this.origin) !== "ws"));
this.openCarrier(wt ? "wt" : "ws", port, hash);
}

Expand All @@ -1075,7 +1080,7 @@ export class Engine {
kind === "wt"
? new WtCarrier(this.feed, `https://${this.planeHost}:${port}/pf2`, hash)
: bridge
? new WsCarrier(this.feed, bridgeUrl(bridge, port, hash))
? new WsCarrier(this.feed, bridgeUrl(bridge, port, hash), passFor(pf.hosts.fingerprint(origin)))
: null;
let opening: Promise<void> | null = null;
if (carrier) {
Expand Down
Loading
Loading