Browser clients
Connect browser inventory and terminal interfaces with credentials issued by an application backend.
Browser packages observe or connect to rstream resources through web APIs. They do not host a native agent, load a CLI context or receive an application's client secret. A backend authenticates the application user, authorizes the project and resource set, and returns a short-lived credential for the required operation.
| Browser operation | Package and credential |
|---|---|
| Live inventory | @rstreamlabs/tunnels Watch, or @rstreamlabs/react; a read-only watch token. |
| Published HTTP or WebTTY access | A connect token limited to the authorized tunnel and paths; @rstreamlabs/webtty or the React terminal when using WebTTY. |
| WebTTY encrypted content | The authorized token plus the trusted browser/device keys required by the server's encryption policy. |
A watch token cannot create or connect to a tunnel. A connect token does not authorize inventory watching. CORS, token authorization and WebTTY encryption are separate controls; listing a server does not grant terminal control or recording access.
Issue watch credentials on the backend
Install @rstreamlabs/tunnels in the backend and browser application. The example below adapts the private LLM mesh watch route to one application-wide inventory. It assumes the application's existing getServerUser() helper admits only users allowed to observe this entire project subset. A multi-tenant application must derive the project and label boundary from its authorized user or tenant before minting; it must not trust resource filters supplied by the browser.
Use this recipe on an Engine that supports client-list scopes. Keep clients.list: false to exclude client inventory.
Save the following as app/api/rstream/watch/route.ts in that Next.js application. The @/lib/auth import is the application's session integration, not an rstream SDK export. The endpoint must enforce its session and authorization policy on every call.
import "server-only";
import { RstreamTunnelsClient } from "@rstreamlabs/tunnels";
import { getServerUser } from "@/lib/auth";
export const runtime = "nodejs";
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
}
const client = new RstreamTunnelsClient({
credentials: {
clientId: required("RSTREAM_CLIENT_ID"),
clientSecret: required("RSTREAM_CLIENT_SECRET"),
},
projectEndpoint: required("RSTREAM_PROJECT_ENDPOINT"),
});
export async function GET(): Promise<Response> {
if (!(await getServerUser())) {
return Response.json({ error: "unauthorized" }, { status: 401 });
}
const { token } = await client.auth.createAuthToken({
expires_in: 60,
permissions: ["tunnels.resources.read-only"],
resources: {
tunnels: {
scopes: {
clients: { list: false },
tunnels: {
list: {
filters: { labels: { app: "dashboard" } },
select: { id: true, name: true, status: true, labels: true },
},
},
},
},
},
});
return Response.json(
{ token, engine: await client.getEngine() },
{ headers: { "Cache-Control": "no-store" } },
);
}The backend credential needs account.projects.read-only to resolve the project and tunnels.resources.read-only to issue the watch token. Restrict the credential to the intended project. projectEndpoint makes the SDK's scope-only issuance project-scoped. Stored credential permissions, token claims and project policy intersect; the token cannot exceed its issuer. Keep the reusable backend client with the application lifecycle and close it when the backend shuts down. Neither its configuration nor its environment values belong in a browser bundle or a NEXT_PUBLIC_ variable.
Connect from the browser
Run this module from a Next.js client component after application sign-in. Install zod alongside @rstreamlabs/tunnels to validate the bootstrap response. Other bundlers may need to resolve Node compatibility imports from the shared SDK package.
import { Watch } from "@rstreamlabs/tunnels";
import { z } from "zod";
const credentialsSchema = z.object({ token: z.string(), engine: z.string() });
async function watchCredentials() {
const response = await fetch("/api/rstream/watch", {
credentials: "same-origin",
cache: "no-store",
});
if (!response.ok) throw new Error("Watch access was refused");
return credentialsSchema.parse(await response.json());
}
const initial = await watchCredentials();
const watch = new Watch(
{ engine: initial.engine, transport: "sse", auth: initial.token },
{ onEvent: (event) => console.log(event.type, event.object) },
);
await watch.connect();Start the local service from Quickstart. In the project configured for the backend, publish its port with the label used by the watch filter. Use a port and publication policy that match your test service.
rstream forward 8080 --http --label app=dashboardOpen the application while that tunnel is online. The console receives state.initial and authorized lifecycle events. Only the selected fields and matching tunnels are visible; client inventory is denied. The standalone Watch owns one subscription and does not reconnect itself. An application supervisor creates a new Watch after onClose, with bounded backoff and fresh credentials, or uses the React helpers below which manage that retry. Each new connection calls the backend again instead of reusing an expired cached token. Rebuild state from the next initial snapshot after reconnect. Call watch.disconnect() when leaving the page; React providers and hooks manage their subscription lifecycle.
For React, use the stable token callback with useRstream or RstreamProvider. Check that each refreshed token belongs to the subscription's Engine. A change of tenant or project requires replacing the subscription rather than supplying a token for another engine to an existing one.
Connect to a published service
A terminal or HTTP viewer needs a different backend-issued token with tunnels.streams.create-delete and a resources.tunnels.scopes.tunnels.connect restriction for its target. Limit the tunnel and request paths to the application operation. Never reuse the read-only watch token for a connection, or a producer token for a browser watch.
Use Authorization: Bearer when the protocol client supports headers. Selected browser protocols accept rstream.token on their documented endpoint only. Keep durable PATs, client secrets and account sessions out of URLs. See HTTP tunnel authentication, Signaling and Fine-grained tokens for the corresponding enforcement rules.
For WebTTY, follow the browser SDK guide. Server resolution determines workspace-managed or explicit-key end-to-end encryption requirements. Token access alone does not supply trusted local key material.