# Browser client

The browser client connects web apps to a service behind a vagus relay and pins the service's leaf certificate to its route ID so the relay cannot impersonate the service. See [Trust boundaries and TLS separation](https://vagus.neuroplast.io/docs/security#trust-boundaries-and-tls-separation) for the end-to-end tunnel layout.

| Layer | Environment | Transport | Statement verification | Min browser (Chrome / Firefox / Safari) |
| --- | --- | --- | --- | --- |
| `pkg/browser/web/client.mjs` (`client.d.mts`) | JS / TypeScript (zero dependencies) | WebTransport only | WebCrypto Ed25519 in JS | 137 / 132 / 26.4 |
| `pkg/browser` (`neuroplast.io/vagus/pkg/browser`) | TinyGo / Go Wasm (uses `client.mjs` as bridge) | WebTransport + automatic post-quantum WebSocket fallback | Go (`pkg/pin`) inside Wasm | 131 / 132 / 26.4 |

## Certificate pinning

A service behind vagus presents short-lived leaf certificates signed by its identity key and publishes a signed statement listing their SHA-256 hashes (see [Certificate pinning](https://vagus.neuroplast.io/docs/security#certificate-pinning)). `dial` uses the first pinning source supplied in its options:

1. `certificateHashes`: SHA-256 digests the page already trusts.
2. `statement`: raw statement bytes obtained out of band (from your own server, an invitation, or a QR code), verified against the route ID.
3. `relayURL`: fetches the statement from the relay's HTTPS endpoint and verifies it against the route ID.

If none of these is set, `dial` rejects unless `trustRelayOperator: true` is passed. Setting `trustRelayOperator: true` uses normal browser Web PKI, which trusts the relay operator (who controls DNS for the relay domain).

Refusals reject with a `VagusError` whose `code` explains why:

| `code` | Cause |
| --- | --- |
| `no-statement` | The relay has no statement for the route, or no pinning source and no `trustRelayOperator` were passed |
| `wrong-route` | The statement was not signed by the key matching the route ID |
| `no-valid-leaf` | None of the certificates in the statement is valid now (a client offline for two weeks needs a fresh statement) |
| `malformed` | The bytes could not be decoded as a statement |
| `no-webtransport` | The browser does not support `WebTransport` |
| `no-hash-pinning` | The browser's `WebTransport` ignores `serverCertificateHashes`, which would silently fall back to Web PKI |
| `no-ed25519` | Browser WebCrypto does not support Ed25519 (JavaScript verification path only) |

In TinyGo and Go Wasm, `pkg/browser` verifies statements in Go via `pkg/pin` and returns `pin.ErrWrongRoute`, `pin.ErrNoValidLeaf`, `browser.ErrNoStatement`, `browser.ErrNoWebTransport`, and `browser.ErrNoHashPinning`.

### Direct dials (without a relay)

When a browser can reach the service directly (for example, on the same LAN), pass the route ID in `routeID` (Go: `Options.RouteID`) and dial any HTTPS URL, including IP literals like `https://192.168.1.20:8733/`. The client verifies the pin against `routeID` instead of the URL's first hostname label.

Direct dials accept only `certificateHashes` or `statement`. They reject `relayURL`, `admission`, `ticket`, and `trustRelayOperator`, ignore defaults set by `install()`, and never fall back to a WebSocket.

### Hash-pinning probe and CSP

Browsers ignore unrecognized WebIDL dictionary fields, so older browsers with `WebTransport` but without `serverCertificateHashes` (such as Firefox 114-124, including ESR 115) would silently fall back to Web PKI. Before the first pinned dial on a page, `dial` probes whether `WebTransport` reads `serverCertificateHashes` and rejects with `no-hash-pinning` if not. On supported browsers, no connection is opened. On unsupported browsers, it briefly constructs and closes a session to `hash-pinning-probe.invalid`, which may trigger a CSP violation report under strict `connect-src` rules. Ignore those reports and do not allowlist that hostname.

If your page uses a Content Security Policy, allow the relay's HTTPS origin, the service's WebTransport origins, and `'unsafe-webtransport-hashes'` in `connect-src` (plus `wss://<relay>` if using WebSocket fallback). Because pinning runs inside page JS or Wasm, serve the page from an origin you trust.

## JavaScript and TypeScript

Copy `pkg/browser/web/client.mjs` (and [`client.d.mts`](https://github.com/neuroplastio/vagus/blob/main/pkg/browser/web/client.d.mts) for TypeScript) into your project.

```ts
import { dial, VagusError } from "./client.mjs";

const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000);
try {
  const session = await dial("https://<route-id>.relay.example.com/echo", {
    relayURL: "https://control.relay.example.com",
    signal: controller.signal,
  });
  const stream = await session.createBidirectionalStream();
  const writer = stream.writable.getWriter();
  await writer.write(new TextEncoder().encode("hello"));
  await writer.close();
  // read stream.readable until done, then call session.close()
} catch (e) {
  if (e instanceof VagusError) console.log("refused:", e.code);
  else throw e;
}
```

To inspect signed application data in the statement before dialing without fetching it twice:

```ts
import { dial, statement } from "./client.mjs";

const st = await statement("https://control.relay.example.com", routeID);
checkMyData(st.data); // application-defined bytes, up to 2 KiB
const session = await dial(url, { statement: st.bytes });
```

### Exports (`client.mjs`)

| Export | Purpose |
| --- | --- |
| `dial(url, options?)` | Opens a pinned `WebTransport` (with `allowPooling: false`); `signal` aborts fetch, admission, challenge, and handshake |
| `ticket(relayURL, url, options?)` | Requests a single-use admission ticket label (pass back as `ticket` to `dial`) |
| `fetchStatement(relayURL, id, options?)` | Returns raw statement `Uint8Array` or `null` |
| `statement(relayURL, id, options?)` | Fetches and verifies a statement in one call |
| `verifyStatement(bytes, id, now?)` | Verifies raw statement bytes locally |
| `routeID(key)` | Computes the route ID string from a 32-byte Ed25519 public key |
| `install(options?)` | Registers the Wasm bridge globals (`vagusDial`, `vagusFetchStatement`, `vagusTicket`) and optional relay defaults |

Key `DialOptions` fields: `routeID` (direct dial), `relayURL`, `admission`, `getChallenge`, `pass`, `signAdmission`, `clearanceKey`, `onClearance`, `ticket`, `statement`, `certificateHashes`, `trustRelayOperator`, `signal`, and `now`. See [`client.d.mts`](https://github.com/neuroplastio/vagus/blob/main/pkg/browser/web/client.d.mts) for exact TypeScript types and [Browser admission](https://vagus.neuroplast.io/docs/admission) for ticket, pass, and clearance options.

## TinyGo and Go Wasm

Add the module:

```sh
go get neuroplast.io/vagus/pkg/browser@latest
```

Load `client.mjs` and call `install()` before starting the Wasm module:

```html
<script src="./wasm_exec.js"></script>
<script type="module">
  import { install } from "./client.mjs";
  install();
  const go = new Go();
  const { instance } = await WebAssembly.instantiateStreaming(fetch("./app.wasm"), go.importObject);
  await go.run(instance);
</script>
```

Options passed to `install()` (`relayURL`, `admission`, `getChallenge`, `trustRelayOperator`) act as defaults for relayed `browser.Dial` calls and can be overridden per call in Go. Direct dials (`RouteID`) ignore them.

```go
session, err := browser.Dial(ctx, "https://"+routeID+".relay.example.com/echo", browser.Options{
	RelayURL: "https://control.relay.example.com",
})
if err != nil {
	return err // pin.ErrWrongRoute, pin.ErrNoValidLeaf, browser.ErrNoStatement, ...
}
defer session.Close()
stream, err := session.OpenStream()
```

See [pkg.go.dev/neuroplast.io/vagus/pkg/browser](https://pkg.go.dev/neuroplast.io/vagus/pkg/browser) for the full API (`Dial`, `FetchStatement`, `Options`, `Session`, `Stream`).

`Dial` verifies statements in Go and respects `ctx` through fetch and handshake; if `ctx` cancels right as the session comes up, `Dial` closes it before returning. `Stream` implements `io.ReadWriteCloser` with `CloseWrite()` (sending FIN while leaving reads open), buffers leftover bytes when a browser chunk exceeds `len(b)`, and waits for browser backpressure on `Write`.

Never call `pkg/browser` synchronously inside a `js.FuncOf` callback. Each call waits on a JS Promise that cannot settle until the callback returns; launch a goroutine instead (see [the browser example](https://github.com/neuroplastio/vagus/blob/main/pkg/browser/example/main.go)).

Build with TinyGo using TinyGo's matching `wasm_exec.js`:

```sh
cp "$(tinygo env TINYGOROOT)/targets/wasm_exec.js" dist/
GOTOOLCHAIN=local tinygo build -target=wasm -no-debug -o dist/app.wasm ./cmd/web
```

Standard Go (`GOOS=js GOARCH=wasm`) works with `$(go env GOROOT)/lib/wasm/wasm_exec.js`; do not mix `wasm_exec.js` across toolchains. Verifying statements inside TinyGo Wasm adds roughly 290 KB uncompressed (110 KB gzipped) for `msgp`, `crypto/ed25519`, and SHA-2. If binary size is tight, verify statements in `client.mjs` and pass `CertificateHashes` into Wasm.

### WebSocket fallback

When a network blocks UDP (stopping QUIC and WebTransport), `browser.Dial` connects through a WebSocket to the relay's HTTPS listener at `wss://<relay>/v1/sessions/<route-id>` (or `/v1/sessions/<ticket>` with admission). Inside the WebSocket, the client runs hybrid post-quantum `Noise_NKhfs_25519+MLKEM1024_ChaChaPoly_SHA256` against a static key listed in the route's signed statement. The request path and all stream data are end-to-end encrypted under ML-KEM-1024 + X25519; the relay forwards raw bytes without reading them, seeing only the `Origin` header (passed to the service), packet sizes, and timing.

`Dial` starts WebTransport first, then starts the WebSocket if WebTransport fails or has not connected after 1.5 seconds. Whichever connects first wins and the other is closed; `Session.Transport()` reports `TransportWebTransport` or `TransportWebSocket`, and `Options.WebTransportOnly` disables fallback. With `Admission`, the 1.5-second timer starts after the first ticket arrives, and the WebSocket requests its own ticket (reusing any clearance from the first ticket when `SignAdmission` is set, so the user solves at most one challenge).

Fallback requires `RelayURL` and a service running the embedded connector with `connector.WithSessions()` and `SetNoiseKeys` so its statement lists Noise keys ([Go integration](https://vagus.neuroplast.io/docs/go-integration)). `CertificateHashes` alone and `TrustRelayOperator` do not include Noise keys and never fall back. The `vagus connect` CLI forwards QUIC only and does not accept WebSocket sessions.

WebSocket sessions expose the same `Stream` API with 256 KiB per-stream and 1 MiB per-session flow-control windows. If your page uses a CSP, add `wss://<relay>` alongside `https://<relay>` in `connect-src`.

## Local test

For a single-binary WebTransport demo with an embedded connector, run [examples/chat](https://github.com/neuroplastio/vagus/tree/main/examples/chat).

To test `pkg/browser`'s TinyGo echo page against a local WebTransport echo service on `127.0.0.1:4443`, first start `vagus relay` and `vagus connect` as in [Local setup](https://vagus.neuroplast.io/docs/local-setup), then build and serve the browser example:

```sh
mise exec -- make browser-example
python3 -m http.server 8000 --bind 127.0.0.1 --directory build/browser
```

Because the local relay certificate is self-signed, launch Chromium with its SPKI hash and a host resolver rule:

```sh
spki=$(openssl x509 -in "$state/local/control.pem" -pubkey -noout |
  openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64)
chromium --user-data-dir="$(mktemp -d)" \
  --ignore-certificate-errors-spki-list="$spki" \
  --host-resolver-rules="MAP *.relay.test 127.0.0.1" http://localhost:8000
```

Enter `https://<id>.relay.test:19452/echo` and relay URL `https://localhost:19453`, then click **Test echo**. It opens one WebTransport session, echoes two streams, and prints `Echo verified on both streams, over webtransport.` (`vagus connect` does not accept WebSocket sessions, so this test exercises WebTransport only.)

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `call install() from web/client.mjs before starting Wasm` | Call `install()` before `go.run(instance)`. |
| Page hangs on click | A `pkg/browser` call ran directly inside a `js.FuncOf` callback instead of a goroutine. |
| `no-statement` | The connector has not published a statement (check `-leaf-dir` and that `admitted` was logged), or `relayURL` names the wrong relay. |
| `wrong-route` | The URL's first hostname label does not match the key that signed the statement. |
| `no-valid-leaf` | The service or browser clock is skewed, or the connector has not rotated leaves in the past two weeks. |
| Handshake fails after statement verification | The service is serving a leaf not listed in the statement. Confirm it serves `cert.pem` from `-leaf-dir` and reloads on change. |
| Handshake rejected by the service | Check the WebTransport URL path and the service's `Origin` check. |
| `WebAssembly.instantiateStreaming` fails | Serve `.wasm` files with `Content-Type: application/wasm`. |
