feat(dashboard): bearer-token auth with browser persistence + MIT license
Pre-release polish. Two related changes bundled because they both land the project on public-release footing: Dashboard auth - fn dashboard now gates the HTTP API + terminal/badge WebSockets behind a bearer token by default. Token resolution order: --token flag, FUSION_DASHBOARD_TOKEN env, FUSION_DAEMON_TOKEN env (back-compat), or an auto-generated fn_<32 hex>. --no-auth disables. The startup banner prints a click-to-open URL with ?token=<token> embedded. - Auth middleware now also accepts fn_token=<token> as a query-string fallback so EventSource and WebSocket clients (which can't set custom headers) still authenticate. - setupTerminalWebSocket / setupBadgeWebSocket now refuse unauthenticated upgrades with a proper 401 + socket close. - Frontend: new auth.ts module captures ?token= off the URL into localStorage (key fn.authToken), strips it from the visible URL via replaceState, and installs a window.fetch wrapper that injects Authorization: Bearer <token> on every same-origin /api/* request. EventSource/WebSocket URL builders (api.ts, sse-bus.ts, useTerminal, useBadgeWebSocket) route through appendTokenQuery(). MIT license - LICENSE file at repo root. - license: "MIT" on root package.json and every packages/*/package.json, plus description/bugs metadata on the CLI package. Docs - docs/cli-reference.md documents --token / --no-auth / FUSION_DASHBOARD_TOKEN and the click-to-open auth flow. - docs/getting-started.md, docs/docker.md, README.md point at the new flow and the CLI reference section. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,14 @@
|
||||
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
/**
|
||||
* Query-string fallback used when the client can't set an Authorization
|
||||
* header (EventSource, WebSocket handshake). The token flows as
|
||||
* `?fn_token=<token>` on those URLs.
|
||||
*/
|
||||
export const TOKEN_QUERY_PARAM = "fn_token";
|
||||
|
||||
/** Paths that are exempt from authentication (liveness probes). */
|
||||
const EXEMPT_PATHS = ["/api/health"];
|
||||
@@ -30,7 +38,7 @@ export function isDaemonAuthActive(options?: { daemon?: { token: string } }): bo
|
||||
/**
|
||||
* Get the daemon token from options or environment.
|
||||
*/
|
||||
function getDaemonToken(options?: { daemon?: { token: string } }): string | undefined {
|
||||
export function getDaemonToken(options?: { daemon?: { token: string } }): string | undefined {
|
||||
if (options?.daemon?.token) {
|
||||
return options.daemon.token;
|
||||
}
|
||||
@@ -44,17 +52,85 @@ function isExemptPath(path: string): boolean {
|
||||
return EXEMPT_PATHS.some((exempt) => path === exempt || path.startsWith(exempt + "/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Constant-time string compare. Returns true only if both strings are the
|
||||
* same length and byte-for-byte equal.
|
||||
*/
|
||||
function constantTimeEqual(provided: string, expected: Buffer): boolean {
|
||||
if (provided.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const providedBuffer = Buffer.from(provided, "utf8");
|
||||
if (providedBuffer.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
return timingSafeEqual(providedBuffer, expected);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a bearer token from either the `Authorization: Bearer <token>`
|
||||
* header or the `fn_token=<token>` query-string fallback. The query-string
|
||||
* path is only needed for transports that can't set headers (EventSource,
|
||||
* WebSocket handshake).
|
||||
*/
|
||||
function extractTokenFromRequest(req: { headers: { authorization?: string }; url?: string }): string | undefined {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith("Bearer ")) {
|
||||
return authHeader.slice(7);
|
||||
}
|
||||
if (req.url) {
|
||||
try {
|
||||
const parsed = new URL(req.url, "http://_placeholder_");
|
||||
const fromQuery = parsed.searchParams.get(TOKEN_QUERY_PARAM);
|
||||
if (fromQuery) return fromQuery;
|
||||
} catch {
|
||||
// Fall through — malformed URL, treat as no token.
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a raw HTTP upgrade request (WebSocket handshake) against the
|
||||
* configured daemon token. Returns true when the request carries a valid
|
||||
* bearer token, false otherwise. Accepts the token either via the
|
||||
* `Authorization` header or the `fn_token` query string — browsers cannot
|
||||
* set custom headers on a WebSocket constructor, so the query-string
|
||||
* fallback is required for same-origin browser clients.
|
||||
*
|
||||
* Uses constant-time comparison to resist timing attacks.
|
||||
*/
|
||||
export function authenticateUpgradeRequest(token: string, req: IncomingMessage): boolean {
|
||||
const expectedBuffer = Buffer.from(token, "utf8");
|
||||
const provided = extractTokenFromRequest(req as { headers: { authorization?: string }; url?: string });
|
||||
if (!provided) return false;
|
||||
return constantTimeEqual(provided, expectedBuffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Express middleware that enforces bearer token authentication.
|
||||
*
|
||||
* Uses constant-time comparison to prevent timing attacks.
|
||||
* Exempts /api/health and paths starting with /api/health/ from auth.
|
||||
* Accepts the token either in the `Authorization: Bearer <token>` header
|
||||
* (preferred) or as a `fn_token=<token>` query parameter — the latter is
|
||||
* needed by EventSource and WebSocket clients which can't send headers.
|
||||
*
|
||||
* @param token - The valid bearer token
|
||||
* @returns Express middleware function
|
||||
*/
|
||||
export function createAuthMiddleware(token: string) {
|
||||
const expectedBuffer = Buffer.from(token, "utf8");
|
||||
const unauthorized = (res: Response): void => {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
};
|
||||
|
||||
return function authMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
// Always allow exempt paths
|
||||
@@ -63,67 +139,17 @@ export function createAuthMiddleware(token: string) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract Authorization header
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
const providedToken = extractTokenFromRequest(req);
|
||||
if (!providedToken) {
|
||||
unauthorized(res);
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse Bearer scheme
|
||||
if (!authHeader.startsWith("Bearer ")) {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
if (!constantTimeEqual(providedToken, expectedBuffer)) {
|
||||
unauthorized(res);
|
||||
return;
|
||||
}
|
||||
|
||||
const providedToken = authHeader.slice(7); // Remove "Bearer " prefix
|
||||
|
||||
// Fast path: check length first to avoid unnecessary crypto calls
|
||||
if (providedToken.length !== expectedBuffer.length) {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Constant-time comparison to prevent timing attacks
|
||||
try {
|
||||
const providedBuffer = Buffer.from(providedToken, "utf8");
|
||||
|
||||
// Ensure buffers are the same length (they should be due to length check above)
|
||||
if (providedBuffer.length !== expectedBuffer.length) {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!timingSafeEqual(providedBuffer, expectedBuffer)) {
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Buffer encoding issues or other crypto errors
|
||||
res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "Valid bearer token required",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Token is valid
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
import { ChatManager } from "./chat.js";
|
||||
import { stopAllDevServers } from "./dev-server-routes.js";
|
||||
import type { SkillsAdapter } from "./skills-adapter.js";
|
||||
import { createAuthMiddleware } from "./auth-middleware.js";
|
||||
import { createAuthMiddleware, authenticateUpgradeRequest, getDaemonToken } from "./auth-middleware.js";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -866,12 +866,25 @@ export function setupTerminalWebSocket(
|
||||
// Default terminal service for stale eviction (uses default store's root dir)
|
||||
const defaultTerminalService = getTerminalService(store.getRootDir());
|
||||
|
||||
// Resolve the daemon token once so every upgrade picks up the same value.
|
||||
const wsDaemonToken = getDaemonToken(options);
|
||||
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const pathname = new URL(req.url || "", `http://${req.headers.host}`).pathname;
|
||||
if (pathname !== "/api/terminal/ws") {
|
||||
return;
|
||||
}
|
||||
|
||||
// When daemon auth is active, refuse WebSocket upgrades that don't
|
||||
// carry a valid bearer token. The token can come from the Authorization
|
||||
// header (rare for browser WebSocket clients) or the `fn_token` query
|
||||
// param (what our own client uses).
|
||||
if (wsDaemonToken && !authenticateUpgradeRequest(wsDaemonToken, req)) {
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (upgraded) => {
|
||||
wss.emit("connection", upgraded, req);
|
||||
});
|
||||
@@ -1130,12 +1143,22 @@ export function setupBadgeWebSocket(
|
||||
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
// Resolve the daemon token once per server so every upgrade picks up the
|
||||
// same value. See the equivalent block in setupTerminalWebSocket above.
|
||||
const badgeWsDaemonToken = getDaemonToken(options);
|
||||
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const pathname = new URL(req.url || "", `http://${req.headers.host}`).pathname;
|
||||
if (pathname !== "/api/ws") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (badgeWsDaemonToken && !authenticateUpgradeRequest(badgeWsDaemonToken, req)) {
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (upgraded) => {
|
||||
wss.emit("connection", upgraded, req);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user