feat(FN-2406): persist dashboard auth token and harden TUI layout
- Persist dashboard auth token in global settings and add daemon-token utilities for reuse - Update dashboard CLI command auth precedence and token handling behavior - Harden dashboard TUI log viewport budgeting to avoid footer overlap under constrained heights - Expand CLI and TUI test coverage for token persistence, auth precedence, and environment mocking - Refresh README/CLI/getting-started docs and add changesets for token persistence and TUI fix
This commit is contained in:
@@ -2,9 +2,25 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
// Use vi.hoisted to define mocks that need to be referenced in vi.mock
|
||||
const { centralInstances } = vi.hoisted(() => {
|
||||
const {
|
||||
centralInstances,
|
||||
mockResolveGlobalDir,
|
||||
mockGlobalSettingsGetSettings,
|
||||
mockGlobalSettingsUpdateSettings,
|
||||
mockDaemonTokenGetOrCreate,
|
||||
} = vi.hoisted(() => {
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
delete process.env.FUSION_DAEMON_TOKEN;
|
||||
delete process.env.FUSION_BEARER_TOKEN;
|
||||
|
||||
const centralInstances: any[] = [];
|
||||
return { centralInstances };
|
||||
return {
|
||||
centralInstances,
|
||||
mockResolveGlobalDir: vi.fn().mockReturnValue("/tmp/test-global"),
|
||||
mockGlobalSettingsGetSettings: vi.fn().mockResolvedValue({}),
|
||||
mockGlobalSettingsUpdateSettings: vi.fn().mockResolvedValue({}),
|
||||
mockDaemonTokenGetOrCreate: vi.fn().mockResolvedValue("fn_test_dashboard_token"),
|
||||
};
|
||||
});
|
||||
|
||||
// ── Multi-project test fixtures ─────────────────────────────────────────
|
||||
@@ -151,6 +167,16 @@ vi.mock("@fusion/core", () => ({
|
||||
getLoadedPlugins: vi.fn().mockReturnValue([]),
|
||||
})),
|
||||
getEnabledPiExtensionPaths: vi.fn(() => []),
|
||||
resolveGlobalDir: mockResolveGlobalDir,
|
||||
GlobalSettingsStore: vi.fn().mockImplementation(() => ({
|
||||
getSettings: mockGlobalSettingsGetSettings,
|
||||
updateSettings: mockGlobalSettingsUpdateSettings,
|
||||
})),
|
||||
DaemonTokenManager: vi.fn().mockImplementation(() => ({
|
||||
getOrCreateToken: mockDaemonTokenGetOrCreate,
|
||||
getToken: vi.fn().mockResolvedValue(undefined),
|
||||
generateToken: vi.fn().mockResolvedValue("fn_test_dashboard_token"),
|
||||
})),
|
||||
getTaskMergeBlocker: vi.fn().mockReturnValue(undefined),
|
||||
syncInsightExtractionAutomation: mockSyncInsightExtraction,
|
||||
INSIGHT_EXTRACTION_SCHEDULE_NAME: "Memory Insight Extraction",
|
||||
@@ -411,11 +437,114 @@ function setupProjectByPath(
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
delete process.env.FUSION_DAEMON_TOKEN;
|
||||
delete process.env.FUSION_BEARER_TOKEN;
|
||||
mockResolveGlobalDir.mockReset();
|
||||
mockResolveGlobalDir.mockReturnValue("/tmp/test-global");
|
||||
mockGlobalSettingsGetSettings.mockReset();
|
||||
mockGlobalSettingsGetSettings.mockResolvedValue({});
|
||||
mockGlobalSettingsUpdateSettings.mockReset();
|
||||
mockGlobalSettingsUpdateSettings.mockResolvedValue({});
|
||||
mockDaemonTokenGetOrCreate.mockReset();
|
||||
mockDaemonTokenGetOrCreate.mockResolvedValue("fn_test_dashboard_token");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
disposeTrackedDashboards();
|
||||
resetMultiProjectState();
|
||||
});
|
||||
|
||||
describe("runDashboard — dashboard auth token persistence + precedence", () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockDiscoverAndLoadExtensions.mockResolvedValue({
|
||||
runtime: { pendingProviderRegistrations: [] },
|
||||
errors: [],
|
||||
});
|
||||
const { TaskStore, DaemonTokenManager } = await import("@fusion/core");
|
||||
(TaskStore as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => makeMockStore());
|
||||
(DaemonTokenManager as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
|
||||
getOrCreateToken: mockDaemonTokenGetOrCreate,
|
||||
getToken: vi.fn().mockResolvedValue(undefined),
|
||||
generateToken: vi.fn().mockResolvedValue("fn_test_dashboard_token"),
|
||||
}));
|
||||
});
|
||||
|
||||
it("generates exactly once on first authenticated run and reuses token on subsequent runs", async () => {
|
||||
const { DaemonTokenManager } = await import("@fusion/core");
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
|
||||
let storedToken: string | undefined;
|
||||
let generationCount = 0;
|
||||
|
||||
(DaemonTokenManager as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
|
||||
getOrCreateToken: vi.fn().mockImplementation(async () => {
|
||||
if (!storedToken) {
|
||||
generationCount += 1;
|
||||
storedToken = "fn_persisted_dashboard_token";
|
||||
}
|
||||
return storedToken;
|
||||
}),
|
||||
}));
|
||||
|
||||
await runDashboard(0, { open: false, dev: true });
|
||||
const firstOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
|
||||
await runDashboard(0, { open: false, dev: true });
|
||||
const secondOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
|
||||
expect(generationCount).toBe(1);
|
||||
expect(firstOpts.daemon).toEqual({ token: "fn_persisted_dashboard_token" });
|
||||
expect(secondOpts.daemon).toEqual({ token: "fn_persisted_dashboard_token" });
|
||||
});
|
||||
|
||||
it("uses --token over env vars and persisted token", async () => {
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
process.env.FUSION_DASHBOARD_TOKEN = "fn_env_dashboard_token";
|
||||
process.env.FUSION_DAEMON_TOKEN = "fn_env_daemon_token";
|
||||
|
||||
await runDashboard(0, { open: false, dev: true, token: "fn_cli_token" });
|
||||
|
||||
const serverOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
expect(serverOpts.daemon).toEqual({ token: "fn_cli_token" });
|
||||
});
|
||||
|
||||
it("uses FUSION_DASHBOARD_TOKEN before FUSION_DAEMON_TOKEN", async () => {
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
process.env.FUSION_DASHBOARD_TOKEN = "fn_env_dashboard_token";
|
||||
process.env.FUSION_DAEMON_TOKEN = "fn_env_daemon_token";
|
||||
|
||||
await runDashboard(0, { open: false, dev: true });
|
||||
|
||||
const serverOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
expect(serverOpts.daemon).toEqual({ token: "fn_env_dashboard_token" });
|
||||
});
|
||||
|
||||
it("uses FUSION_DAEMON_TOKEN when dashboard token env var is absent", async () => {
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
process.env.FUSION_DAEMON_TOKEN = "fn_env_daemon_token";
|
||||
|
||||
await runDashboard(0, { open: false, dev: true });
|
||||
|
||||
const serverOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
expect(serverOpts.daemon).toEqual({ token: "fn_env_daemon_token" });
|
||||
});
|
||||
|
||||
it("disables auth entirely with --no-auth and bypasses persisted token lookup", async () => {
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
const { DaemonTokenManager } = await import("@fusion/core");
|
||||
|
||||
await runDashboard(0, { open: false, dev: true, noAuth: true });
|
||||
|
||||
const serverOpts = (createServer as ReturnType<typeof vi.fn>).mock.calls.at(-1)![1];
|
||||
expect(serverOpts.daemon).toBeUndefined();
|
||||
expect(serverOpts.noAuth).toBe(true);
|
||||
expect(DaemonTokenManager).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("runDashboard — AuthStorage & ModelRegistry wiring", () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
@@ -15,22 +15,36 @@ const {
|
||||
mockSelfHealingStop,
|
||||
mockCheckStuckBudget,
|
||||
mockStuckCheckNow,
|
||||
} = vi.hoisted(() => ({
|
||||
mockAuthStorage: { getAuth: vi.fn(), setAuth: vi.fn(), getApiKey: vi.fn().mockResolvedValue(undefined) },
|
||||
mockModelRegistry: {
|
||||
registerProvider: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
},
|
||||
mockDiscoverAndLoadExtensions: vi.fn().mockResolvedValue({
|
||||
runtime: { pendingProviderRegistrations: [] },
|
||||
errors: [],
|
||||
}),
|
||||
mockCreateExtensionRuntime: vi.fn(),
|
||||
mockSelfHealingStart: vi.fn(),
|
||||
mockSelfHealingStop: vi.fn(),
|
||||
mockCheckStuckBudget: vi.fn().mockResolvedValue(true),
|
||||
mockStuckCheckNow: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
mockResolveGlobalDir,
|
||||
mockGlobalSettingsGetSettings,
|
||||
mockGlobalSettingsUpdateSettings,
|
||||
mockDaemonTokenGetOrCreate,
|
||||
} = vi.hoisted(() => {
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
delete process.env.FUSION_DAEMON_TOKEN;
|
||||
delete process.env.FUSION_BEARER_TOKEN;
|
||||
|
||||
return {
|
||||
mockAuthStorage: { getAuth: vi.fn(), setAuth: vi.fn(), getApiKey: vi.fn().mockResolvedValue(undefined) },
|
||||
mockModelRegistry: {
|
||||
registerProvider: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
},
|
||||
mockDiscoverAndLoadExtensions: vi.fn().mockResolvedValue({
|
||||
runtime: { pendingProviderRegistrations: [] },
|
||||
errors: [],
|
||||
}),
|
||||
mockCreateExtensionRuntime: vi.fn(),
|
||||
mockSelfHealingStart: vi.fn(),
|
||||
mockSelfHealingStop: vi.fn(),
|
||||
mockCheckStuckBudget: vi.fn().mockResolvedValue(true),
|
||||
mockStuckCheckNow: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveGlobalDir: vi.fn().mockReturnValue("/tmp/test-global"),
|
||||
mockGlobalSettingsGetSettings: vi.fn().mockResolvedValue({}),
|
||||
mockGlobalSettingsUpdateSettings: vi.fn().mockResolvedValue({}),
|
||||
mockDaemonTokenGetOrCreate: vi.fn().mockResolvedValue("fn_test_dashboard_token"),
|
||||
};
|
||||
});
|
||||
|
||||
// Minimal mock store backed by EventEmitter so `store.on` works
|
||||
function makeMockStore() {
|
||||
@@ -157,6 +171,16 @@ vi.mock("@fusion/core", () => ({
|
||||
};
|
||||
}),
|
||||
getEnabledPiExtensionPaths: vi.fn(() => []),
|
||||
resolveGlobalDir: mockResolveGlobalDir,
|
||||
GlobalSettingsStore: vi.fn().mockImplementation(() => ({
|
||||
getSettings: mockGlobalSettingsGetSettings,
|
||||
updateSettings: mockGlobalSettingsUpdateSettings,
|
||||
})),
|
||||
DaemonTokenManager: vi.fn().mockImplementation(() => ({
|
||||
getOrCreateToken: mockDaemonTokenGetOrCreate,
|
||||
getToken: vi.fn().mockResolvedValue(undefined),
|
||||
generateToken: vi.fn().mockResolvedValue("fn_test_dashboard_token"),
|
||||
})),
|
||||
getTaskMergeBlocker: vi.fn((task: any) => {
|
||||
if (task.column !== "in-review") return `task is in '${task.column}', must be in 'in-review'`;
|
||||
if (task.paused) return "task is paused";
|
||||
@@ -732,12 +756,24 @@ function resetGitHubMocks() {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
delete process.env.FUSION_DAEMON_TOKEN;
|
||||
delete process.env.FUSION_BEARER_TOKEN;
|
||||
|
||||
resetGitHubMocks();
|
||||
mockExecSync.mockReset();
|
||||
mockExecSync.mockReturnValue("");
|
||||
mockExec.mockClear();
|
||||
mockStuckCheckNow.mockReset();
|
||||
mockStuckCheckNow.mockResolvedValue(undefined);
|
||||
mockResolveGlobalDir.mockReset();
|
||||
mockResolveGlobalDir.mockReturnValue("/tmp/test-global");
|
||||
mockGlobalSettingsGetSettings.mockReset();
|
||||
mockGlobalSettingsGetSettings.mockResolvedValue({});
|
||||
mockGlobalSettingsUpdateSettings.mockReset();
|
||||
mockGlobalSettingsUpdateSettings.mockResolvedValue({});
|
||||
mockDaemonTokenGetOrCreate.mockReset();
|
||||
mockDaemonTokenGetOrCreate.mockResolvedValue("fn_test_dashboard_token");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -2646,6 +2682,7 @@ describe("StreamedLogBuffer", () => {
|
||||
|
||||
describe("runDashboard — merge stream sink routing", () => {
|
||||
it("routes streamed merge deltas through log sink without raw stdout writes", async () => {
|
||||
process.env.FUSION_DASHBOARD_TOKEN = "fn_test_dashboard_token";
|
||||
const { TaskStore, AutomationStore, AgentStore, PluginStore, PluginLoader, CentralCore } = await import("@fusion/core");
|
||||
const { aiMergeTask } = await import("@fusion/engine");
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
@@ -2726,11 +2763,13 @@ describe("runDashboard — merge stream sink routing", () => {
|
||||
|
||||
stdoutWriteSpy.mockRestore();
|
||||
consoleLogSpy.mockRestore();
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
});
|
||||
});
|
||||
|
||||
describe("runDashboard runtime logger wiring", () => {
|
||||
it("injects a runtime logger into createServer and preserves non-TTY console fallback", async () => {
|
||||
process.env.FUSION_DASHBOARD_TOKEN = "fn_test_dashboard_token";
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
@@ -2747,9 +2786,11 @@ describe("runDashboard runtime logger wiring", () => {
|
||||
);
|
||||
|
||||
consoleLogSpy.mockRestore();
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
});
|
||||
|
||||
it("routes runtime logger output through DashboardLogSink in TTY mode", async () => {
|
||||
process.env.FUSION_DASHBOARD_TOKEN = "fn_test_dashboard_token";
|
||||
const { createServer } = await import("@fusion/dashboard");
|
||||
const { DashboardLogSink, DashboardTUI } = await import("./dashboard-tui.js");
|
||||
|
||||
@@ -2783,6 +2824,7 @@ describe("runDashboard runtime logger wiring", () => {
|
||||
tuiStopSpy.mockRestore();
|
||||
tuiLogSpy.mockRestore();
|
||||
captureConsoleSpy.mockRestore();
|
||||
delete process.env.FUSION_DASHBOARD_TOKEN;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { TaskStore, AutomationStore, CentralCore, AgentStore, PluginStore, PluginLoader, getTaskMergeBlocker, getEnabledPiExtensionPaths, isEphemeralAgent } from "@fusion/core";
|
||||
import {
|
||||
TaskStore,
|
||||
AutomationStore,
|
||||
CentralCore,
|
||||
AgentStore,
|
||||
PluginStore,
|
||||
PluginLoader,
|
||||
getTaskMergeBlocker,
|
||||
getEnabledPiExtensionPaths,
|
||||
isEphemeralAgent,
|
||||
DaemonTokenManager,
|
||||
GlobalSettingsStore,
|
||||
resolveGlobalDir,
|
||||
} from "@fusion/core";
|
||||
import {
|
||||
createServer,
|
||||
GitHubClient,
|
||||
@@ -307,6 +319,34 @@ async function resolveRuntimeProjectPath(): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveDashboardAuthToken(opts: { noAuth?: boolean; token?: string }): Promise<string | undefined> {
|
||||
if (opts.noAuth) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const explicitToken = opts.token
|
||||
?? process.env.FUSION_DASHBOARD_TOKEN
|
||||
?? process.env.FUSION_DAEMON_TOKEN;
|
||||
|
||||
if (explicitToken) {
|
||||
return explicitToken;
|
||||
}
|
||||
|
||||
const globalDir = resolveGlobalDir();
|
||||
const settingsStore = new GlobalSettingsStore(globalDir);
|
||||
const tokenManager = new DaemonTokenManager(settingsStore);
|
||||
|
||||
if (typeof tokenManager.getOrCreateToken === "function") {
|
||||
return tokenManager.getOrCreateToken();
|
||||
}
|
||||
|
||||
const existingToken = await tokenManager.getToken();
|
||||
if (existingToken) {
|
||||
return existingToken;
|
||||
}
|
||||
return tokenManager.generateToken();
|
||||
}
|
||||
|
||||
export async function runDashboard(port: number, opts: { paused?: boolean; dev?: boolean; interactive?: boolean; open?: boolean; host?: string; noAuth?: boolean; token?: string } = {}) {
|
||||
// Default to localhost so the dashboard (and its shell-capable terminal API)
|
||||
// is not exposed on the LAN. Pass --host 0.0.0.0 explicitly to opt-in.
|
||||
@@ -318,19 +358,15 @@ export async function runDashboard(port: number, opts: { paused?: boolean; dev?:
|
||||
// server is bound to a non-localhost interface (e.g. `pnpm dev dashboard`
|
||||
// which injects --host 0.0.0.0 for LAN testing) nearby users can't hit the
|
||||
// terminal or exec endpoints uninvited. Precedence:
|
||||
// 1. `opts.token` — explicit override (mostly for tests)
|
||||
// 1. `opts.token` — explicit override (mostly for tests)
|
||||
// 2. `FUSION_DASHBOARD_TOKEN` — user-provided env
|
||||
// 3. `FUSION_DAEMON_TOKEN` — back-compat with daemon mode
|
||||
// 4. auto-generated random token (printed at startup so the user can auth)
|
||||
// 4. stored token in ~/.fusion/settings.json
|
||||
// 5. newly generated persisted token (first authenticated run only)
|
||||
// `--no-auth` skips the middleware entirely. The token is embedded in the
|
||||
// launch URL (as `?token=...`) so the user can click once and the browser
|
||||
// stores it to localStorage for subsequent loads.
|
||||
const dashboardAuthToken: string | undefined = opts.noAuth
|
||||
? undefined
|
||||
: opts.token
|
||||
?? process.env.FUSION_DASHBOARD_TOKEN
|
||||
?? process.env.FUSION_DAEMON_TOKEN
|
||||
?? `fn_${randomBytes(16).toString("hex")}`;
|
||||
const dashboardAuthToken = await resolveDashboardAuthToken(opts);
|
||||
|
||||
// Single sink/logger pair for all dashboard command diagnostics.
|
||||
// In TTY mode this routes to DashboardTUI; in non-TTY mode it falls back to console.*.
|
||||
|
||||
Reference in New Issue
Block a user