Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(api): device tokens, API version and CORS for remote clients
Salman Qureshi75a3d7b40e39
diff --git a/src/cli/devices-cli.ts b/src/cli/devices-cli.tsnew file mode 100644index 00000000..44fc1fa8--- /dev/null+++ b/src/cli/devices-cli.ts@@ -0,0 +1,89 @@+import type { Command } from 'commander';+import chalk from 'chalk';+import { hostname, platform } from 'node:os';+import { createDevice, listDevices, revokeDevice } from '../web/devices.js';++/**+ * `mercury devices` — pair and manage remote clients (Mercury Desktop on+ * another machine, a phone, a script). Tokens are shown once.+ *+ * mercury devices add "Office laptop" → prints the token to paste+ * mercury devices list+ * mercury devices revoke <id>+ *+ * Runs against the device file directly; the runtime does not need to be+ * up, and a token takes effect on the next request.+ */+export function registerDevicesCli(program: Command): void {+ const devices = program+ .command('devices')+ .description('Pair remote clients (Mercury Desktop, phones, scripts) with device tokens');++ devices+ .command('add [name]')+ .description('Create a device token (shown once) for a remote client')+ .option('--platform <platform>', 'macos | windows | linux | android | ios | script', 'script')+ .option('--json', 'Print machine-readable output')+ .action((name: string | undefined, opts: { platform?: string; json?: boolean }) => {+ const created = createDevice(name ?? `${hostname()} (${platform()})`, opts.platform);+ if (opts.json) {+ console.log(JSON.stringify(created));+ return;+ }+ console.log('');+ console.log(chalk.green(` ✓ Device "${created.device.name}" added`) + chalk.dim(` · id ${created.device.id}`));+ console.log('');+ console.log(' Paste this token into Mercury Desktop → Add connection. It is shown once:');+ console.log('');+ console.log(` ${chalk.white(created.token)}`);+ console.log('');+ console.log(chalk.dim(' Revoke it any time with: mercury devices revoke ' + created.device.id));+ console.log('');+ });++ devices+ .command('list')+ .description('List paired devices')+ .option('--json', 'Print machine-readable output')+ .action((opts: { json?: boolean }) => {+ const list = listDevices();+ if (opts.json) {+ console.log(JSON.stringify(list));+ return;+ }+ console.log('');+ if (list.length === 0) {+ console.log(chalk.dim(' No devices paired. Add one with: mercury devices add "My laptop"'));+ console.log('');+ return;+ }+ for (const d of list) {+ const seen = d.lastSeenAt ? `last seen ${formatAgo(d.lastSeenAt)}` : 'never connected';+ console.log(` ${chalk.white(d.id)} ${d.name}` + chalk.dim(` · ${d.platform} · ${seen}`));+ }+ console.log('');+ });++ devices+ .command('revoke <id>')+ .description('Revoke a device token')+ .action((id: string) => {+ if (revokeDevice(id)) {+ console.log(chalk.green(` ✓ Device ${id} revoked`));+ } else {+ console.error(chalk.red(` ✗ No device with id ${id}`));+ process.exitCode = 1;+ }+ });+}++function formatAgo(iso: string): string {+ const ms = Date.now() - new Date(iso).getTime();+ if (!Number.isFinite(ms) || ms < 0) return iso;+ const minutes = Math.round(ms / 60_000);+ if (minutes < 1) return 'just now';+ if (minutes < 60) return `${minutes} min ago`;+ const hours = Math.round(minutes / 60);+ if (hours < 48) return `${hours} h ago`;+ return `${Math.round(hours / 24)} days ago`;+}diff --git a/src/index.ts b/src/index.tsindex 42f1445e..e411f0ef 100644--- a/src/index.ts+++ b/src/index.ts@@ -58,6 +58,7 @@ import { BotManager } from './bots/bot-manager.js';import { getPluginManager, peekPluginManager, setProviderLookup } from './plugins/manager.js';import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper } from './plugins/channel-bridge.js';import { registerPluginsCli } from './cli/plugins-cli.js';+import { registerDevicesCli } from './cli/devices-cli.js';import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';import { isSqliteAvailable } from './utils/sqlite-driver.js';import { runStorageDoctor } from './utils/storage-doctor.js';@@ -5018,6 +5019,8 @@ serviceCmdshowServiceStatus();});+registerDevicesCli(program);+program.command('upgrade').description('Upgrade Mercury to the latest version')diff --git a/src/utils/config.ts b/src/utils/config.tsindex f10e8f54..62d3b6ff 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -275,6 +275,12 @@ export interface MercuryConfig {web: {enabled: boolean;port: number;+ /**+ * Extra browser origins allowed to call /api/* with a Bearer token+ * (CORS). Mercury Desktop's own origins are always allowed; list a+ * self-hosted web build or a dev server here. Never '*'.+ */+ corsOrigins?: string[];};mcp?: McpConfig;}diff --git a/src/web/api-contract.test.ts b/src/web/api-contract.test.tsnew file mode 100644index 00000000..c77e1ac3--- /dev/null+++ b/src/web/api-contract.test.ts@@ -0,0 +1,184 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { Hono } from 'hono';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { initWebAuth, createSession } from './auth.js';+import { authGuard } from './middleware.js';+import { createDevice, _resetDeviceState } from './devices.js';+import { apiCors, allowedOrigins, normalizeOrigin } from './cors.js';+import { API_VERSION, API_FEATURES } from './api-contract.js';++/**+ * The contract a remote client (Mercury Desktop, phones) relies on:+ * - a device token opens /api/* from any address;+ * - /api/health answers an authenticated remote peer with apiVersion;+ * - POST /api/auth/token turns a password into a device token, once;+ * - CORS lets the desktop origin in and nobody else.+ */++const REMOTE = { incoming: { socket: { remoteAddress: '10.0.0.7' } } };+const LOOPBACK = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };++describe('api contract', () => {+ let home: string;+ const previousHome = process.env.MERCURY_HOME;++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-contract-'));+ process.env.MERCURY_HOME = home;+ _resetDeviceState();+ });++ afterEach(() => {+ if (previousHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = previousHome;+ rmSync(home, { recursive: true, force: true });+ });++ it('a device token passes the guard from a non-loopback peer; a revoked one does not', async () => {+ const { token } = createDevice('Desktop', 'macos');+ let nextCalled = false;+ const ok = await authGuard(makeContext('/api/chat/models', token, '10.0.0.7'), async () => { nextCalled = true; });+ expect(nextCalled).toBe(true);+ expect(ok).toBeUndefined();++ const { revokeDevice, listDevices } = await import('./devices.js');+ revokeDevice(listDevices()[0].id);+ nextCalled = false;+ const denied = await authGuard(makeContext('/api/chat/models', token, '10.0.0.7'), async () => { nextCalled = true; }) as { status?: number };+ expect(nextCalled).toBe(false);+ expect(denied?.status).toBe(401);+ });++ it('/api/health carries the contract for loopback and for an authenticated remote peer only', async () => {+ const { default: statusRoutes } = await import('./api/status.js');+ const { token } = createDevice('Desktop', 'macos');++ const loopback = await statusRoutes.request('http://127.0.0.1:6174/api/health', {}, LOOPBACK);+ expect(loopback.status).toBe(200);+ const body = await loopback.json() as { apiVersion: number; features: string[]; version: string };+ expect(body.apiVersion).toBe(API_VERSION);+ expect(body.features).toEqual([...API_FEATURES]);++ const anonymous = await statusRoutes.request('http://127.0.0.1:6174/api/health', {}, REMOTE);+ expect(anonymous.status).toBe(404);++ const withDevice = await statusRoutes.request('http://127.0.0.1:6174/api/health', { headers: { Authorization: `Bearer ${token}` } }, REMOTE);+ expect(withDevice.status).toBe(200);+ expect(((await withDevice.json()) as { apiVersion: number }).apiVersion).toBe(API_VERSION);++ const session = createSession();+ const withSession = await statusRoutes.request('http://127.0.0.1:6174/api/health', { headers: { Authorization: `Bearer ${session}` } }, REMOTE);+ expect(withSession.status).toBe(200);+ });++ it('POST /api/auth/token exchanges the password for a device token, then lists and revokes it', async () => {+ const { default: authRoutes } = await import('./api/auth.js');+ const { username, password } = initWebAuth();+ expect(password).not.toBe('');++ const bad = await authRoutes.request('http://127.0.0.1:6174/api/auth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password: 'wrong', deviceName: 'Desktop' }),+ }, REMOTE);+ expect(bad.status).toBe(401);++ const res = await authRoutes.request('http://127.0.0.1:6174/api/auth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password, deviceName: 'Desktop', platform: 'macos' }),+ }, REMOTE);+ expect(res.status).toBe(200);+ const body = await res.json() as { token: string; device: { id: string; name: string }; apiVersion: number; features: string[] };+ expect(body.token).toMatch(/^mdt_/);+ expect(body.device.name).toBe('Desktop');+ expect(body.apiVersion).toBe(API_VERSION);+ expect(Array.isArray(body.features)).toBe(true);++ const list = await authRoutes.request('http://127.0.0.1:6174/api/auth/devices', { headers: { Authorization: `Bearer ${body.token}` } }, REMOTE);+ const listed = await list.json() as { devices: Array<{ id: string }>; current: string };+ expect(listed.devices.map((d) => d.id)).toContain(body.device.id);+ expect(listed.current).toBe(body.device.id);++ const revoke = await authRoutes.request('http://127.0.0.1:6174/api/auth/token/revoke', { method: 'POST', headers: { Authorization: `Bearer ${body.token}` } }, REMOTE);+ expect(revoke.status).toBe(200);+ let nextCalled = false;+ await authGuard(makeContext('/api/chat/models', body.token, '10.0.0.7'), async () => { nextCalled = true; });+ expect(nextCalled).toBe(false);+ });++ it('locks an address out after repeated failures', async () => {+ const { default: authRoutes } = await import('./api/auth.js');+ const { username } = initWebAuth();+ const attacker = { incoming: { socket: { remoteAddress: '203.0.113.9' } } };+ let last = 0;+ for (let i = 0; i < 12; i++) {+ const r = await authRoutes.request('http://127.0.0.1:6174/api/auth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password: `guess-${i}` }),+ }, attacker);+ last = r.status;+ if (last === 429) {+ expect(r.headers.get('Retry-After')).toBeTruthy();+ break;+ }+ }+ expect(last).toBe(429);+ // Another address is unaffected.+ const other = await authRoutes.request('http://127.0.0.1:6174/api/auth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password: 'guess' }),+ }, REMOTE);+ expect(other.status).toBe(401);+ });++ it('CORS admits the desktop origins and configured extras, never a wildcard or a stranger', async () => {+ const app = new Hono();+ app.use('/api/*', apiCors(['https://dashboard.example.com', '*', 'not a url', 'https://x.example/path']));+ app.get('/api/ping', (c) => c.json({ ok: true }));++ const desktop = await app.request('http://127.0.0.1:6174/api/ping', { headers: { Origin: 'tauri://localhost' } });+ expect(desktop.headers.get('Access-Control-Allow-Origin')).toBe('tauri://localhost');+ expect(desktop.headers.get('Access-Control-Allow-Credentials')).toBeNull();++ const windows = await app.request('http://127.0.0.1:6174/api/ping', { headers: { Origin: 'http://tauri.localhost' } });+ expect(windows.headers.get('Access-Control-Allow-Origin')).toBe('http://tauri.localhost');++ const extra = await app.request('http://127.0.0.1:6174/api/ping', { headers: { Origin: 'https://dashboard.example.com' } });+ expect(extra.headers.get('Access-Control-Allow-Origin')).toBe('https://dashboard.example.com');++ const stranger = await app.request('http://127.0.0.1:6174/api/ping', { headers: { Origin: 'https://evil.example' } });+ expect(stranger.headers.get('Access-Control-Allow-Origin')).toBeNull();++ const preflight = await app.request('http://127.0.0.1:6174/api/ping', {+ method: 'OPTIONS',+ headers: { Origin: 'tauri://localhost', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization' },+ });+ expect(preflight.status).toBe(204);+ expect(preflight.headers.get('Access-Control-Allow-Headers')).toMatch(/Authorization/);++ const set = allowedOrigins(['https://a.example'], {} as NodeJS.ProcessEnv);+ expect(set.has('https://a.example')).toBe(true);+ expect(set.has('http://localhost:1420')).toBe(false);+ expect(allowedOrigins([], { MERCURY_DESKTOP_DEV: '1' } as NodeJS.ProcessEnv).has('http://localhost:1420')).toBe(true);+ expect(normalizeOrigin('https://A.example:8443/')).toBe('https://a.example:8443');+ expect(normalizeOrigin('*')).toBeNull();+ });+});++function makeContext(path: string, token: string, remoteAddress: string): any {+ return {+ req: {+ url: `http://127.0.0.1:6174${path}`,+ raw: new Request(`http://127.0.0.1:6174${path}`),+ headers: new Headers(),+ header: (name: string) => name.toLowerCase() === 'authorization' && token ? `Bearer ${token}` : undefined,+ },+ env: { incoming: { socket: { remoteAddress } } },+ json: (body: unknown, status = 200) => ({ body, status }),+ };+}diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsnew file mode 100644index 00000000..663a4ba8--- /dev/null+++ b/src/web/api-contract.ts@@ -0,0 +1,44 @@+/**+ * The API contract between a Mercury runtime and every client that is not+ * shipped inside the same binary: Mercury Desktop, the phone apps, scripts.+ *+ * Two numbers exist and they move independently:+ *+ * - the PACKAGE version (`package.json`, `/api/health.version`) — what to+ * print in an About box and what `mercury upgrade` compares;+ * - the API VERSION (`API_VERSION`, `/api/health.apiVersion`) — a single+ * integer bumped ONLY on a change a client cannot tolerate: a removed or+ * renamed route, a changed response shape, a changed auth scheme.+ *+ * Additive changes never bump the integer. They add a FEATURE flag instead,+ * and clients gate UI on the flag. A client declares the range of API+ * versions it understands; outside that range it tells the user to update+ * one side or the other. `docs/api-contract.md` records which runtime+ * release introduced each version.+ */++export const API_VERSION = 1;++/**+ * Capabilities a client may rely on. Order is irrelevant; names are stable+ * once published (remove = bump API_VERSION).+ */+export const API_FEATURES: readonly string[] = Object.freeze([+ 'auth.devices', // device tokens: POST /api/auth/token, GET/DELETE /api/auth/devices+ 'chat.sse', // GET /api/chat/events (Server-Sent Events)+ 'chat.attachments', // multipart uploads on POST /api/chat/send+ 'bots', // /api/bots/*+ 'plugins', // /api/plugins/*+ 'mcp', // /api/mcp/*+ 'boards', // /api/boards/*+ 'brain', // /api/brain/*+]);++export interface ApiContractInfo {+ apiVersion: number;+ features: readonly string[];+}++export function apiContract(): ApiContractInfo {+ return { apiVersion: API_VERSION, features: API_FEATURES };+}diff --git a/src/web/api/auth.ts b/src/web/api/auth.tsindex 957c19ed..06e4b994 100644--- a/src/web/api/auth.ts+++ b/src/web/api/auth.ts@@ -6,6 +6,10 @@ import { join, dirname } from 'path';import { fileURLToPath } from 'url';import process from 'node:process';import { authenticate, createSession, destroySession, changePassword, changeUsername, getSessionCookieName, getSessionMaxAge } from '../auth.js';+import { createDevice, listDevices, revokeDevice } from '../devices.js';+import { authenticateRequest, bearerToken } from '../middleware.js';+import { apiContract } from '../api-contract.js';+import { createLoginLimiter } from '../login-limiter.js';function resolveWebDir(...segments: string[]): string {const __dirname = dirname(fileURLToPath(import.meta.url));@@ -97,6 +101,89 @@ auth.get('/api/auth/logout', (c) => {return c.redirect('/login');});+// ── Device tokens (Mercury Desktop, phones, scripts) ──────────────────────+//+// POST /api/auth/token { username, password, deviceName?, platform? }+// → 200 { token, device, apiVersion, features, version? }+// → 401 bad credentials · 429 too many failures from this address+//+// The token is the only credential the client keeps; the password is never+// stored on the device. Same bcrypt check as the web login, plus a small+// per-address failure limiter because this endpoint is reachable without a+// browser and will be pointed at from the internet through tunnels.++const tokenLimiter = createLoginLimiter();++function peerAddress(c: { env?: unknown }): string {+ try {+ return String((c.env as any)?.incoming?.socket?.remoteAddress || 'unknown');+ } catch {+ return 'unknown';+ }+}++auth.post('/api/auth/token', async (c) => {+ const peer = peerAddress(c);+ const wait = tokenLimiter.retryAfterSeconds(peer);+ if (wait > 0) {+ c.header('Retry-After', String(wait));+ return c.json({ error: 'Too many failed sign-in attempts; try again later' }, 429);+ }+ let body: Record<string, unknown>;+ try {+ body = await c.req.json();+ } catch {+ return c.json({ error: 'Expected a JSON body' }, 400);+ }+ const username = typeof body.username === 'string' ? body.username : '';+ const password = typeof body.password === 'string' ? body.password : '';+ if (!username || !password) {+ return c.json({ error: 'Username and password required' }, 400);+ }+ if (!authenticate(username, password)) {+ tokenLimiter.recordFailure(peer);+ return c.json({ error: 'Invalid username or password' }, 401);+ }+ tokenLimiter.reset(peer);+ let created;+ try {+ created = createDevice(body.deviceName, body.platform);+ } catch (err: any) {+ return c.json({ error: err?.message || 'Could not create device' }, 409);+ }+ return c.json({ token: created.token, device: created.device, ...apiContract() });+});++auth.get('/api/auth/devices', (c) => {+ const principal = authenticateRequest(c);+ return c.json({+ devices: listDevices(),+ current: principal?.kind === 'device' ? principal.deviceId : null,+ });+});++auth.delete('/api/auth/devices/:id', (c) => {+ const id = c.req.param('id');+ if (!/^[0-9a-f]{8}$/.test(id)) return c.json({ error: 'Bad device id' }, 400);+ return revokeDevice(id) ? c.json({ success: true }) : c.json({ error: 'No such device' }, 404);+});++/** Sign out this device: revoke the token that made the call. */+auth.post('/api/auth/token/revoke', (c) => {+ const principal = authenticateRequest(c);+ if (principal?.kind !== 'device') return c.json({ error: 'Not a device token' }, 400);+ revokeDevice(principal.deviceId);+ return c.json({ success: true });+});++// Sessions obtained with a Bearer header (scripts, or a desktop client on+// the web-session path) end here instead of through the cookie redirect.+auth.post('/api/auth/logout', (c) => {+ const token = bearerToken(c) || getCookie(c, getSessionCookieName());+ if (token) destroySession(token);+ return c.json({ success: true });+});+auth.post('/api/auth/password', async (c) => {const body = await c.req.json();const { currentPassword, newPassword } = body;diff --git a/src/web/api/status.ts b/src/web/api/status.tsindex 9d93edf0..e06fd849 100644--- a/src/web/api/status.ts+++ b/src/web/api/status.ts@@ -2,7 +2,8 @@ import { Hono } from 'hono';import { readFileSync } from 'node:fs';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';-import { isLoopbackRequest } from '../middleware.js';+import { isLoopbackRequest, authenticateRequest } from '../middleware.js';+import { apiContract } from '../api-contract.js';import { peekPluginManager } from '../../plugins/manager.js';import { getLoopLag } from '../../utils/loop-lag.js';@@ -54,16 +55,24 @@ function versionString(): string {}/**- * Liveness for `mercury attach` — no auth, loopback only, answers the- * moment the listener is bound (before channels and bots have booted). The- * pid lets a launcher tell "my runtime, still booting" from "some other- * process owns this port" without a restart.+ * Liveness for `mercury attach` and the handshake for every remote client.+ *+ * - Loopback: no auth, answers the moment the listener is bound (before+ * channels and bots have booted). The pid lets a launcher tell "my+ * runtime, still booting" from "some other process owns this port".+ * - Any other peer: only with a valid credential (device token or web+ * session). Unauthenticated, the runtime stays invisible (404), exactly+ * as before — a scanner learns nothing. A client with no token yet goes+ * through POST /api/auth/token, whose reply carries the same contract.+ *+ * `apiVersion` / `features` are the contract (api-contract.ts); `version`+ * is the package version, for display only.*/status.get('/api/health', (c) => {- if (!isLoopbackRequest(c)) return c.json({ error: 'Not found' }, 404);+ if (!isLoopbackRequest(c) && !authenticateRequest(c)) return c.json({ error: 'Not found' }, 404);const lag = getLoopLag();const plugins = peekPluginManager()?.health();- return c.json({ ok: true, pid: process.pid, version: versionString(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) }, ...(plugins ? { plugins: { safeMode: plugins.safeMode, running: plugins.running, tools: plugins.tools } } : {}) });+ return c.json({ ok: true, pid: process.pid, version: versionString(), ...apiContract(), state: currentStatus.state, booting: currentStatus.state === 'booting', loopLag: { p99Ms: Math.round(lag.p99Ms), maxMs: Math.round(lag.maxMs) }, ...(plugins ? { plugins: { safeMode: plugins.safeMode, running: plugins.running, tools: plugins.tools } } : {}) });});status.get('/api/status', (c) => {diff --git a/src/web/cors.ts b/src/web/cors.tsnew file mode 100644index 00000000..150d87fd--- /dev/null+++ b/src/web/cors.ts@@ -0,0 +1,62 @@+import { cors } from 'hono/cors';+import type { MiddlewareHandler } from 'hono';++/**+ * CORS for clients that are not served by this runtime: Mercury Desktop's+ * webview has its own origin (`tauri://localhost` on macOS and Linux,+ * `http://tauri.localhost` on Windows). Browsers served from this runtime+ * are same-origin and never need this.+ *+ * Authentication is `Authorization: Bearer`, never a cookie, so this does+ * not enable credentials and a cross-site page cannot ride the session+ * cookie through it. Extra origins (a self-hosted web build, a dev server)+ * come from `web.corsOrigins` in mercury.yaml.+ */++export const DESKTOP_ORIGINS: readonly string[] = Object.freeze([+ 'tauri://localhost',+ 'http://tauri.localhost',+ 'https://tauri.localhost',+]);++/** Vite's default port for `tauri dev`; only honored when the developer asks for it. */+const DEV_ORIGINS: readonly string[] = Object.freeze([+ 'http://localhost:1420',+ 'http://127.0.0.1:1420',+]);++export function allowedOrigins(extra: readonly string[] | undefined, env: NodeJS.ProcessEnv = process.env): Set<string> {+ const set = new Set<string>(DESKTOP_ORIGINS);+ if (env.MERCURY_DESKTOP_DEV === '1') for (const o of DEV_ORIGINS) set.add(o);+ for (const raw of extra ?? []) {+ const origin = normalizeOrigin(raw);+ if (origin) set.add(origin);+ }+ return set;+}++/** An origin is scheme://host[:port], nothing else. Anything else is dropped. */+export function normalizeOrigin(raw: unknown): string | null {+ if (typeof raw !== 'string') return null;+ const trimmed = raw.trim();+ if (!trimmed || trimmed === '*') return null; // never wildcard an authenticated API+ try {+ const url = new URL(trimmed);+ if (url.pathname !== '/' || url.search || url.hash || url.username || url.password) return null;+ return url.origin === 'null' ? null : url.origin;+ } catch {+ return null;+ }+}++export function apiCors(extra: readonly string[] | undefined): MiddlewareHandler {+ const allowed = allowedOrigins(extra);+ return cors({+ origin: (origin) => (allowed.has(origin) ? origin : null),+ allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],+ allowHeaders: ['Authorization', 'Content-Type', 'Accept', 'Last-Event-ID'],+ exposeHeaders: ['Content-Type', 'Content-Disposition'],+ maxAge: 600,+ credentials: false,+ });+}diff --git a/src/web/devices.test.ts b/src/web/devices.test.tsnew file mode 100644index 00000000..df434342--- /dev/null+++ b/src/web/devices.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir, platform } from 'node:os';+import { join } from 'node:path';+import { createDevice, listDevices, revokeDevice, validateDeviceToken, looksLikeDeviceToken, getDevicesPath, _resetDeviceState, normalizeDeviceName } from './devices.js';++/**+ * Device tokens: the credential a remote client (Mercury Desktop, a phone)+ * keeps. Hashed at rest, constant-time compared, revocable one at a time.+ */+describe('device tokens', () => {+ let home: string;+ const previousHome = process.env.MERCURY_HOME;++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-devices-'));+ process.env.MERCURY_HOME = home;+ _resetDeviceState();+ });++ afterEach(() => {+ if (previousHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = previousHome;+ rmSync(home, { recursive: true, force: true });+ });++ it('creates a token that validates, and stores only its hash', () => {+ const created = createDevice('Office laptop', 'macos');+ expect(created.token).toMatch(/^mdt_[0-9a-f]{8}_[0-9a-f]{64}$/);+ expect(looksLikeDeviceToken(created.token)).toBe(true);++ const device = validateDeviceToken(created.token);+ expect(device?.id).toBe(created.device.id);+ expect(device?.name).toBe('Office laptop');+ expect(device?.platform).toBe('macos');++ const raw = readFileSync(getDevicesPath(), 'utf-8');+ expect(raw).not.toContain(created.token.split('_')[2]);+ if (platform() !== 'win32') {+ expect(statSync(getDevicesPath()).mode & 0o777).toBe(0o600);+ }+ });++ it('rejects a wrong secret, a wrong id and malformed strings', () => {+ const created = createDevice('Phone', 'android');+ const [prefix, id, secret] = created.token.split('_');+ const flipped = secret[0] === 'a' ? 'b' : 'a';+ expect(validateDeviceToken(`${prefix}_${id}_${flipped}${secret.slice(1)}`)).toBeNull();+ expect(validateDeviceToken(`${prefix}_deadbeef_${secret}`)).toBeNull();+ expect(validateDeviceToken('')).toBeNull();+ expect(validateDeviceToken('Bearer x')).toBeNull();+ expect(looksLikeDeviceToken('mdt_short')).toBe(false);+ });++ it('revokes one device without touching the others', () => {+ const a = createDevice('A');+ const b = createDevice('B');+ expect(listDevices().map((d) => d.id).sort()).toEqual([a.device.id, b.device.id].sort());+ expect(revokeDevice(a.device.id)).toBe(true);+ expect(revokeDevice(a.device.id)).toBe(false);+ expect(validateDeviceToken(a.token)).toBeNull();+ expect(validateDeviceToken(b.token)?.id).toBe(b.device.id);+ });++ it('survives a corrupt file by treating it as empty, never by throwing', () => {+ writeFileSync(getDevicesPath(), '{not json', { mode: 0o600 });+ expect(listDevices()).toEqual([]);+ expect(validateDeviceToken('mdt_00000000_' + '0'.repeat(64))).toBeNull();+ const created = createDevice('After corruption');+ expect(validateDeviceToken(created.token)?.id).toBe(created.device.id);+ });++ it('records last-seen on use, at most once a minute', () => {+ const created = createDevice('Laptop');+ expect(listDevices()[0].lastSeenAt).toBeNull();+ validateDeviceToken(created.token);+ const first = listDevices()[0].lastSeenAt;+ expect(first).toBeTruthy();+ validateDeviceToken(created.token);+ expect(listDevices()[0].lastSeenAt).toBe(first);+ });++ it('sanitises names: control characters out, length capped, empty becomes a default', () => {+ expect(normalizeDeviceName(' Office\u0007 laptop ')).toBe('Office laptop');+ expect(normalizeDeviceName('x'.repeat(100))).toHaveLength(64);+ expect(normalizeDeviceName('')).toBe('Unnamed device');+ expect(normalizeDeviceName(undefined)).toBe('Unnamed device');+ });+});diff --git a/src/web/devices.ts b/src/web/devices.tsnew file mode 100644index 00000000..8056daed--- /dev/null+++ b/src/web/devices.ts@@ -0,0 +1,191 @@+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * Device tokens — long-lived bearer credentials for clients that are not on+ * this machine's loopback: Mercury Desktop on another computer, a phone,+ * a script on a server. One token per device, revocable one at a time.+ *+ * Why not the web session? Sessions live in memory, die with the process and+ * are cookie-shaped; a desktop app needs something it can keep in the OS+ * keychain and present as `Authorization: Bearer` from any address.+ *+ * Why not the attach token? That one is a per-boot, loopback-only secret+ * for `mercury attach` and must stay that way.+ *+ * Storage: `~/.mercury/devices.json`, owner-only, holding only a SHA-256 of+ * each secret. The plaintext token is shown exactly once, at creation.+ *+ * Token shape: `mdt_<id>_<secret>` — `mdt` = Mercury device token, the id+ * selects the record (so lookup is O(1) and the hash compare is constant+ * time), the secret is 32 random bytes.+ */++export interface DeviceRecord {+ id: string;+ name: string;+ /** Free-form: "macos", "windows", "linux", "android", "ios", "script". */+ platform: string;+ tokenHash: string;+ createdAt: string;+ lastSeenAt: string | null;+}++export interface DeviceSummary {+ id: string;+ name: string;+ platform: string;+ createdAt: string;+ lastSeenAt: string | null;+}++interface DevicesFile {+ version: 1;+ devices: DeviceRecord[];+}++const FILE_NAME = 'devices.json';+const TOKEN_PREFIX = 'mdt';+const TOKEN_RE = /^mdt_([0-9a-f]{8})_([0-9a-f]{64})$/;+/** How often `lastSeenAt` is written back — once a minute per device is plenty. */+const LAST_SEEN_WRITE_INTERVAL_MS = 60_000;++const lastSeenWrites = new Map<string, number>();++export function getDevicesPath(): string {+ return join(getMercuryHome(), FILE_NAME);+}++function hashSecret(secret: string): string {+ return createHash('sha256').update(secret, 'utf8').digest('hex');+}++function readFile(): DevicesFile {+ const path = getDevicesPath();+ if (!existsSync(path)) return { version: 1, devices: [] };+ try {+ // Repair permissions on a file a previous version might have left 0644.+ try { chmodSync(path, 0o600); } catch { /* best effort */ }+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Partial<DevicesFile>;+ if (parsed.version !== 1 || !Array.isArray(parsed.devices)) return { version: 1, devices: [] };+ return { version: 1, devices: parsed.devices.filter(isRecord) };+ } catch {+ return { version: 1, devices: [] };+ }+}++function isRecord(value: unknown): value is DeviceRecord {+ if (!value || typeof value !== 'object') return false;+ const v = value as Record<string, unknown>;+ return typeof v.id === 'string' && typeof v.name === 'string' && typeof v.tokenHash === 'string';+}++function writeFile(data: DevicesFile): void {+ const home = getMercuryHome();+ if (!existsSync(home)) mkdirSync(home, { recursive: true });+ const path = getDevicesPath();+ // Write-then-rename so a crash mid-write never leaves a truncated file+ // (which would silently revoke every device).+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: 0o600 });+ try { chmodSync(tmp, 0o600); } catch { /* best effort */ }+ renameSync(tmp, path);+}++export function listDevices(): DeviceSummary[] {+ return readFile().devices.map(toSummary);+}++function toSummary(d: DeviceRecord): DeviceSummary {+ return { id: d.id, name: d.name, platform: d.platform, createdAt: d.createdAt, lastSeenAt: d.lastSeenAt };+}++export interface CreatedDevice {+ device: DeviceSummary;+ /** The plaintext token. Shown once; never stored. */+ token: string;+}++const MAX_NAME_LENGTH = 64;+const MAX_DEVICES = 200;++export function normalizeDeviceName(name: unknown): string {+ const trimmed = String(name ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();+ return (trimmed || 'Unnamed device').slice(0, MAX_NAME_LENGTH);+}++export function normalizePlatform(platform: unknown): string {+ const p = String(platform ?? '').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 24);+ return p || 'unknown';+}++export function createDevice(name: unknown, platform?: unknown): CreatedDevice {+ const data = readFile();+ if (data.devices.length >= MAX_DEVICES) {+ throw new Error(`Too many devices (${MAX_DEVICES}); revoke one first`);+ }+ let id = randomBytes(4).toString('hex');+ while (data.devices.some((d) => d.id === id)) id = randomBytes(4).toString('hex');+ const secret = randomBytes(32).toString('hex');+ const record: DeviceRecord = {+ id,+ name: normalizeDeviceName(name),+ platform: normalizePlatform(platform),+ tokenHash: hashSecret(secret),+ createdAt: new Date().toISOString(),+ lastSeenAt: null,+ };+ data.devices.push(record);+ writeFile(data);+ return { device: toSummary(record), token: `${TOKEN_PREFIX}_${id}_${secret}` };+}++export function revokeDevice(id: string): boolean {+ const data = readFile();+ const before = data.devices.length;+ data.devices = data.devices.filter((d) => d.id !== id);+ if (data.devices.length === before) return false;+ writeFile(data);+ lastSeenWrites.delete(id);+ return true;+}++/** True when the string has the device-token shape (cheap pre-check; no I/O). */+export function looksLikeDeviceToken(token: string): boolean {+ return TOKEN_RE.test(token);+}++/**+ * Resolve a bearer token to its device, or null. Constant-time on the+ * secret; the id lookup is by equality, which only reveals whether an id+ * exists — ids are not secret.+ */+export function validateDeviceToken(token: string): DeviceSummary | null {+ const match = TOKEN_RE.exec(token);+ if (!match) return null;+ const [, id, secret] = match;+ const data = readFile();+ const record = data.devices.find((d) => d.id === id);+ if (!record) return null;+ const expected = Buffer.from(record.tokenHash, 'hex');+ const actual = Buffer.from(hashSecret(secret), 'hex');+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;+ touchLastSeen(data, record);+ return toSummary(record);+}++function touchLastSeen(data: DevicesFile, record: DeviceRecord): void {+ const now = Date.now();+ const last = lastSeenWrites.get(record.id) ?? 0;+ if (now - last < LAST_SEEN_WRITE_INTERVAL_MS) return;+ lastSeenWrites.set(record.id, now);+ record.lastSeenAt = new Date(now).toISOString();+ try { writeFile(data); } catch { /* best effort: last-seen is cosmetic */ }+}++/** Test hook: forget write throttling between cases. */+export function _resetDeviceState(): void {+ lastSeenWrites.clear();+}diff --git a/src/web/login-limiter.test.ts b/src/web/login-limiter.test.tsnew file mode 100644index 00000000..e6a2ffa0--- /dev/null+++ b/src/web/login-limiter.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { createLoginLimiter } from './login-limiter.js';++describe('login limiter', () => {+ it('allows up to the limit, then locks for the lockout window, then forgets', () => {+ let t = 1_000_000;+ const limiter = createLoginLimiter({ maxFailures: 3, windowMs: 60_000, lockoutMs: 30_000, now: () => t });+ const ip = '10.0.0.1';+ expect(limiter.retryAfterSeconds(ip)).toBe(0);+ limiter.recordFailure(ip);+ limiter.recordFailure(ip);+ expect(limiter.retryAfterSeconds(ip)).toBe(0);+ limiter.recordFailure(ip);+ expect(limiter.retryAfterSeconds(ip)).toBe(30);+ t += 10_000;+ expect(limiter.retryAfterSeconds(ip)).toBe(20);+ t += 21_000;+ expect(limiter.retryAfterSeconds(ip)).toBe(0);+ });++ it('a success clears the slate', () => {+ const limiter = createLoginLimiter({ maxFailures: 2 });+ limiter.recordFailure('a');+ limiter.reset('a');+ limiter.recordFailure('a');+ expect(limiter.retryAfterSeconds('a')).toBe(0);+ });++ it('old failures outside the window do not count', () => {+ let t = 0;+ const limiter = createLoginLimiter({ maxFailures: 2, windowMs: 1_000, now: () => t });+ limiter.recordFailure('a');+ t += 5_000;+ limiter.recordFailure('a');+ expect(limiter.retryAfterSeconds('a')).toBe(0);+ });+});diff --git a/src/web/login-limiter.ts b/src/web/login-limiter.tsnew file mode 100644index 00000000..c4a62dad--- /dev/null+++ b/src/web/login-limiter.ts@@ -0,0 +1,79 @@+/**+ * Per-address failure limiter for password endpoints that are reachable+ * without a browser. Small and in-memory on purpose: the goal is to turn an+ * online guess from "thousands per second" into "ten per quarter hour",+ * not to be a WAF. bcrypt already makes each attempt slow.+ */++export interface LoginLimiter {+ /** Seconds the caller must wait, or 0 when an attempt is allowed. */+ retryAfterSeconds(key: string): number;+ recordFailure(key: string): void;+ reset(key: string): void;+}++export interface LoginLimiterOptions {+ maxFailures?: number;+ windowMs?: number;+ lockoutMs?: number;+ now?: () => number;+}++interface Entry {+ failures: number;+ firstFailureAt: number;+ lockedUntil: number;+}++const MAX_TRACKED = 10_000;++export function createLoginLimiter(options: LoginLimiterOptions = {}): LoginLimiter {+ const maxFailures = options.maxFailures ?? 10;+ const windowMs = options.windowMs ?? 15 * 60_000;+ const lockoutMs = options.lockoutMs ?? 15 * 60_000;+ const now = options.now ?? Date.now;+ const entries = new Map<string, Entry>();++ function prune(t: number): void {+ if (entries.size < MAX_TRACKED) return;+ for (const [key, e] of entries) {+ if (e.lockedUntil <= t && t - e.firstFailureAt > windowMs) entries.delete(key);+ }+ // Still full (an attacker spraying addresses): drop the oldest half.+ if (entries.size >= MAX_TRACKED) {+ let i = 0;+ for (const key of entries.keys()) {+ if (i++ % 2 === 0) entries.delete(key);+ }+ }+ }++ return {+ retryAfterSeconds(key) {+ const e = entries.get(key);+ if (!e) return 0;+ const t = now();+ if (e.lockedUntil > t) return Math.max(1, Math.ceil((e.lockedUntil - t) / 1000));+ if (t - e.firstFailureAt > windowMs) entries.delete(key);+ return 0;+ },+ recordFailure(key) {+ const t = now();+ prune(t);+ const e = entries.get(key);+ if (!e || t - e.firstFailureAt > windowMs) {+ entries.set(key, { failures: 1, firstFailureAt: t, lockedUntil: 0 });+ return;+ }+ e.failures += 1;+ if (e.failures >= maxFailures) {+ e.lockedUntil = t + lockoutMs;+ e.failures = 0;+ e.firstFailureAt = t;+ }+ },+ reset(key) {+ entries.delete(key);+ },+ };+}diff --git a/src/web/middleware.ts b/src/web/middleware.tsindex 0496e708..d2f9d96e 100644--- a/src/web/middleware.ts+++ b/src/web/middleware.ts@@ -1,8 +1,9 @@import { Context, Next } from 'hono';import { getCookie } from 'hono/cookie';import { validateSession, getSessionCookieName, readAttachToken } from './auth.js';+import { looksLikeDeviceToken, validateDeviceToken } from './devices.js';-const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout', '/api/health']);+const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout', '/api/auth/token', '/api/health']);/*** The attach token is only honored from loopback connections. Defense in@@ -18,6 +19,42 @@ export function isLoopbackRequest(c: Context): boolean {}}+export type Principal =+ | { kind: 'session' }+ | { kind: 'attach' }+ | { kind: 'device'; deviceId: string; deviceName: string };++export function bearerToken(c: Context): string | null {+ const header = c.req.header('Authorization');+ if (!header) return null;+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());+ return match ? match[1].trim() : null;+}++/**+ * Who is calling, or null.+ *+ * - web session: cookie (browser) or Bearer (scripts) — any peer;+ * - device token: Bearer, any peer — that is its purpose (devices.ts);+ * - attach token: Bearer, loopback only.+ */+export function authenticateRequest(c: Context): Principal | null {+ const cookieToken = getCookie(c, getSessionCookieName());+ if (cookieToken && validateSession(cookieToken)) return { kind: 'session' };++ const bearer = bearerToken(c);+ if (!bearer) return null;+ if (validateSession(bearer)) return { kind: 'session' };+ if (looksLikeDeviceToken(bearer)) {+ const device = validateDeviceToken(bearer);+ return device ? { kind: 'device', deviceId: device.id, deviceName: device.name } : null;+ }+ // Attach clients (`mercury attach`) authenticate with the machine-local+ // token instead of the interactive web login.+ if (isLoopbackRequest(c) && bearer === readAttachToken()) return { kind: 'attach' };+ return null;+}+export async function authGuard(c: Context, next: Next) {const path = new URL(c.req.url).pathname;if (path.startsWith('/vendor/') || path.startsWith('/static/') || path.startsWith('/assets/') || path.startsWith('/icons/') || path.endsWith('.css') || path.endsWith('.js') || path.endsWith('.png') || path.endsWith('.ico') || path.endsWith('.svg') || path.endsWith('.woff2') || path.endsWith('.webmanifest')) {@@ -27,13 +64,7 @@ export async function authGuard(c: Context, next: Next) {return next();}if (path.startsWith('/api/')) {- const token = getCookie(c, getSessionCookieName()) || c.req.header('Authorization')?.replace('Bearer ', '');- if (token && validateSession(token)) {- return next();- }- // Attach clients (`mercury attach`) authenticate with the machine-local- // token instead of the interactive web login.- if (token && isLoopbackRequest(c) && token === readAttachToken()) {+ if (authenticateRequest(c)) {return next();}return c.json({ error: 'Unauthorized' }, 401);@@ -55,4 +86,4 @@ export async function errorHandler(c: Context, next: Next) {}return c.html('<h1>500 — Internal Server Error</h1>', 500);}-}\ No newline at end of file+}diff --git a/src/web/server.ts b/src/web/server.tsindex 08f55641..34e9e496 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -6,7 +6,9 @@ import { join, dirname, extname } from 'node:path';import { fileURLToPath } from 'node:url';import { logger } from '../utils/logger.js';import { authGuard, errorHandler } from './middleware.js';+import { apiCors } from './cors.js';import { initWebAuth, getWebPort } from './auth.js';+import { loadConfig } from '../utils/config.js';import authRoutes from './api/auth.js';import statusRoutes, { updateStatus } from './api/status.js';import providerRoutes from './api/providers.js';@@ -32,6 +34,15 @@ const app = new Hono();const __dirname = dirname(fileURLToPath(import.meta.url));+function readCorsOrigins(): string[] {+ try {+ const list = loadConfig().web?.corsOrigins;+ return Array.isArray(list) ? list.filter((o): o is string => typeof o === 'string') : [];+ } catch {+ return [];+ }+}+function resolveWebDir(subpath: string): string {const envVar = subpath === 'static' ? process.env.MERCURY_WEB_STATIC : process.env.MERCURY_UI_DIR;if (envVar) return envVar;@@ -69,6 +80,10 @@ const spaIndexPath = join(uiDir, 'index.html');const spaAvailable = existsSync(spaIndexPath);app.use('*', errorHandler);+// CORS before the guard: a preflight (OPTIONS) carries no credential and+// must be answered, not rejected. API routes only; the dashboard itself is+// same-origin.+app.use('/api/*', apiCors(readCorsOrigins()));app.use('*', authGuard);// ── API routes (always available) ──