repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Add ui token auth server

ecdab218137317bd18be0fd0e9a7b76c822660bd

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/ui/__tests__/server.test.ts

Modified
1 1 import { describe, expect, it } from "vitest";
2 2 import { humanError, redactToken, uiError } from "../errors";
3 3 import { chooseLanAddress, uiUrl } from "../network";
4 +import { startUiServer } from "../server";
5 6 describe("ui network helpers", () => {
6 7 it("prefers non-internal IPv4 LAN addresses", () => {
42 43 expect(humanError(err)).toContain("Retryable: yes");
47 +describe("ui server", () => {
48 + it("serves shell only with query token and sets strict cookie", async () => {
49 + const server = await startUiServer({
50 + address: "127.0.0.1",
51 + token: "tok",
52 + preferredPort: 0,
53 + });
54 + try {
55 + const unauthorized = await fetch(server.baseUrl);
56 + expect(unauthorized.status).toBe(401);
57 + expect(await unauthorized.text()).toContain("Unauthorized");
59 + const authorized = await fetch(`${server.baseUrl}/?token=tok`);
60 + expect(authorized.status).toBe(200);
61 + expect(authorized.headers.get("set-cookie")).toContain("pi_ui_token=tok");
62 + expect(authorized.headers.get("set-cookie")).toContain(
63 + "SameSite=Strict",
64 + );
65 + expect(await authorized.text()).toContain("Pi UI shell");
66 + } finally {
67 + await server.close("test");
68 + }
69 + });
71 + it("accepts cookie and bearer auth for status", async () => {
72 + const server = await startUiServer({
73 + address: "127.0.0.1",
74 + token: "tok",
75 + preferredPort: 0,
76 + });
77 + try {
78 + const cookie = await fetch(`${server.baseUrl}/api/status`, {
79 + headers: { cookie: "pi_ui_token=tok" },
80 + });
81 + expect(cookie.status).toBe(200);
82 + expect(await cookie.json()).toMatchObject({
83 + state: "waiting",
84 + clients: 0,
85 + });
87 + const bearer = await fetch(`${server.baseUrl}/api/status`, {
88 + headers: { authorization: "Bearer tok" },
89 + });
90 + expect(bearer.status).toBe(200);
91 + } finally {
92 + await server.close("test");
93 + }
94 + });
96 + it("rejects wrong tokens", async () => {
97 + const server = await startUiServer({
98 + address: "127.0.0.1",
99 + token: "tok",
100 + preferredPort: 0,
101 + });
102 + try {
103 + const response = await fetch(`${server.baseUrl}/api/status`, {
104 + headers: { authorization: "Bearer wrong" },
105 + });
106 + expect(response.status).toBe(401);
107 + } finally {
108 + await server.close("test");
110 + });
111 +});

extensions/ui/server.ts

Added
new file mode 100644
1 +import { randomBytes } from "node:crypto";
2 +import {
3 + createServer,
4 + type IncomingMessage,
5 + type Server,
6 + type ServerResponse,
7 +} from "node:http";
8 +import { listenHostFor, uiUrl } from "./network";
10 +export type UiServerState = "waiting" | "connected" | "inactive" | "stopped";
12 +export type UiServer = {
13 + baseUrl: string;
14 + publicUrl: string;
15 + port: number;
16 + token: string;
17 + state(): UiServerState;
18 + clients(): number;
19 + close(reason: string): Promise<void>;
20 +};
22 +export type StartUiServerOptions = {
23 + address: string;
24 + token?: string;
25 + preferredPort?: number;
26 + onClientState?: (state: UiServerState) => void;
27 +};
29 +const COOKIE = "pi_ui_token";
30 +const MAX_BODY_BYTES = 1_000_000;
32 +export async function startUiServer(
33 + options: StartUiServerOptions,
34 +): Promise<UiServer> {
35 + const token = options.token ?? randomBytes(32).toString("base64url");
36 + const host = listenHostFor(options.address);
37 + let currentState: UiServerState = "waiting";
38 + let clientCount = 0;
39 + let closed = false;
40 + const server = createServer((req, res) => {
41 + void dispatch(req, res, {
42 + token,
43 + state: () => currentState,
44 + clients: () => clientCount,
45 + setState(next) {
46 + currentState = next;
47 + options.onClientState?.(next);
48 + },
49 + clientSeen() {
50 + clientCount += 1;
51 + },
52 + });
53 + });
55 + await listen(server, host, options.preferredPort ?? 0);
56 + const address = server.address();
57 + if (!address || typeof address === "string") throw new Error("Failed to bind UI server");
58 + const baseUrl = `http://127.0.0.1:${address.port}`;
59 + const publicUrl = uiUrl(options.address, address.port, token);
61 + return {
62 + baseUrl,
63 + publicUrl,
64 + port: address.port,
65 + token,
66 + state: () => currentState,
67 + clients: () => clientCount,
68 + async close(reason) {
69 + void reason;
70 + if (closed) return;
71 + closed = true;
72 + currentState = "stopped";
73 + options.onClientState?.("stopped");
74 + await closeServer(server);
75 + },
76 + };
79 +type RouteContext = {
80 + token: string;
81 + state(): UiServerState;
82 + clients(): number;
83 + setState(state: UiServerState): void;
84 + clientSeen(): void;
85 +};
87 +async function dispatch(
88 + req: IncomingMessage,
89 + res: ServerResponse,
90 + ctx: RouteContext,
91 +): Promise<void> {
92 + try {
93 + const url = new URL(req.url ?? "/", "http://127.0.0.1");
94 + setSecurityHeaders(res);
95 + if (hasOversizedBody(req)) return json(res, 413, { error: "body too large" });
96 + if (req.method === "GET" && url.pathname === "/") {
97 + return serveIndex(req, url, res, ctx);
98 + }
99 + if (!authorized(req, ctx.token)) return serveUnauthorized(res);
100 + if (req.method === "GET" && url.pathname === "/api/status") {
101 + return json(res, 200, { state: ctx.state(), clients: ctx.clients() });
103 + return json(res, 404, { error: "not found" });
104 + } catch (error) {
105 + return json(res, 500, {
106 + error: error instanceof Error ? error.message : String(error),
107 + });
111 +function serveIndex(
112 + req: IncomingMessage,
113 + url: URL,
114 + res: ServerResponse,
115 + ctx: RouteContext,
116 +): void {
117 + if (url.searchParams.get("token") !== ctx.token && !cookieAuthorized(req, ctx.token)) {
118 + return serveUnauthorized(res);
120 + ctx.clientSeen();
121 + ctx.setState("connected");
122 + res.setHeader("Set-Cookie", `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`);
123 + res.setHeader("Content-Type", "text/html; charset=utf-8");
124 + res.end(renderShellPage());
127 +function renderShellPage(): string {
128 + return `<!doctype html>
129 +<html lang="en">
130 +<head>
131 +<meta charset="utf-8">
132 +<meta name="viewport" content="width=device-width, initial-scale=1">
133 +<title>Pi UI shell</title>
134 +<style>
135 +:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
136 +body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: Canvas; color: CanvasText; }
137 +main { border: 4px solid CanvasText; padding: 24px; max-width: 720px; }
138 +h1 { margin: 0 0 12px; }
139 +code { border: 1px solid color-mix(in srgb, CanvasText 40%, transparent); padding: 2px 4px; }
140 +</style>
141 +</head>
142 +<body>
143 +<main>
144 +<h1>Pi UI shell</h1>
145 +<p>Phase 1 server is running. RPC stream arrives in a later phase.</p>
146 +<p>Return to terminal and run <code>/ui off</code> to stop.</p>
147 +</main>
148 +</body>
149 +</html>`;
152 +function serveUnauthorized(res: ServerResponse): void {
153 + res.statusCode = 401;
154 + res.setHeader("Content-Type", "text/html; charset=utf-8");
155 + res.end(
156 + "<!doctype html><title>Unauthorized</title><h1>Unauthorized</h1><p>Open the exact /ui link or scan the current QR code again.</p>",
157 + );
160 +function authorized(req: IncomingMessage, token: string): boolean {
161 + return req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token);
164 +function cookieAuthorized(req: IncomingMessage, token: string): boolean {
165 + return (req.headers.cookie ?? "")
166 + .split(/;\s*/)
167 + .some((cookie) => cookie === `${COOKIE}=${token}`);
170 +function hasOversizedBody(req: IncomingMessage): boolean {
171 + const length = req.headers["content-length"];
172 + return typeof length === "string" && Number(length) > MAX_BODY_BYTES;
175 +function setSecurityHeaders(res: ServerResponse): void {
176 + res.setHeader("X-Content-Type-Options", "nosniff");
177 + res.setHeader("Referrer-Policy", "no-referrer");
178 + res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
181 +function json(res: ServerResponse, status: number, body: unknown): void {
182 + res.statusCode = status;
183 + res.setHeader("Content-Type", "application/json; charset=utf-8");
184 + res.end(JSON.stringify(body));
187 +function listen(server: Server, host: string, port: number): Promise<void> {
188 + return new Promise((resolve, reject) => {
189 + const onError = (error: NodeJS.ErrnoException) => {
190 + server.off("error", onError);
191 + reject(error);
192 + };
193 + server.once("error", onError);
194 + server.listen(port, host, () => {
195 + server.off("error", onError);
196 + resolve();
197 + });
198 + });
201 +function closeServer(server: Server): Promise<void> {
202 + return new Promise((resolve, reject) => {
203 + server.close((error) => (error ? reject(error) : resolve()));
204 + });