Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(security): remote access you control — true origin checks, owner approvals, device lifecycle
Salman Qureshia56b6436b0c2
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex d9d671b6..d90bc42d 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -1,3 +1,4 @@+import { commandTouchesMercuryCredentials, isMercuryCredentialPath } from '../security/protected-paths.js';import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, lstatSync } from 'node:fs';import { join, resolve, sep, dirname, basename } from 'node:path';import { homedir } from 'node:os';@@ -732,6 +733,10 @@ export class PermissionManager {* calls, because the file system can change between them.*/async checkFsAccess(path: string, mode: 'read' | 'write'): Promise<FsAccessResult> {+ // Mercury's login credentials are off limits to its own tools, whatever the scopes or mode.+ if (isMercuryCredentialPath(path)) {+ return { allowed: false, reason: "Permission denied: that is one of Mercury's login credential files (device tokens, password, sessions). Manage devices with /server.", code: 'denied' };+ }if (mode === 'write') return this.checkScopedAccess(path, mode);const resolved = resolve(path);@@ -958,6 +963,9 @@ export class PermissionManager {}const trimmed = command.trim();+ if (commandTouchesMercuryCredentials(trimmed)) {+ return { allowed: false, reason: "Blocked: the command names one of Mercury's login credential files (device tokens, password, sessions). Manage devices with /server.", needsApproval: false };+ }const segments = splitShellSegments(trimmed);const ctx = this.ctx();const cwd = options.cwd ?? this.cwd;diff --git a/src/channels/discord.ts b/src/channels/discord.tsindex 81e147f0..3cad4a68 100644--- a/src/channels/discord.ts+++ b/src/channels/discord.ts@@ -924,10 +924,14 @@ export class DiscordChannel extends BaseChannel {const resolver = this.pendingApprovals.get(customId);if (resolver) {if (customId.startsWith('perm_') || customId.startsWith('perm_mode_') || customId.startsWith('loop_')) {- const metadata = this.lastMessageMetadata;- if (metadata && !metadata.isDM && !metadata.isAdmin) {- await interaction.reply({ content: 'Only admins can approve actions in server channels.', flags: MessageFlags.Ephemeral });- return;+ // Whoever CLICKED must be an admin (not whoever sent the last message):+ // in a server channel anyone can press a button.+ if (interaction.inGuild() && interaction.guild) {+ const member = await interaction.guild.members.fetch(interaction.user.id).catch(() => null);+ if (!(await this.isGuildAdmin(member, interaction.guild))) {+ await interaction.reply({ content: 'Only admins can approve actions in server channels.', flags: MessageFlags.Ephemeral });+ return;+ }}}this.pendingApprovals.delete(customId);diff --git a/src/channels/slack.ts b/src/channels/slack.tsindex ec65f0c9..9ef0ddcc 100644--- a/src/channels/slack.ts+++ b/src/channels/slack.ts@@ -199,6 +199,11 @@ export class SlackChannel extends BaseChannel {}const resolver = this.pendingApprovals.get(actionId);+ // In a channel anyone can press a button: only an admin's click counts (a DM has only the owner).+ if (resolver && channel && !channel.startsWith('D') && !findSlackAdmin(this.config, userId)) {+ try { await client.chat.postEphemeral({ channel, user: userId, text: 'Only admins can approve actions in this channel.' }); } catch { /* best effort */ }+ return;+ }if (resolver) {this.pendingApprovals.delete(actionId);for (const suffix of [':yes', ':always', ':no', ':ask-me', ':allow-all']) {diff --git a/src/channels/web.ts b/src/channels/web.tsindex 9107ef9e..97a8cfe2 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -22,7 +22,7 @@ interface PendingInteraction {}export interface ChatEvent {- type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice';+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice' | 'owner_approval';data?: Record<string, unknown>;}@@ -109,14 +109,25 @@ export class WebChannel extends BaseChannel {this.sseClients.delete(id);}- addActivityClient(controller: ReadableStreamDefaultController): string {+ addActivityClient(controller: ReadableStreamDefaultController, thisComputer = false): string {const id = `act_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;this.activityClients.set(id, new SSEClient(controller, id));+ if (thisComputer) this.localActivityClients.add(id);return id;}+ /** Activity screens on this computer: the only ones that get security questions (they can answer them). */+ private localActivityClients = new Set<string>();++ /** A security question for the owner (owner-approvals), to Mercury Desktop on this computer only. */+ sendOwnerApproval(a: { id: string; code: string; kind: string; title: string; detail?: string; who: string; ip?: string; expiresAt: number; status: string }, change: 'new' | 'decided'): void {+ const out: ChatEvent = { type: 'owner_approval', data: { change, id: a.id, code: a.code, kind: a.kind, title: a.title, detail: a.detail, who: a.who, ip: a.ip, expiresAt: a.expiresAt, status: a.status } };+ for (const id of this.localActivityClients) this.activityClients.get(id)?.send(out);+ }+removeActivityClient(id: string): void {this.activityClients.delete(id);+ this.localActivityClients.delete(id);}setSessionTitleLookup(fn: (sessionId: string) => string | undefined): void {diff --git a/src/core/agent.ts b/src/core/agent.tsindex e43c8551..c8d449bc 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -17,6 +17,11 @@ import { DeepSeekProvider } from '../providers/deepseek.js';import { ArtifactCollector } from '../artifacts/collector.js';import { artifactStore, type Artifact } from '../artifacts/store.js';import { chatFoldersFor, outputRoot, researchDir, type ChatFolders } from '../artifacts/output-dir.js';+import { ownerApprovals } from '../security/owner-approvals.js';+import { approvalAnsweredText, approvalRequestText, isOwnerSender, newLocationText, parseApprovalReply } from '../security/approval-messages.js';+import { audit } from '../security/audit.js';+import { setApprovalRoutes } from '../web/owner-gate.js';+import { onDeviceNewLocation } from '../web/middleware.js';import { artifactKindLabel, artifactRef, formatBytes } from '../artifacts/ref.js';import { getMercuryHome } from '../utils/config.js';import { createProvider } from '../providers/registry.js';@@ -669,6 +674,7 @@ export class Agent {this.scheduler.setOnScheduledTask(async (manifest) => this.handleScheduledTask(manifest));this.channels.onIncomingMessage((msg) => this.enqueueMessage(msg));+ this.wireOwnerApprovals();this.scheduler.onHeartbeat(async () => {await this.heartbeat();@@ -716,6 +722,58 @@ export class Agent {});}+ /**+ * Security questions for the owner (owner-approvals): sent to every+ * messaging channel they connected and shown in the CLI here; answered by+ * a reply with the code from an admin of that channel, /server here, or+ * Mercury Desktop on this computer.+ */+ private wireOwnerApprovals(): void {+ const messaging = () => this.channels.getActiveChannels().filter((t) => t !== 'cli' && t !== 'web' && t !== 'internal').map((t) => this.channels.get(t)).filter((ch): ch is NonNullable<typeof ch> => !!ch && ch.isReady() && !ch.noBroadcast);+ const label = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);+ setApprovalRoutes(() => [...messaging().map((ch) => label(ch.type)), 'this computer (/server or Mercury Desktop)']);+ ownerApprovals().onChange((a, change) => {+ const cli = this.channels.get('cli');+ if (change === 'new') {+ const text = approvalRequestText(a);+ for (const ch of messaging()) void ch.send(text).catch((e) => logger.warn({ e, channel: ch.type }, 'Owner approval: send failed'));+ if (cli instanceof CLIChannel) cli.sendSystemNotice(`${text.replace(/Reply “approve (\w+)” to allow it, or “deny \w+”/, 'Answer with /server approve $1 (or deny $1)')}`);+ const web = this.channels.get('web');+ if (web instanceof WebChannel) web.sendOwnerApproval(a, 'new');+ } else {+ const web = this.channels.get('web');+ if (web instanceof WebChannel) web.sendOwnerApproval(a, 'decided');+ }+ });+ onDeviceNewLocation((device, ip) => {+ const text = newLocationText(device.name, ip);+ for (const ch of messaging()) void ch.send(text).catch(() => {});+ const cli = this.channels.get('cli');+ if (cli instanceof CLIChannel) cli.sendSystemNotice(text);+ });+ }++ /** A messaging-channel reply to a security question. True when it was one (and nothing else should see it). */+ private answerOwnerApproval(msg: ChannelMessage): boolean {+ if (msg.channelType === 'cli' || msg.channelType === 'web' || msg.channelType === 'internal') return false;+ const reply = parseApprovalReply(msg.content);+ if (!reply) return false;+ const pending = ownerApprovals().find(reply.code);+ if (!pending || pending.status !== 'pending') return false;+ const channel = this.channels.getChannelForMessage(msg);+ if (!isOwnerSender(msg)) {+ void channel?.send('Only the owner (an admin of this chat) can answer that.', msg.channelId).catch(() => {});+ audit('action.denied', { who: pending.who, detail: `answer from a non-admin on ${msg.channelType} ignored`, by: msg.channelType });+ return true;+ }+ const decided = ownerApprovals().decide(reply.code, reply.decision, msg.channelType);+ if (!decided) return false;+ if (decided.kind === 'action') audit(decided.status === 'allowed' ? 'action.allowed' : 'action.denied', { who: decided.who, ip: decided.ip, detail: decided.title, by: msg.channelType });+ else if (decided.status === 'denied') audit('pair.denied', { who: decided.who, ip: decided.ip, by: msg.channelType });+ void channel?.send(approvalAnsweredText(decided), msg.channelId).catch(() => {});+ return true;+ }+getBotManager(): import('../bots/bot-manager.js').BotManager | undefined {return this.botManager;}@@ -776,6 +834,10 @@ export class Agent {const trimmed = msg.content.trim();+ // "approve K7Q2M": the owner answering a security question (a new device,+ // a remote sensitive action) from their messaging channel.+ if (this.answerOwnerApproval(msg)) return;+// Onboarding from a chat without a bot thread (Telegram, web, Discord):// the next plain message in THAT chat is the new bot's persona — same// state machine as the TUI, same choices, just addressed to the chatdiff --git a/src/index.ts b/src/index.tsindex 2296a617..89539425 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,5 +1,5 @@import { readFileSync, writeFileSync, existsSync, statSync, chmodSync } from 'node:fs';-import { createHash } from 'node:crypto';+import { createHash, randomBytes } from 'node:crypto';import { fileURLToPath } from 'node:url';import { dirname, join, resolve as pathResolve } from 'node:path';import { Command } from 'commander';@@ -2175,14 +2175,24 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {console.log(chalk.dim(' Password unchanged.'));}} else {- console.log(chalk.dim(' Default password is Mercury@123 — set a custom one now or press Enter to keep it.'));+ console.log(chalk.dim(' This password signs in the dashboard and new devices (Mercury Desktop, phones).'));+ console.log(chalk.dim(' Press Enter to have Mercury make a strong one for you.'));console.log('');- const webPassword = await ask(chalk.white(' Web dashboard password [Mercury@123]: '));- if (webPassword.trim()) {- setWebPassword(webPassword.trim());+ let chosen = '';+ for (let attempt = 0; attempt < 3 && !chosen; attempt++) {+ const typed = (await ask(chalk.white(' Web dashboard password [generate one]: '))).trim();+ if (!typed) break;+ if (typed.length < 10) { console.log(chalk.yellow(' Use at least 10 characters (or press Enter to generate one).')); continue; }+ chosen = typed;+ }+ if (chosen) {+ setWebPassword(chosen);console.log(chalk.green(' ✓ Web dashboard password set.'));} else {- console.log(chalk.dim(' Using default password: Mercury@123'));+ const { initWebAuth: makeAuth, isWebAuthInitialized } = await import('./web/auth.js');+ const generated = !isWebAuthInitialized() ? makeAuth().password : (() => { const p = randomBytes(12).toString('base64url'); setWebPassword(p); return p; })();+ console.log(chalk.green(` ✓ Username: mercury Password: ${chalk.bold(generated)}`));+ console.log(chalk.dim(' Save it in your password manager — it is shown only now. Change it any time with /server.'));}}} else {@@ -2995,7 +3005,13 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {cloudClient.on('skill.install', async (msg) => {const skillUrl = msg.payload?.skillUrl as string | undefined;if (skillUrl) {- logger.info({ skillUrl }, 'Cloud command: install skill');+ logger.info('Cloud command: install skill (asking the owner)');+ // A skill is instructions Mercury follows from then on: the owner decides, not the Cloud account.+ const { askOwner } = await import('./security/owner-approvals.js');+ if (!(await askOwner({ title: 'Install a skill sent by Mercury Cloud', who: 'Mercury Cloud', detail: skillUrl.slice(0, 300) }))) {+ cloudClient!.send({ type: 'skill.ack', agentId: config.cloud.agentId, payload: { success: false, error: 'The owner did not approve installing this skill.' }, timestamp: new Date().toISOString() });+ return;+ }try {await skillLoader.installFromUrl(skillUrl);cloudClient!.send({@@ -3298,6 +3314,15 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'Invalid permission mode request.' } });return;}+ if (action === 'allow-all') {+ // Acting without asking, switched on from Cloud: the owner confirms it first.+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'notice', data: { message: 'Waiting for the owner to approve Allow All on their own device…' } });+ const { askOwner } = await import('./security/owner-approvals.js');+ if (!(await askOwner({ title: 'Turn on Allow All for a chat, from Mercury Cloud', who: 'Mercury Cloud' }))) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'The owner did not approve Allow All.' } });+ return;+ }+ }webChannel.setSessionPermissionMode(suppliedSessionId, action);cloudClient!.sendStream({conversationId,diff --git a/src/plugins/lifecycle.test.ts b/src/plugins/lifecycle.test.tsindex a1e79e76..362345aa 100644--- a/src/plugins/lifecycle.test.ts+++ b/src/plugins/lifecycle.test.ts@@ -121,8 +121,10 @@ describe('web API', () => {it('only accepts changes from this machine', async () => {const dir = inProcessPlugin(src, { id: 'web-test' });+ // From another device it waits for the owner's approval.const denied = await pluginRoutes.request('/api/plugins/install', post({ source: dir }), lan);- expect(denied.status).toBe(403);+ expect(denied.status).toBe(428);+ expect(((await denied.json()) as { approvalRequired: boolean }).approvalRequired).toBe(true);expect(readState().plugins['web-test']).toBeUndefined();const ok = await pluginRoutes.request('/api/plugins/install', post({ source: dir }), loopback);@@ -133,8 +135,8 @@ describe('web API', () => {expect(list.status).toBe(200);expect(((await list.json()) as { items: Array<{ id: string }> }).items.map((i: { id: string }) => i.id)).toContain('web-test');- expect((await pluginRoutes.request('/api/plugins/web-test/disable', post({}), lan)).status).toBe(403);- expect((await pluginRoutes.request('/api/plugins/web-test', { method: 'DELETE' }, lan)).status).toBe(403);+ expect((await pluginRoutes.request('/api/plugins/web-test/disable', post({}), lan)).status).toBe(428);+ expect((await pluginRoutes.request('/api/plugins/web-test', { method: 'DELETE' }, lan)).status).toBe(428);expect((await pluginRoutes.request('/api/plugins/web-test', { method: 'DELETE' }, loopback)).status).toBe(200);expect(readState().plugins['web-test']).toBeUndefined();});diff --git a/src/security/approval-messages.ts b/src/security/approval-messages.tsnew file mode 100644index 00000000..22dd1836--- /dev/null+++ b/src/security/approval-messages.ts@@ -0,0 +1,41 @@+import type { ChannelMessage } from '../types/channel.js';+import type { OwnerApproval } from './owner-approvals.js';++/**+ * How an owner approval reads on a messaging channel, and how a reply to it+ * is understood. A reply works only from the owner (an admin of that+ * channel), only with the code, and only once.+ */++const REPLY = /^\s*(approve|allow|yes|ok|deny|reject|no)\s+([A-Za-z2-9]{5})\s*[.!]?\s*$/i;++export function parseApprovalReply(text: string): { decision: 'allow' | 'deny'; code: string } | null {+ const m = REPLY.exec(text);+ if (!m) return null;+ const word = m[1].toLowerCase();+ return { decision: ['approve', 'allow', 'yes', 'ok'].includes(word) ? 'allow' : 'deny', code: m[2].toUpperCase() };+}++/** The sender is the owner on their channel: an admin (Telegram, Signal, WhatsApp roles; Discord/Slack admin flag). */+export function isOwnerSender(msg: ChannelMessage): boolean {+ if (msg.senderRole === 'admin') return true;+ return (msg.metadata as { isAdmin?: unknown } | undefined)?.isAdmin === true;+}++const minutes = (ms: number): string => `${Math.max(1, Math.round(ms / 60_000))} min`;++export function approvalRequestText(a: OwnerApproval, now = Date.now()): string {+ const head = a.kind === 'pair'+ ? `🔐 Mercury: a new device wants to connect: “${a.who}”${a.detail ? ` (${a.detail})` : ''}.`+ : `🔐 Mercury: “${a.who}” wants to: ${a.title}${a.detail ? `\n ${a.detail}` : ''}${a.ip ? `\n (from ${a.ip})` : ''}`;+ return `${head}\nReply “approve ${a.code}” to allow it, or “deny ${a.code}”. It expires in ${minutes(a.expiresAt - now)}.${a.kind === 'pair' ? ' If you didn’t just sign in somewhere, deny it.' : ''}`;+}++export function approvalAnsweredText(a: OwnerApproval): string {+ const what = a.kind === 'pair' ? `the device “${a.who}”` : `“${a.title}” for ${a.who}`;+ return a.status === 'allowed' ? `✓ Approved ${what}.` : `✗ Denied ${what}.`;+}++export function newLocationText(name: string, ip: string): string {+ return `🔐 Mercury: your device “${name}” connected from a new address (${ip}). If that wasn’t you, revoke it with /server on the computer Mercury runs on.`;+}diff --git a/src/security/audit.ts b/src/security/audit.tsnew file mode 100644index 00000000..f860d766--- /dev/null+++ b/src/security/audit.ts@@ -0,0 +1,55 @@+import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * The security log: who paired, who was approved, denied, revoked or+ * expired, remote sensitive actions and their answers, remote-access+ * changes. `~/.mercury/security/audit.jsonl`, owner-only, kept to ~1 MB+ * (the previous file is kept once as audit.1.jsonl).+ */++export type AuditKind =+ | 'pair.requested' | 'pair.approved' | 'pair.denied' | 'pair.expired' | 'pair.local'+ | 'device.revoked' | 'device.expired' | 'device.new-location' | 'device.blocked'+ | 'action.requested' | 'action.allowed' | 'action.denied'+ | 'remote.changed' | 'login.failed' | 'login.locked' | 'password.changed';++export interface AuditEntry {+ at: string;+ kind: AuditKind;+ /** Who it was about: a device name/id, "browser", "cloud". */+ who?: string;+ ip?: string;+ detail?: string;+ /** Who decided: "cli", "desktop", "telegram", "timeout"… */+ by?: string;+}++const MAX_BYTES = 1_000_000;++export function auditPath(): string {+ return join(getMercuryHome(), 'security', 'audit.jsonl');+}++export function audit(kind: AuditKind, fields: Omit<AuditEntry, 'at' | 'kind'> = {}): void {+ try {+ const path = auditPath();+ const dir = join(getMercuryHome(), 'security');+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });+ if (existsSync(path) && statSync(path).size > MAX_BYTES) renameSync(path, join(dir, 'audit.1.jsonl'));+ const entry: AuditEntry = { at: new Date().toISOString(), kind, ...fields };+ appendFileSync(path, `${JSON.stringify(entry)}\n`, { encoding: 'utf-8', mode: 0o600 });+ try { chmodSync(path, 0o600); } catch { /* best effort */ }+ } catch { /* the log must never break a request */ }+}++/** The newest entries first. */+export function readAudit(limit = 50): AuditEntry[] {+ try {+ const lines = readFileSync(auditPath(), 'utf-8').trim().split('\n').filter(Boolean);+ return lines.slice(-limit).reverse().map((l) => JSON.parse(l) as AuditEntry);+ } catch {+ return [];+ }+}diff --git a/src/security/check.ts b/src/security/check.tsnew file mode 100644index 00000000..2c45fb1b--- /dev/null+++ b/src/security/check.ts@@ -0,0 +1,86 @@+import { existsSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { compareSync } from 'bcryptjs';+import { getMercuryHome } from '../utils/config.js';+import { loadPermissionMode } from '../capabilities/permission-mode-store.js';+import { listDevices } from '../web/devices.js';+import { loadWebAuth } from '../web/auth.js';+import { readRemoteSettings } from './remote-settings.js';++/**+ * The security check (`mercury doctor --security`, /server → Security check,+ * Mercury Desktop): what a careful person would look at before letting other+ * devices reach this Mercury, each with what to do about it.+ */++export interface SecurityFinding {+ level: 'ok' | 'info' | 'warn' | 'risk';+ title: string;+ detail?: string;+ fix?: string;+}++const KNOWN_WEAK = ['Mercury@123', 'mercury', 'password', 'admin', '123456', '12345678', 'changeme'];+const CREDENTIAL_FILES = ['devices.json', 'web-config.json', 'web-sessions.json', 'attach-token', 'remote.json', 'mercury.yaml', '.env'];++export interface CheckContext {+ /** The last request from outside this computer, if any (middleware.lastRemoteRequest). */+ lastRemote?: { at: number; proxied: boolean; clientIpKnown: boolean } | null;+ cloudConnected?: boolean;+ now?: number;+}++export function securityCheck(ctx: CheckContext = {}): SecurityFinding[] {+ const out: SecurityFinding[] = [];+ const now = ctx.now ?? Date.now();+ const remote = readRemoteSettings();+ const devices = listDevices();++ // Password+ const auth = loadWebAuth();+ if (!auth) {+ out.push({ level: 'info', title: 'No sign-in password yet', detail: 'Nobody can sign in from another device until one is set.', fix: 'mercury web-reset-password' });+ } else {+ const weak = KNOWN_WEAK.find((p) => { try { return compareSync(p, auth.password_hash); } catch { return false; } });+ if (weak) out.push({ level: 'risk', title: 'The sign-in password is a well-known one', detail: `It is “${weak}”, which anyone can guess.`, fix: 'Change it: /server → Password, or mercury web-reset-password' });+ else out.push({ level: 'ok', title: 'The sign-in password is not a well-known one' });+ }++ // Remote access+ if (!remote.enabled) {+ out.push({ level: 'ok', title: 'Remote access is off', detail: 'Only this computer can use Mercury.' });+ } else {+ out.push({ level: 'info', title: `Remote access is on · ${devices.length} device${devices.length === 1 ? '' : 's'}`, detail: remote.allowIps.length ? `Only from: ${remote.allowIps.join(', ')}` : 'From any address (with an approved device or the password).', fix: devices.length ? undefined : 'Turn it off with /server if you never connect from elsewhere.' });+ const stale = devices.filter((d) => now - Date.parse(d.lastSeenAt ?? d.createdAt) > 30 * 86_400_000);+ if (stale.length) out.push({ level: 'warn', title: `${stale.length} device${stale.length === 1 ? '' : 's'} not used in 30 days`, detail: stale.map((d) => d.name).join(', '), fix: 'Revoke the ones you no longer use: /server → Devices' });+ if (remote.idleDays === 0 && devices.length) out.push({ level: 'warn', title: 'Unused devices never expire', fix: 'Set an idle limit: /server → Devices' });+ if (remote.allowShell) out.push({ level: 'warn', title: 'Remote devices may use the terminal', detail: 'Each command still needs your approval.', fix: 'Turn it off unless you need it: /server' });+ if (loadPermissionMode() === 'allow-all' && devices.length) {+ out.push({ level: 'warn', title: 'Allow All is on while devices can connect', detail: 'Mercury acts without asking, also for a paired device. That device is trusted like you; make sure each one is yours.', fix: 'Review /server → Devices, or switch to Ask Me' });+ }+ const lr = ctx.lastRemote;+ if (lr && remote.allowIps.length && !lr.clientIpKnown) {+ out.push({ level: 'risk', title: "The address allow-list can't work with this tunnel", detail: "The last remote request didn't say which address it came from, so every remote client is refused while the list is set.", fix: 'Use a tunnel that passes the client address (Tailscale Serve, Cloudflare Tunnel), or clear the list' });+ }+ }++ // Credential files+ const home = getMercuryHome();+ if (process.platform !== 'win32') {+ const open = CREDENTIAL_FILES.filter((f) => {+ const p = join(home, f);+ try { return existsSync(p) && (statSync(p).mode & 0o077) !== 0; } catch { return false; }+ });+ if (open.length) out.push({ level: 'risk', title: 'Some credential files can be read by other users', detail: open.join(', '), fix: `chmod 600 ${open.map((f) => `~/.mercury/${f}`).join(' ')}` });+ else out.push({ level: 'ok', title: 'Credential files are private to you' });+ }++ if (ctx.cloudConnected) out.push({ level: 'info', title: 'Mercury Cloud is connected', detail: 'Allow All and skill installs from Cloud ask you first.' });+ return out;+}++export function summarizeFindings(f: SecurityFinding[]): string {+ const risks = f.filter((x) => x.level === 'risk').length;+ const warns = f.filter((x) => x.level === 'warn').length;+ return risks ? `${risks} risk${risks === 1 ? '' : 's'}${warns ? `, ${warns} to review` : ''}` : warns ? `${warns} to review` : 'All good';+}diff --git a/src/security/ip-match.ts b/src/security/ip-match.tsnew file mode 100644index 00000000..37cc1195--- /dev/null+++ b/src/security/ip-match.ts@@ -0,0 +1,83 @@+import { isIP } from 'node:net';++/**+ * Allowed-address rules: an address ("203.0.113.7", "2001:db8::1") or a+ * range ("203.0.113.0/24", "100.64.0.0/10" for a tailnet, "2001:db8::/32").+ */++function v4(ip: string): bigint | null {+ const parts = ip.split('.');+ if (parts.length !== 4) return null;+ let n = 0n;+ for (const p of parts) {+ if (!/^\d{1,3}$/.test(p) || Number(p) > 255) return null;+ n = (n << 8n) | BigInt(Number(p));+ }+ return n;+}++function v6(ip: string): bigint | null {+ let s = ip.toLowerCase();+ // An IPv4-mapped tail ("::ffff:1.2.3.4").+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);+ if (tail) {+ const n4 = v4(tail[1]);+ if (n4 === null) return null;+ s = `${s.slice(0, -tail[1].length)}${(n4 >> 16n).toString(16)}:${(n4 & 0xffffn).toString(16)}`;+ }+ const halves = s.split('::');+ if (halves.length > 2) return null;+ const head = halves[0] ? halves[0].split(':') : [];+ const rest = halves.length === 2 && halves[1] ? halves[1].split(':') : [];+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;+ if (fill < 0) return null;+ const groups = [...head, ...Array(fill).fill('0'), ...rest];+ if (groups.length !== 8) return null;+ let n = 0n;+ for (const g of groups) {+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;+ n = (n << 16n) | BigInt(parseInt(g, 16));+ }+ return n;+}++/** "::ffff:1.2.3.4" is 1.2.3.4. */+export function normalizeIp(ip: string): string {+ const m = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip.trim());+ return m ? m[1] : ip.trim().replace(/^\[|\]$/g, '');+}++/** A valid rule, normalized, or null. */+export function parseIpRule(rule: string): string | null {+ const [addr, bits, extra] = rule.trim().split('/');+ if (extra !== undefined || !addr) return null;+ const ip = normalizeIp(addr);+ const family = isIP(ip);+ if (!family) return null;+ if (bits === undefined) return ip;+ if (!/^\d{1,3}$/.test(bits)) return null;+ const n = Number(bits);+ if (n > (family === 4 ? 32 : 128)) return null;+ return `${ip}/${n}`;+}++export function ipMatches(ipRaw: string, rule: string): boolean {+ const ip = normalizeIp(ipRaw);+ const parsed = parseIpRule(rule);+ if (!parsed) return false;+ const [base, bitsStr] = parsed.split('/');+ const family = isIP(ip);+ if (!family || family !== isIP(base)) return false;+ const a = family === 4 ? v4(ip) : v6(ip);+ const b = family === 4 ? v4(base) : v6(base);+ if (a === null || b === null) return false;+ const width = family === 4 ? 32 : 128;+ const bits = bitsStr === undefined ? width : Number(bitsStr);+ if (bits === 0) return true;+ const shift = BigInt(width - bits);+ return (a >> shift) === (b >> shift);+}++export function ipAllowed(ip: string, rules: readonly string[]): boolean {+ return rules.some((r) => ipMatches(ip, r));+}diff --git a/src/security/live-streams.ts b/src/security/live-streams.tsnew file mode 100644index 00000000..8905e276--- /dev/null+++ b/src/security/live-streams.ts@@ -0,0 +1,36 @@+/**+ * Open event streams, by who opened them, so revoking a device (or signing+ * a browser out) cuts its live connection at once instead of leaving it+ * streaming until it disconnects by itself.+ */++type Close = () => void;+const streams = new Map<string, Set<Close>>();++/** `principal` is "device:<id>" or "session:<key>". Returns the unregister function. */+export function trackStream(principal: string | null, close: Close): () => void {+ if (!principal) return () => {};+ const set = streams.get(principal) ?? new Set<Close>();+ set.add(close);+ streams.set(principal, set);+ return () => {+ set.delete(close);+ if (!set.size) streams.delete(principal);+ };+}++/** Close every stream a principal holds; how many were closed. */+export function closeStreams(principal: string): number {+ const set = streams.get(principal);+ if (!set) return 0;+ streams.delete(principal);+ let n = 0;+ for (const close of set) { try { close(); n++; } catch { /* already closed */ } }+ return n;+}++export function closeStreamsWhere(match: (principal: string) => boolean): number {+ let n = 0;+ for (const key of [...streams.keys()]) if (match(key)) n += closeStreams(key);+ return n;+}diff --git a/src/security/owner-approvals.ts b/src/security/owner-approvals.tsnew file mode 100644index 00000000..c5c62569--- /dev/null+++ b/src/security/owner-approvals.ts@@ -0,0 +1,160 @@+import { randomBytes, randomInt } from 'node:crypto';++/**+ * Asking the owner. A new device wants to pair, or a remote device wants to+ * do something that could outlive its access (a shell, Allow All, a new+ * channel admin, Cloud sign-in…). The question goes to every place the+ * owner is (their connected messaging channel, this computer's CLI and+ * Mercury Desktop), carries a short code, and is answered once, by the owner:+ * never by the device that asked. Nobody answering in time is a "no".+ */++export type ApprovalKind = 'pair' | 'action';+export type ApprovalStatus = 'pending' | 'allowed' | 'denied' | 'expired';++export interface OwnerApproval {+ id: string;+ /** Short code the owner can type ("approve K7Q2M") — no 0/O/1/I. */+ code: string;+ kind: ApprovalKind;+ /** "New device: Salman's iPhone", "Run a shell command". */+ title: string;+ detail?: string;+ /** The device (or "browser", "cloud") asking. */+ who: string;+ ip?: string;+ at: number;+ expiresAt: number;+ status: ApprovalStatus;+ decidedBy?: string;+ /** For actions: what the grant is good for (one use). */+ scope?: { principal: string; action: string };+ consumed?: boolean;+}++type Listener = (a: OwnerApproval, change: 'new' | 'decided') => void;++const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';+const KEEP_DECIDED_MS = 15 * 60_000;++export class OwnerApprovals {+ private items = new Map<string, OwnerApproval>();+ private waiters = new Map<string, Array<(s: ApprovalStatus) => void>>();+ private listeners = new Set<Listener>();++ constructor(private readonly now: () => number = Date.now) {}++ onChange(l: Listener): () => void {+ this.listeners.add(l);+ return () => { this.listeners.delete(l); };+ }++ private emit(a: OwnerApproval, change: 'new' | 'decided'): void {+ for (const l of this.listeners) { try { l({ ...a }, change); } catch { /* a listener's problem */ } }+ }++ private newCode(): string {+ const taken = new Set([...this.items.values()].filter((a) => a.status === 'pending').map((a) => a.code));+ for (;;) {+ const code = Array.from({ length: 5 }, () => ALPHABET[randomInt(ALPHABET.length)]).join('');+ if (!taken.has(code)) return code;+ }+ }++ request(input: Pick<OwnerApproval, 'kind' | 'title' | 'who'> & Partial<Pick<OwnerApproval, 'detail' | 'ip' | 'scope'>>, ttlMs: number): OwnerApproval {+ this.sweep();+ const at = this.now();+ const a: OwnerApproval = { ...input, id: randomBytes(9).toString('base64url'), code: this.newCode(), at, expiresAt: at + ttlMs, status: 'pending' };+ this.items.set(a.id, a);+ const timer = setTimeout(() => this.expire(a.id), ttlMs);+ timer.unref?.();+ this.emit(a, 'new');+ return { ...a };+ }++ private expire(id: string): void {+ const a = this.items.get(id);+ if (!a || a.status !== 'pending') return;+ a.status = 'expired';+ a.decidedBy = 'timeout';+ this.settle(a);+ }++ private settle(a: OwnerApproval): void {+ for (const w of this.waiters.get(a.id) ?? []) w(a.status);+ this.waiters.delete(a.id);+ this.emit(a, 'decided');+ }++ /** By id or by its code (case-insensitive). Null when there's no such pending question. */+ find(idOrCode: string): OwnerApproval | null {+ const key = idOrCode.trim();+ const a = this.items.get(key) ?? [...this.items.values()].find((x) => x.status === 'pending' && x.code === key.toUpperCase());+ return a ? { ...a } : null;+ }++ decide(idOrCode: string, decision: 'allow' | 'deny', by: string): OwnerApproval | null {+ const found = this.find(idOrCode);+ const a = found ? this.items.get(found.id) : undefined;+ if (!a || a.status !== 'pending') return null;+ if (this.now() > a.expiresAt) { this.expire(a.id); return null; }+ a.status = decision === 'allow' ? 'allowed' : 'denied';+ a.decidedBy = by;+ this.settle(a);+ return { ...a };+ }++ /** Resolves when it's decided (or expires). */+ wait(id: string): Promise<ApprovalStatus> {+ const a = this.items.get(id);+ if (!a) return Promise.resolve('expired');+ if (a.status !== 'pending') return Promise.resolve(a.status);+ return new Promise((resolve) => this.waiters.set(id, [...(this.waiters.get(id) ?? []), resolve]));+ }++ /** An allowed action approval, used once, by the principal and for the action it was asked for. */+ consume(id: string, scope: { principal: string; action: string }): boolean {+ const a = this.items.get(id);+ if (!a || a.kind !== 'action' || a.status !== 'allowed' || a.consumed) return false;+ if (!a.scope || a.scope.principal !== scope.principal || a.scope.action !== scope.action) return false;+ if (this.now() > a.expiresAt + KEEP_DECIDED_MS) return false;+ a.consumed = true;+ return true;+ }++ pending(): OwnerApproval[] {+ this.sweep();+ return [...this.items.values()].filter((a) => a.status === 'pending').sort((x, y) => x.at - y.at).map((a) => ({ ...a }));+ }++ get(id: string): OwnerApproval | null {+ const a = this.items.get(id);+ return a ? { ...a } : null;+ }++ private sweep(): void {+ const t = this.now();+ for (const [id, a] of this.items) if (a.status !== 'pending' && t - a.expiresAt > KEEP_DECIDED_MS) this.items.delete(id);+ }+}++/**+ * Ask and wait (for callers that can wait: Mercury Cloud's commands). True+ * only when the owner allowed it in time.+ */+export async function askOwner(input: { title: string; who: string; detail?: string }, ttlMs = 10 * 60_000): Promise<boolean> {+ const approvals = ownerApprovals();+ const a = approvals.request({ kind: 'action', ...input, scope: { principal: input.who, action: input.title } }, ttlMs);+ return (await approvals.wait(a.id)) === 'allowed';+}++let shared: OwnerApprovals | null = null;+export function ownerApprovals(): OwnerApprovals {+ shared ??= new OwnerApprovals();+ return shared;+}++/** Test hook. */+export function _setOwnerApprovals(a: OwnerApprovals | null): void {+ shared = a;+}diff --git a/src/security/protected-paths.ts b/src/security/protected-paths.tsnew file mode 100644index 00000000..7d77bc6e--- /dev/null+++ b/src/security/protected-paths.ts@@ -0,0 +1,76 @@+import { existsSync, realpathSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * Files no API caller reads or writes through Mercury's file endpoints.+ *+ * - Mercury's own credentials (device tokens, the password hash, browser+ * sessions, the attach token, remote-access settings, the security log,+ * provider keys): writing one would let a caller plant a token that+ * survives being revoked; reading one hands out secrets. Always refused.+ * - The owner's keys and shell start-up files (~/.ssh, ~/.gnupg, cloud+ * credentials, .zshrc…): refused to remote devices.+ */++const MERCURY_SECRETS = ['devices.json', 'web-config.json', 'web-sessions.json', 'attach-token', 'remote.json', 'security', 'mercury.yaml', '.env', 'keys', 'github-session.json', 'chatgpt-session.json'];+const HOME_SECRETS = ['.ssh', '.gnupg', '.aws', '.azure', '.config/gcloud', '.kube', '.docker/config.json', '.netrc', '.npmrc', '.pypirc', '.git-credentials', '.zshrc', '.bashrc', '.bash_profile', '.profile', '.zprofile', '.config/fish', 'Library/Keychains'];++/** The real path, following symlinks; for a file that doesn't exist yet, its nearest existing parent's. */+export function realPathOf(p: string): string {+ let cur = resolve(p);+ const tail: string[] = [];+ for (let i = 0; i < 64; i++) {+ if (existsSync(cur)) {+ try { return join(realpathSync(cur), ...tail.reverse()); } catch { return resolve(p); }+ }+ const parent = dirname(cur);+ if (parent === cur) break;+ tail.push(cur.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));+ cur = parent;+ }+ return resolve(p);+}++const within = (child: string, parent: string): boolean => {+ const rel = relative(parent, child);+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));+};++/** Inside `root` after following symlinks (a link inside the workspace pointing at ~/.ssh is not inside it). */+export function realInside(path: string, root: string): boolean {+ return within(realPathOf(path), realPathOf(root));+}++/** Why this path is off limits, or null. `remote` adds the owner's keys and start-up files. */+export function protectedReason(path: string, remote: boolean): string | null {+ const real = realPathOf(path);+ const home = realPathOf(homedir());+ const mercury = realPathOf(getMercuryHome());+ for (const name of MERCURY_SECRETS) {+ if (within(real, join(mercury, name))) return "Mercury's credentials can't be read or changed this way.";+ }+ if (remote) {+ for (const name of HOME_SECRETS) {+ if (within(real, join(home, name))) return 'Keys and shell start-up files can only be opened on the computer itself.';+ }+ }+ return null;+}++/** Mercury's login credentials: never touched by its own tools (a prompt-injected agent can't read or plant a token). */+const AGENT_DENIED = ['devices.json', 'web-config.json', 'web-sessions.json', 'attach-token', 'remote.json', 'security'];++export function isMercuryCredentialPath(path: string): boolean {+ const real = realPathOf(path);+ const mercury = realPathOf(getMercuryHome());+ return AGENT_DENIED.some((name) => within(real, join(mercury, name)) || within(resolve(path), join(resolve(getMercuryHome()), name)));+}++/** A shell command that names one of those files. */+export function commandTouchesMercuryCredentials(command: string): boolean {+ const home = getMercuryHome();+ const mentionsHome = command.includes('.mercury') || command.includes(home) || /\$MERCURY_HOME|\$\{MERCURY_HOME\}/.test(command);+ return mentionsHome && AGENT_DENIED.some((name) => command.includes(name));+}diff --git a/src/security/remote-security.test.ts b/src/security/remote-security.test.tsnew file mode 100644index 00000000..69003fa3--- /dev/null+++ b/src/security/remote-security.test.ts@@ -0,0 +1,251 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Hono } from 'hono';+import { ipAllowed, ipMatches, parseIpRule } from './ip-match.js';+import { OwnerApprovals, _setOwnerApprovals, ownerApprovals } from './owner-approvals.js';+import { closeStreams, trackStream } from './live-streams.js';+import { readRemoteSettings, writeRemoteSettings } from './remote-settings.js';+import { parseApprovalReply, isOwnerSender } from './approval-messages.js';+import { commandTouchesMercuryCredentials, isMercuryCredentialPath, protectedReason, realInside } from './protected-paths.js';++const LOCAL = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };+const LAN = { incoming: { socket: { remoteAddress: '192.168.1.20' } } };++let home: string;+const previous = process.env.MERCURY_HOME;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-sec-'));+ process.env.MERCURY_HOME = home;+ _setOwnerApprovals(new OwnerApprovals());+});+afterEach(() => {+ if (previous === undefined) delete process.env.MERCURY_HOME; else process.env.MERCURY_HOME = previous;+ rmSync(home, { recursive: true, force: true });+});++async function app() {+ const { authGuard } = await import('../web/middleware.js');+ const { requireOwner } = await import('../web/owner-gate.js');+ const { default: security } = await import('../web/api/security.js');+ const a = new Hono();+ a.use('*', authGuard);+ a.route('/', security);+ a.get('/api/ping', (c) => c.json({ ok: true }));+ a.post('/api/danger', (c) => requireOwner(c, { id: 'test.danger', title: 'Do the dangerous thing' }) ?? c.json({ done: true }));+ return a;+}++async function device(name = 'Phone') {+ const { createDevice, _resetDeviceState } = await import('../web/devices.js');+ _resetDeviceState();+ return createDevice(name, 'ios');+}++const bearer = (token: string, extra: Record<string, string> = {}) => ({ headers: { Authorization: `Bearer ${token}`, ...extra } });++describe('where a request comes from', () => {+ it('a tunnel on this machine is remote, whatever the socket says', async () => {+ const a = await app();+ const { token } = await device();+ const { writeAttachToken, readAttachToken } = await import('../web/auth.js');+ writeAttachToken();+ const attach = readAttachToken()!;+ // Straight from this machine with the attach token: this computer.+ expect((await a.request('http://127.0.0.1:6174/api/security/status', bearer(attach), LOCAL)).status).toBe(200);+ // The same token through a tunnel (Tailscale Serve, cloudflared add these headers): not honoured.+ const tunneled = await a.request('http://127.0.0.1:6174/api/security/status', bearer(attach, { 'X-Forwarded-For': '203.0.113.9', Host: 'mercury.tail1234.ts.net' }), LOCAL);+ expect(tunneled.status).toBe(401);+ // A device through the tunnel is a remote device: the owner's settings are off limits.+ const remote = await a.request('http://127.0.0.1:6174/api/security/status', bearer(token, { 'X-Forwarded-For': '203.0.113.9' }), LOCAL);+ expect(remote.status).toBe(403);+ expect(((await remote.json()) as { thisComputerOnly: boolean }).thisComputerOnly).toBe(true);+ });++ it('refuses a page that reached this machine under another name (DNS rebinding)', async () => {+ const a = await app();+ const res = await a.request('http://evil.example:6174/api/ping', { headers: { Host: 'evil.example:6174' } }, LOCAL);+ expect(res.status).toBe(421);+ });+});++describe('remote access switch and allow-list', () => {+ it('turning remote access off shuts out devices, never this computer', async () => {+ const a = await app();+ const { token } = await device();+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token), LAN)).status).toBe(200);+ writeRemoteSettings({ enabled: false });+ const off = await a.request('http://127.0.0.1/api/ping', bearer(token), LAN);+ expect(off.status).toBe(403);+ expect(((await off.json()) as { remoteOff: boolean }).remoteOff).toBe(true);+ // Sign-in from outside is closed too.+ expect((await a.request('http://127.0.0.1/api/auth/token', { method: 'POST' }, LAN)).status).toBe(403);+ const { writeAttachToken, readAttachToken } = await import('../web/auth.js');+ writeAttachToken();+ expect((await a.request('http://127.0.0.1/api/ping', bearer(readAttachToken()!), LOCAL)).status).toBe(200);+ });++ it('lets in only listed addresses, and fails closed when the tunnel hides the address', async () => {+ const a = await app();+ const { token } = await device();+ writeRemoteSettings({ allowIps: ['100.64.0.0/10'] });+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token, { 'X-Forwarded-For': '100.101.2.3' }), LOCAL)).status).toBe(200);+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token, { 'X-Forwarded-For': '203.0.113.9' }), LOCAL)).status).toBe(403);+ // Only the right-most X-Forwarded-For entry (the one this machine's proxy added) counts.+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token, { 'X-Forwarded-For': '100.101.2.3, 203.0.113.9' }), LOCAL)).status).toBe(403);+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token, { 'Tailscale-User-Login': '[email protected]' }), LOCAL)).status).toBe(403);+ });++ it('keeps settings sane whatever is in the file', () => {+ writeFileSync(join(home, 'remote.json'), JSON.stringify({ enabled: 'yes', allowIps: ['1.2.3.4', 'nonsense', '10.0.0.0/8'], maxDevices: 9999, idleDays: -5 }));+ expect(readRemoteSettings()).toEqual({ enabled: true, allowIps: ['1.2.3.4', '10.0.0.0/8'], allowShell: false, maxDevices: 200, idleDays: 0 });+ writeFileSync(join(home, 'remote.json'), '{ broken');+ expect(readRemoteSettings().enabled).toBe(true);+ });+});++describe('the owner approves sensitive actions from other devices', () => {+ it('428 with a code, then works once with the approval, for that device only', async () => {+ const a = await app();+ const phone = await device('Phone');+ const laptop = await device('Laptop');+ const first = await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token) }, LAN);+ expect(first.status).toBe(428);+ const ask = (await first.json()) as { approvalId: string; code: string };+ // The asking device can't answer its own question.+ const self = await a.request(`http://127.0.0.1/api/security/approvals/${ask.approvalId}`, { method: 'POST', ...bearer(phone.token), body: JSON.stringify({ decision: 'allow' }) }, LAN);+ expect(self.status).toBe(403);+ // It can see how its question stands.+ const st = await a.request(`http://127.0.0.1/api/security/approvals/${ask.approvalId}/status`, bearer(phone.token), LAN);+ expect(((await st.json()) as { status: string }).status).toBe('pending');+ // Another device can't use it.+ expect((await a.request(`http://127.0.0.1/api/security/approvals/${ask.approvalId}/status`, bearer(laptop.token), LAN)).status).toBe(404);+ ownerApprovals().decide(ask.code, 'allow', 'telegram');+ expect((await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(laptop.token, { 'X-Mercury-Approval': ask.approvalId }) }, LAN)).status).toBe(428);+ const ok = await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token, { 'X-Mercury-Approval': ask.approvalId }) }, LAN);+ expect(ok.status).toBe(200);+ // Once.+ expect((await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token, { 'X-Mercury-Approval': ask.approvalId }) }, LAN)).status).toBe(428);+ });++ it('a denial is a 403 that says so; on this computer nothing is asked', async () => {+ const a = await app();+ const phone = await device();+ const ask = (await (await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token) }, LAN)).json()) as { approvalId: string; code: string };+ ownerApprovals().decide(ask.approvalId, 'deny', 'cli');+ const denied = await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token, { 'X-Mercury-Approval': ask.approvalId }) }, LAN);+ expect(denied.status).toBe(403);+ const { writeAttachToken, readAttachToken } = await import('../web/auth.js');+ writeAttachToken();+ expect((await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(readAttachToken()!) }, LOCAL)).status).toBe(200);+ });++ it('questions expire as "no"', async () => {+ let now = 1_000;+ const ap = new OwnerApprovals(() => now);+ const q = ap.request({ kind: 'pair', title: 'New device', who: 'Phone' }, 60_000);+ now += 61_000;+ expect(ap.decide(q.code, 'allow', 'cli')).toBeNull();+ });+});++describe('device tokens', () => {+ it('an unused device expires (and says so); devices from before the upgrade keep working', async () => {+ const a = await app();+ const { token, device: d } = await device();+ writeRemoteSettings({ idleDays: 30 });+ const file = join(home, 'devices.json');+ const data = JSON.parse((await import('node:fs')).readFileSync(file, 'utf-8'));+ const long = new Date(Date.now() - 40 * 86_400_000).toISOString();+ data.devices[0] = { ...data.devices[0], createdAt: long, lastSeenAt: long, idleSince: undefined };+ writeFileSync(file, JSON.stringify(data));+ const { migrateDevices } = await import('../web/devices.js');+ expect(migrateDevices()).toBe(1); // the old device's clock starts now+ expect((await a.request('http://127.0.0.1/api/ping', bearer(token), LAN)).status).toBe(200);+ // Forty days later, unused: expired.+ const again = JSON.parse((await import('node:fs')).readFileSync(file, 'utf-8'));+ again.devices[0] = { ...again.devices[0], lastSeenAt: long, idleSince: long };+ writeFileSync(file, JSON.stringify(again));+ const res = await a.request('http://127.0.0.1/api/ping', bearer(token), LAN);+ expect(res.status).toBe(401);+ expect(((await res.json()) as { expired: boolean }).expired).toBe(true);+ const { listDevices } = await import('../web/devices.js');+ expect(listDevices().find((x) => x.id === d.id)).toBeUndefined();+ });++ it('respects the device limit', async () => {+ writeRemoteSettings({ maxDevices: 1 });+ await device('One');+ await expect(device('Two')).rejects.toThrow(/limit is 1/);+ });++ it('revoking closes the live streams of that device only', () => {+ let a = 0; let b = 0;+ trackStream('device:aaaa0000', () => { a++; });+ trackStream('device:aaaa0000', () => { a++; });+ trackStream('device:bbbb0000', () => { b++; });+ expect(closeStreams('device:aaaa0000')).toBe(2);+ expect([a, b]).toEqual([2, 0]);+ expect(closeStreams('device:aaaa0000')).toBe(0);+ });+});++describe('files', () => {+ it("Mercury's credentials are never reachable; remote devices also can't reach keys", () => {+ expect(protectedReason(join(home, 'devices.json'), false)).toMatch(/credentials/);+ expect(protectedReason(join(home, 'security', 'audit.jsonl'), false)).toMatch(/credentials/);+ expect(protectedReason(join(home, 'notes.md'), false)).toBeNull();+ expect(protectedReason(join((process.env.HOME ?? '/'), '.ssh', 'id_ed25519'), true)).toMatch(/Keys/);+ expect(protectedReason(join((process.env.HOME ?? '/'), '.ssh', 'id_ed25519'), false)).toBeNull();+ });++ it("a symlink inside the workspace doesn't reach outside it", () => {+ const ws = join(home, 'ws');+ mkdirSync(ws);+ mkdirSync(join(home, 'outside'));+ writeFileSync(join(home, 'outside', 'secret.txt'), 'x');+ symlinkSync(join(home, 'outside'), join(ws, 'link'));+ expect(realInside(join(ws, 'link', 'secret.txt'), ws)).toBe(false);+ expect(realInside(join(ws, 'new-file.txt'), ws)).toBe(true);+ });++ it("Mercury's own tools can't read or name its login files", () => {+ expect(isMercuryCredentialPath(join(home, 'attach-token'))).toBe(true);+ expect(isMercuryCredentialPath(join(home, 'mercury.yaml'))).toBe(false);+ expect(commandTouchesMercuryCredentials(`cat ${home}/devices.json`)).toBe(true);+ expect(commandTouchesMercuryCredentials('cat ~/.mercury/web-sessions.json')).toBe(true);+ expect(commandTouchesMercuryCredentials('ls ~/.mercury/bots')).toBe(false);+ });+});++describe('answers from a messaging channel', () => {+ it('reads "approve CODE" / "deny CODE", from the owner only', () => {+ expect(parseApprovalReply('approve k7q2m')).toEqual({ decision: 'allow', code: 'K7Q2M' });+ expect(parseApprovalReply(' Deny K7Q2M. ')).toEqual({ decision: 'deny', code: 'K7Q2M' });+ expect(parseApprovalReply('approve the plan')).toBeNull();+ expect(parseApprovalReply('please approve K7Q2M now')).toBeNull();+ const base = { id: '1', channelId: 'telegram:1', channelType: 'telegram' as const, senderId: '1', content: '', timestamp: 0 };+ expect(isOwnerSender({ ...base, senderRole: 'admin' })).toBe(true);+ expect(isOwnerSender({ ...base, senderRole: 'member' })).toBe(false);+ expect(isOwnerSender({ ...base, metadata: { isAdmin: true } })).toBe(true);+ expect(isOwnerSender({ ...base })).toBe(false);+ });+});++describe('addresses', () => {+ it('matches single addresses and ranges, v4 and v6', () => {+ expect(parseIpRule('203.0.113.7')).toBe('203.0.113.7');+ expect(parseIpRule('::ffff:203.0.113.7')).toBe('203.0.113.7');+ expect(parseIpRule('10.0.0.0/33')).toBeNull();+ expect(parseIpRule('nope')).toBeNull();+ expect(ipMatches('100.101.2.3', '100.64.0.0/10')).toBe(true);+ expect(ipMatches('100.128.0.1', '100.64.0.0/10')).toBe(false);+ expect(ipMatches('2001:db8::1', '2001:db8::/32')).toBe(true);+ expect(ipMatches('2001:db9::1', '2001:db8::/32')).toBe(false);+ expect(ipMatches('::ffff:10.1.2.3', '10.0.0.0/8')).toBe(true);+ expect(ipAllowed('1.2.3.4', ['5.6.7.8', '1.2.3.4'])).toBe(true);+ expect(ipAllowed('1.2.3.4', [])).toBe(false);+ });+});diff --git a/src/security/remote-settings.ts b/src/security/remote-settings.tsnew file mode 100644index 00000000..8f5113ba--- /dev/null+++ b/src/security/remote-settings.ts@@ -0,0 +1,69 @@+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { parseIpRule } from './ip-match.js';++/**+ * The owner's remote-access settings (`/server`, `mercury server`), in+ * `~/.mercury/remote.json`. Read on every remote request (cached by mtime),+ * so a change from the CLI applies at once without a restart.+ */++export interface RemoteSettings {+ /** Remote clients (device tokens, sessions through a tunnel) may connect at all. */+ enabled: boolean;+ /** Client addresses allowed in; empty = any. Needs a proxy that passes the real address. */+ allowIps: string[];+ /** Remote devices may use the terminal (each run still needs the owner's approval). */+ allowShell: boolean;+ /** Most devices that can be paired. */+ maxDevices: number;+ /** A device unused this many days stops working until approved again. 0 = never. */+ idleDays: number;+}++export const DEFAULT_REMOTE: RemoteSettings = { enabled: true, allowIps: [], allowShell: false, maxDevices: 10, idleDays: 30 };++export function remoteSettingsPath(): string {+ return join(getMercuryHome(), 'remote.json');+}++let cache: { mtime: number; path: string; value: RemoteSettings } | null = null;++function normalize(raw: Partial<RemoteSettings>): RemoteSettings {+ const num = (v: unknown, d: number, lo: number, hi: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : d);+ return {+ enabled: typeof raw.enabled === 'boolean' ? raw.enabled : DEFAULT_REMOTE.enabled,+ allowIps: Array.isArray(raw.allowIps) ? [...new Set(raw.allowIps.map((r) => parseIpRule(String(r))).filter((r): r is string => !!r))].slice(0, 100) : [],+ allowShell: raw.allowShell === true,+ maxDevices: num(raw.maxDevices, DEFAULT_REMOTE.maxDevices, 1, 200),+ idleDays: num(raw.idleDays, DEFAULT_REMOTE.idleDays, 0, 3650),+ };+}++export function readRemoteSettings(): RemoteSettings {+ const path = remoteSettingsPath();+ try {+ if (!existsSync(path)) return { ...DEFAULT_REMOTE };+ const mtime = statSync(path).mtimeMs;+ if (cache && cache.path === path && cache.mtime === mtime) return cache.value;+ const value = normalize(JSON.parse(readFileSync(path, 'utf-8')) as Partial<RemoteSettings>);+ cache = { mtime, path, value };+ return value;+ } catch {+ // Unreadable settings: the safe defaults, not "everything allowed".+ return { ...DEFAULT_REMOTE };+ }+}++export function writeRemoteSettings(patch: Partial<RemoteSettings>): RemoteSettings {+ const next = normalize({ ...readRemoteSettings(), ...patch });+ const path = remoteSettingsPath();+ mkdirSync(dirname(path), { recursive: true });+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(next, null, 2), { encoding: 'utf-8', mode: 0o600 });+ try { chmodSync(tmp, 0o600); } catch { /* best effort */ }+ renameSync(tmp, path);+ cache = null;+ return next;+}diff --git a/src/security/request-origin.ts b/src/security/request-origin.tsnew file mode 100644index 00000000..f671e605--- /dev/null+++ b/src/security/request-origin.ts@@ -0,0 +1,90 @@+import type { Context } from 'hono';+import { normalizeIp } from './ip-match.js';++/**+ * Where a request really comes from.+ *+ * Mercury listens on 127.0.0.1 only, so a remote client always arrives+ * through a tunnel or proxy on this machine (Tailscale Serve, cloudflared,+ * ngrok, nginx/Caddy) — and those connect from 127.0.0.1 too. The socket+ * address alone therefore says nothing; a request is from THIS computer only+ * when the socket is loopback, no proxy added its headers, and the Host is a+ * loopback name. Everything else is remote.+ *+ * Proxies that add none of those headers and rewrite Host to 127.0.0.1 (a+ * bare nginx `proxy_pass`) can't be told apart from a local browser; the+ * actions that matter most also require the local attach token (which only+ * a process on this machine can read), and the security check warns about it.+ */++export interface RequestOrigin {+ /** The TCP peer is this machine. */+ socketLocal: boolean;+ /** A proxy or tunnel forwarded it (one of its headers is present). */+ proxied: boolean;+ /** The Host header names this machine (localhost, 127.0.0.1, ::1). */+ hostLocal: boolean;+ /** From this computer: local socket, not proxied, local Host. */+ local: boolean;+ /** The client's address as best known: the forwarded one through a proxy, else the socket's. */+ clientIp: string;+ /** The client's address is real: the proxy passed it on, or the client connected directly (so allow-lists can work). */+ clientIpKnown: boolean;+}++const PROXY_HEADERS = [+ 'forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip',+ 'cf-connecting-ip', 'cf-ray', 'true-client-ip', 'fly-client-ip', 'x-client-ip',+ 'tailscale-user-login', 'tailscale-user-name', 'tailscale-headers-info',+];++const LOCAL_SOCKETS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);+const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);++export function socketAddress(c: Context): string {+ try {+ return String((c.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined)?.incoming?.socket?.remoteAddress || '');+ } catch {+ return '';+ }+}++/** The host part of a Host header ("127.0.0.1:6174" → "127.0.0.1", "[::1]:6174" → "::1"). */+export function hostName(host: string): string {+ const h = host.trim().toLowerCase();+ if (h.startsWith('[')) return h.slice(1, h.indexOf(']') > 0 ? h.indexOf(']') : undefined);+ return h.replace(/:\d+$/, '');+}++function forwardedFor(value: string): string | null {+ // Forwarded: for=203.0.113.7;proto=https, for="[2001:db8::1]"+ const all = [...value.matchAll(/for="?\[?([^\]";,]+)\]?"?/gi)].map((m) => m[1]);+ return all.length ? all[all.length - 1] : null;+}++export function requestOrigin(c: Context): RequestOrigin {+ const socket = socketAddress(c);+ const socketLocal = LOCAL_SOCKETS.has(socket);+ const header = (name: string): string => c.req.header(name) ?? '';+ const proxied = PROXY_HEADERS.some((h) => header(h) !== '');+ // The Node server builds the URL from Host, so its hostname is the Host (requests made in-process have no header).+ let urlHost = '';+ try { urlHost = new URL(c.req.url).hostname; } catch { /* none */ }+ const hostLocal = LOCAL_HOSTS.has(hostName(header('host') || urlHost));+ // The address the proxy saw. The right-most X-Forwarded-For entry is the+ // one this machine's proxy appended; anything left of it is client-supplied.+ const xff = header('x-forwarded-for').split(',').map((s) => s.trim()).filter(Boolean);+ const forwarded = header('cf-connecting-ip') || header('true-client-ip') || header('fly-client-ip')+ || xff[xff.length - 1] || header('x-real-ip') || forwardedFor(header('forwarded')) || '';+ // Known: what the proxy reported, or a direct connection's own socket address.+ const viaProxy = proxied && forwarded !== '';+ const direct = !proxied && !socketLocal && socket !== '';+ return {+ socketLocal,+ proxied,+ hostLocal,+ local: socketLocal && !proxied && hostLocal,+ clientIp: normalizeIp(viaProxy ? forwarded : socket || 'unknown'),+ clientIpKnown: viaProxy || direct,+ };+}diff --git a/src/utils/config.ts b/src/utils/config.tsindex 2b685ffc..1ddf5923 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -293,6 +293,12 @@ export interface MercuryConfig {* self-hosted web build or a dev server here. Never '*'.*/corsOrigins?: string[];+ /**+ * Host names this server may be reached by directly, besides localhost —+ * only for a proxy of your own that rewrites Host and adds no forwarding+ * headers. Anything else is refused (DNS rebinding).+ */+ allowedHosts?: string[];};mcp?: McpConfig;/** Where the files Mercury makes go (default ~/mercury-artifacts): Research/ and one folder per chat. */diff --git a/src/web/api-contract.test.ts b/src/web/api-contract.test.tsindex b57555e9..cfe84722 100644--- a/src/web/api-contract.test.ts+++ b/src/web/api-contract.test.ts@@ -85,16 +85,39 @@ describe('api contract', () => {}, REMOTE);expect(bad.status).toBe(401);- const res = await authRoutes.request('http://127.0.0.1:6174/api/auth/token', {+ // From another device the owner approves it first: 202 with a code…+ const asked = 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(asked.status).toBe(202);+ const pending = await asked.json() as { pending: boolean; pairingId: string; pollToken: string; code: string; token?: string };+ expect(pending.pending).toBe(true);+ expect(pending.token).toBeUndefined();+ expect(pending.code).toMatch(/^[A-Z2-9]{5}$/);+ const poll = () => authRoutes.request('http://127.0.0.1:6174/api/auth/token/pending', {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ pairingId: pending.pairingId, pollToken: pending.pollToken, waitMs: 10 }),+ }, REMOTE);+ expect(((await (await poll()).json()) as { status: string }).status).toBe('pending');+ // A wrong poll token learns nothing.+ const forged = await authRoutes.request('http://127.0.0.1:6174/api/auth/token/pending', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pairingId: pending.pairingId, pollToken: 'x'.repeat(32) }) }, REMOTE);+ expect(forged.status).toBe(404);+ // …the owner says yes (here: as the CLI would), and the next poll gets the token, once.+ const { ownerApprovals } = await import('../security/owner-approvals.js');+ expect(ownerApprovals().decide(pending.code, 'allow', 'cli')?.status).toBe('allowed');+ const res = await poll();expect(res.status).toBe(200);const body = await res.json() as { token: string; device: { id: string; name: string }; apiVersion: number; features: string[] };+ expect((await poll()).status).toBe(404);expect(body.token).toMatch(/^mdt_/);expect(body.device.name).toBe('Desktop');expect(body.apiVersion).toBe(API_VERSION);+ // On this computer there's no one to ask.+ const here = 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: 'Laptop' }) }, LOOPBACK);+ expect(here.status).toBe(200);+ expect(((await here.json()) as { token: string }).token).toMatch(/^mdt_/);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);diff --git a/src/web/api/artifacts.ts b/src/web/api/artifacts.tsindex 75b7ea67..23018846 100644--- a/src/web/api/artifacts.ts+++ b/src/web/api/artifacts.ts@@ -7,7 +7,7 @@ import { Hono } from 'hono';import { artifactStore, type Artifact } from '../../artifacts/store.js';import type { ArtifactKind } from '../../artifacts/classify.js';import type { SessionRepository } from '../../sessions/index.js';-import { isLoopbackRequest } from '../middleware.js';+import { isThisComputer } from '../middleware.js';import { canConvert, CONVERT_MIME, convertedName, convertFile, type ConvertFormat } from '../../artifacts/convert/index.js';import { logger } from '../../utils/logger.js';@@ -79,7 +79,7 @@ artifacts.get('/api/artifacts/folder', (c) => {});artifacts.post('/api/artifacts/folder/tidy', (c) => {- if (!isLoopbackRequest(c)) return c.json({ error: 'Tidying files only works on the computer Mercury runs on.' }, 403);+ if (!isThisComputer(c)) return c.json({ error: 'Tidying files only works on the computer Mercury runs on.' }, 403);const folders = chatFoldersFor(outputRoot(outputSetting()));const moved: Array<{ name: string; to: string }> = [];const failed: Array<{ name: string; error: string }> = [];@@ -149,7 +149,7 @@ artifacts.get('/api/artifacts/:id/file', (c) => {});artifacts.post('/api/artifacts/:id/export', async (c) => {- if (!isLoopbackRequest(c)) return c.json({ error: 'Saving to a folder only works on the computer Mercury runs on. Use Download instead.' }, 403);+ if (!isThisComputer(c)) return c.json({ error: 'Saving to a folder only works on the computer Mercury runs on. Use Download instead.' }, 403);const a = artifactStore().get(c.req.param('id'));if (!a || !existsSync(a.storedPath)) return c.json({ error: 'Not found' }, 404);const body = (await c.req.json().catch(() => ({}))) as { dest?: unknown; as?: unknown };diff --git a/src/web/api/auth.ts b/src/web/api/auth.tsindex 4ce2ff65..8aa31fa5 100644--- a/src/web/api/auth.ts+++ b/src/web/api/auth.ts@@ -5,11 +5,16 @@ import { existsSync, readFileSync } from 'fs';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 { createHash, randomBytes, timingSafeEqual } from 'node:crypto';+import { authenticateAsync, createSession, destroySession, destroyAllSessions, changePassword, changeUsername, getSessionCookieName, getSessionMaxAge, sessionKey } from '../auth.js';+import { createDevice, getDevice, listDevices, revokeAllDevices, revokeDevice } from '../devices.js';+import { authenticateRequest, bearerToken, isThisComputer, originOf, principalLabel } from '../middleware.js';import { apiContract } from '../api-contract.js';import { createLoginLimiter } from '../login-limiter.js';+import { requireOwner, whereToApprove } from '../owner-gate.js';+import { ownerApprovals } from '../../security/owner-approvals.js';+import { audit } from '../../security/audit.js';+import { closeStreams } from '../../security/live-streams.js';function resolveWebDir(...segments: string[]): string {const __dirname = dirname(fileURLToPath(import.meta.url));@@ -63,7 +68,34 @@ auth.get('/login', (c) => {return c.html(renderLoginPage());});+// Sign-in attempts are limited per client: per address when the tunnel says+// who it is, one shared allowance for unknown remote clients, and never+// against someone on this computer (so nobody online can lock the owner out+// of their own machine).+const signInLimiter = createLoginLimiter();++function limiterKey(c: Parameters<typeof originOf>[0]): string {+ const o = originOf(c);+ if (o.local) return 'this-computer';+ return o.clientIpKnown ? `ip:${o.clientIp}` : 'remote-unknown';+}++/** Secure cookies over https (directly or through a tunnel that says so). */+function overHttps(c: Parameters<typeof originOf>[0]): boolean {+ try {+ return new URL(c.req.url).protocol === 'https:' || (c.req.header('x-forwarded-proto') ?? '').split(',')[0].trim() === 'https';+ } catch {+ return false;+ }+}+auth.post('/api/auth/login', async (c) => {+ const key = limiterKey(c);+ const wait = signInLimiter.retryAfterSeconds(key);+ if (wait > 0) {+ c.header('Retry-After', String(wait));+ return c.html(renderLoginPage(`Too many failed attempts. Try again in ${Math.ceil(wait / 60)} minutes.`), 429);+ }const body = await c.req.parseBody();const username = (body.username as string) || '';const password = (body.password as string) || '';@@ -72,14 +104,17 @@ auth.post('/api/auth/login', async (c) => {return c.html(renderLoginPage('Please enter both username and password'), 400);}- if (!authenticate(username, password)) {+ if (!(await authenticateAsync(username, password))) {+ signInLimiter.recordFailure(key);+ audit('login.failed', { who: 'browser', ip: originOf(c).clientIp });return c.html(renderLoginPage('Invalid username or password'), 401);}+ signInLimiter.reset(key);const token = createSession();setCookie(c, getSessionCookieName(), token, {httpOnly: true,- secure: false,+ secure: overHttps(c),sameSite: 'Strict',maxAge: getSessionMaxAge(),path: '/',@@ -90,10 +125,10 @@ auth.post('/api/auth/login', async (c) => {auth.get('/api/auth/logout', (c) => {const token = getCookie(c, getSessionCookieName());- if (token) destroySession(token);+ if (token) { destroySession(token); closeStreams(`session:${sessionKey(token)}`); }setCookie(c, getSessionCookieName(), '', {httpOnly: true,- secure: false,+ secure: overHttps(c),sameSite: 'Strict',maxAge: 0,path: '/',@@ -104,27 +139,40 @@ auth.get('/api/auth/logout', (c) => {// ── 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+// On this computer → 200 { token, device, apiVersion, features, version? }+// From anywhere else → 202 { pending, pairingId, pollToken, code, where, expiresAt }:+// the owner approves the new device (their messaging channel, the CLI,+// Mercury Desktop here); the client asks POST /api/auth/token/pending+// { pairingId, pollToken } until it gets the token (or "denied"/"expired").+// → 401 bad credentials · 429 too many failures · 409 device limit//// 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.+// stored on the device.-const tokenLimiter = createLoginLimiter();+const PAIRING_TTL_MS = 10 * 60_000;-function peerAddress(c: { env?: unknown }): string {- try {- return String((c.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined)?.incoming?.socket?.remoteAddress || 'unknown');- } catch {- return 'unknown';- }+interface PendingPairing {+ approvalId: string;+ pollHash: string;+ deviceName: unknown;+ platform: unknown;+ ip?: string;+ /** Set once the token was handed out: a second poll can't mint another. */+ done?: boolean;+}++const pairings = new Map<string, PendingPairing>();+const sha = (s: string): string => createHash('sha256').update(s).digest('hex');++function sameSecret(presented: string, hash: string): boolean {+ const a = Buffer.from(sha(presented), 'hex');+ const b = Buffer.from(hash, 'hex');+ return a.length === b.length && timingSafeEqual(a, b);}auth.post('/api/auth/token', async (c) => {- const peer = peerAddress(c);- const wait = tokenLimiter.retryAfterSeconds(peer);+ const key = limiterKey(c);+ const wait = signInLimiter.retryAfterSeconds(key);if (wait > 0) {c.header('Retry-After', String(wait));return c.json({ error: 'Too many failed sign-in attempts; try again later' }, 429);@@ -140,18 +188,89 @@ auth.post('/api/auth/token', async (c) => {if (!username || !password) {return c.json({ error: 'Username and password required' }, 400);}- if (!authenticate(username, password)) {- tokenLimiter.recordFailure(peer);+ const origin = originOf(c);+ if (!(await authenticateAsync(username, password))) {+ signInLimiter.recordFailure(key);+ audit('login.failed', { who: typeof body.deviceName === 'string' ? body.deviceName.slice(0, 64) : 'a device', ip: origin.clientIp });+ if (signInLimiter.retryAfterSeconds(key) > 0) audit('login.locked', { ip: origin.clientIp });return c.json({ error: 'Invalid username or password' }, 401);}- tokenLimiter.reset(peer);- let created;+ signInLimiter.reset(key);++ // On this computer the owner is right here: no one to ask.+ if (origin.local) {+ try {+ const created = createDevice(body.deviceName, body.platform, 'this computer');+ audit('pair.local', { who: created.device.name });+ return c.json({ token: created.token, device: created.device, ...apiContract() });+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : 'Could not create device' }, 409);+ }+ }++ // Check the limit now, not after the owner said yes.+ if (listDevices().length >= (await import('../../security/remote-settings.js')).readRemoteSettings().maxDevices) {+ return c.json({ error: 'This Mercury has reached its device limit. Revoke a device, or raise the limit with /server.' }, 409);+ }+ const name = String(body.deviceName ?? 'A new device').replace(/[^\P{C}]/gu, '').trim().slice(0, 64) || 'A new device';+ const platform = typeof body.platform === 'string' ? body.platform.replace(/[^a-z0-9-]/gi, '').slice(0, 24) : '';+ const ip = origin.clientIpKnown ? origin.clientIp : undefined;+ const approval = ownerApprovals().request({+ kind: 'pair',+ title: `New device: ${name}`,+ detail: [platform && `on ${platform}`, ip && `from ${ip}`].filter(Boolean).join(', ') || undefined,+ who: name,+ ip,+ }, PAIRING_TTL_MS);+ const pairingId = randomBytes(12).toString('base64url');+ const pollToken = randomBytes(24).toString('base64url');+ pairings.set(pairingId, { approvalId: approval.id, pollHash: sha(pollToken), deviceName: body.deviceName, platform: body.platform, ip });+ const timer = setTimeout(() => pairings.delete(pairingId), PAIRING_TTL_MS + 5 * 60_000);+ timer.unref?.();+ audit('pair.requested', { who: name, ip });+ return c.json({+ pending: true,+ pairingId,+ pollToken,+ code: approval.code,+ where: whereToApprove(),+ expiresAt: approval.expiresAt,+ message: `Approve this device on ${whereToApprove()}. Code: ${approval.code}`,+ }, 202);+});++/** A pairing waiting for the owner: answers within ~25 s if it's decided meanwhile. */+auth.post('/api/auth/token/pending', async (c) => {+ let body: Record<string, unknown>;+ try { body = await c.req.json(); } catch { return c.json({ error: 'Expected a JSON body' }, 400); }+ const pairingId = typeof body.pairingId === 'string' ? body.pairingId : '';+ const pollToken = typeof body.pollToken === 'string' ? body.pollToken : '';+ const p = pairings.get(pairingId);+ if (!p || !pollToken || !sameSecret(pollToken, p.pollHash)) return c.json({ status: 'expired', error: 'This sign-in request is no longer waiting. Sign in again.' }, 404);+ if (p.done) return c.json({ status: 'expired', error: 'This sign-in request was already completed.' }, 410);+ const approvals = ownerApprovals();+ let status = approvals.get(p.approvalId)?.status ?? 'expired';+ if (status === 'pending') {+ status = await Promise.race([+ approvals.wait(p.approvalId),+ new Promise<'pending'>((r) => { const t = setTimeout(() => r('pending'), Math.min(25_000, Number(body.waitMs) || 25_000)); t.unref?.(); }),+ ]);+ }+ if (status === 'pending') return c.json({ status: 'pending', code: approvals.get(p.approvalId)?.code });+ if (status !== 'allowed') {+ pairings.delete(pairingId);+ return c.json({ status, error: status === 'denied' ? 'The owner did not approve this device.' : 'Nobody approved this device in time. Sign in again to ask again.' }, 403);+ }+ p.done = true;+ pairings.delete(pairingId);+ const decidedBy = approvals.get(p.approvalId)?.decidedBy ?? 'owner';try {- created = createDevice(body.deviceName, body.platform);+ const created = createDevice(p.deviceName, p.platform, decidedBy);+ audit('pair.approved', { who: created.device.name, ip: p.ip, by: decidedBy });+ return c.json({ status: 'approved', token: created.token, device: created.device, ...apiContract() });} catch (err) {- return c.json({ error: err instanceof Error ? err.message : 'Could not create device' }, 409);+ return c.json({ status: 'error', error: err instanceof Error ? err.message : 'Could not create device' }, 409);}- return c.json({ token: created.token, device: created.device, ...apiContract() });});auth.get('/api/auth/devices', (c) => {@@ -162,10 +281,22 @@ auth.get('/api/auth/devices', (c) => {});});+/** Revoke a device: its own token always; another device from this computer, or with the owner's approval. */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);+ const principal = authenticateRequest(c);+ const self = principal?.kind === 'device' && principal.deviceId === id;+ if (!self) {+ const target = getDevice(id);+ const wait = requireOwner(c, { id: `device.revoke:${id}`, title: `Sign out the device “${target?.name ?? id}”` });+ if (wait) return wait;+ }+ const name = getDevice(id)?.name ?? id;+ if (!revokeDevice(id)) return c.json({ error: 'No such device' }, 404);+ closeStreams(`device:${id}`);+ audit('device.revoked', { who: name, by: self ? 'itself' : principalLabel(principal) });+ return c.json({ success: true });});/** Sign out this device: revoke the token that made the call. */@@ -173,6 +304,8 @@ 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);+ closeStreams(`device:${principal.deviceId}`);+ audit('device.revoked', { who: principal.deviceName, by: 'itself' });return c.json({ success: true });});@@ -180,27 +313,46 @@ auth.post('/api/auth/token/revoke', (c) => {// 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);+ if (token) { destroySession(token); closeStreams(`session:${sessionKey(token)}`); }return c.json({ success: true });});+/**+ * Change the password. Every other browser is signed out (a changed password+ * means the old one may be known); `signOutDevices: true` revokes every+ * device token too. From a remote device it also needs the owner's approval.+ */auth.post('/api/auth/password', async (c) => {- const body = await c.req.json();+ const body = await c.req.json().catch(() => ({})) as { currentPassword?: string; newPassword?: string; signOutDevices?: boolean };const { currentPassword, newPassword } = body;if (!currentPassword || !newPassword) {return c.json({ error: 'Current and new password required' }, 400);}+ if (newPassword.length < 10) return c.json({ error: 'Use at least 10 characters for the new password.' }, 400);+ const wait = requireOwner(c, { id: 'auth.password', title: 'Change the Mercury password' });+ if (wait) return wait;const ok = changePassword(currentPassword, newPassword);if (!ok) return c.json({ error: 'Current password is incorrect' }, 403);- return c.json({ success: true });+ const keep = bearerToken(c) || getCookie(c, getSessionCookieName()) || undefined;+ for (const k of destroyAllSessions(keep)) closeStreams(`session:${k}`);+ let devicesSignedOut = 0;+ if (body.signOutDevices === true) {+ const ids = revokeAllDevices();+ for (const id of ids) closeStreams(`device:${id}`);+ devicesSignedOut = ids.length;+ }+ audit('password.changed', { by: isThisComputer(c) ? 'this computer' : principalLabel(authenticateRequest(c)), detail: devicesSignedOut ? `${devicesSignedOut} devices signed out` : undefined });+ return c.json({ success: true, devicesSignedOut });});auth.post('/api/auth/username', async (c) => {- const body = await c.req.json();+ const body = await c.req.json().catch(() => ({})) as { currentPassword?: string; newUsername?: string };const { currentPassword, newUsername } = body;if (!currentPassword || !newUsername) {return c.json({ error: 'Current password and new username required' }, 400);}+ const wait = requireOwner(c, { id: 'auth.username', title: 'Change the Mercury username' });+ if (wait) return wait;const ok = changeUsername(currentPassword, newUsername);if (!ok) return c.json({ error: 'Current password is incorrect' }, 403);return c.json({ success: true });diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex da1bb86e..5f06cb8c 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -1,3 +1,6 @@+import { requireOwner } from '../owner-gate.js';+import { trackStream } from '../../security/live-streams.js';+import { principalKey, principalOf } from '../middleware.js';import { Hono } from 'hono';import { openFolder, tildify } from '../../bots/open-folder.js';import type { Context } from 'hono';@@ -90,6 +93,13 @@ app.post('/api/bots/inbox/read', async (c: Context) => {});// Onboard a bot+/** Tiers that run commands or reach the whole home folder: from another device, the owner decides. */+const POWERFUL_TIERS = new Set(['operator', 'full']);+function gateTier(c: any, tier: string | undefined, botId: string): Response | null {+ if (!tier || !POWERFUL_TIERS.has(tier)) return null;+ return requireOwner(c, { id: `bots.tier:${botId}:${tier}`, title: `Give the bot “${botId}” ${tier === 'full' ? 'full access to this computer' : 'permission to run commands'}` });+}+app.post('/api/bots', async (c: any) => {if (!botManager) {return c.json({ error: 'Bots not available' }, 400);@@ -102,6 +112,8 @@ app.post('/api/bots', async (c: any) => {if (body.tier !== undefined && !isPermissionTier(body.tier)) {return c.json({ error: `Unknown permission tier: ${body.tier}` }, 400);}+ const tierWait = gateTier(c, body.tier, String(body.id));+ if (tierWait) return tierWait;try {const manifest = botManager.store.create({id: body.id,@@ -179,13 +191,16 @@ app.get('/api/bots/events', (c: any) => {try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }}, 15000);- c.req.raw.signal?.addEventListener('abort', () => {+ const cleanup = () => {clearInterval(keepalive);unsubscribe();unsubscribeInbox();unsubscribeApprovals();rosterSseClients.delete(client);- });+ untrack();+ };+ const untrack = trackStream(principalKey(principalOf(c)), () => { cleanup(); try { controller.close(); } catch { /* closed */ } });+ c.req.raw.signal?.addEventListener('abort', cleanup);},cancel() {},});@@ -247,6 +262,9 @@ app.post('/api/bots/import', async (c: any) => {if (!botManager) return c.json({ error: 'Bots not available' }, 400);const bundle = await c.req.json().catch(() => null) as any;if (!bundle) return c.json({ error: 'Invalid JSON body' }, 400);+ // A bundle brings its own permissions and schedules.+ const importWait = requireOwner(c, { id: 'bots.import', title: 'Import bots (with their own permissions and schedules)' });+ if (importWait) return importWait;try {const report = importBotBundle(botManager.store, bundle, c.req.query('overwrite') === '1' ? { overwrite: true } : {});for (const created of report.created) botManager.invalidateRuntime(created);@@ -488,6 +506,8 @@ app.post('/api/bots/:id/crew', async (c: any) => {if (body.tier !== undefined && !isPermissionTier(body.tier)) {return c.json({ error: `Unknown permission tier: ${body.tier}` }, 400);}+ const tierWait = gateTier(c, body.tier, String(body.id));+ if (tierWait) return tierWait;const result = botManager.addCrew(id, { id: body.id, name: body.name, description: body.description, persona: body.persona });if (!result.ok) return c.json({ error: result.error }, 400);// A tier choice overrides the crew's verbatim lead inheritance (§2.5:@@ -593,6 +613,10 @@ app.put('/api/bots/:id/permissions', async (c: any) => {const id = c.req.param('id');if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);const body = await c.req.json().catch(() => null) as { tier?: string; permissions?: any } | null;+ const permWait = body?.permissions !== undefined+ ? requireOwner(c, { id: `bots.permissions:${c.req.param('id')}`, title: `Rewrite the permissions of the bot “${c.req.param('id')}”` })+ : gateTier(c, body?.tier, c.req.param('id'));+ if (permWait) return permWait;if (!body) return c.json({ error: 'Invalid JSON body' }, 400);try {if (body.tier !== undefined) {diff --git a/src/web/api/channels.ts b/src/web/api/channels.tsindex 4c77adf2..e7630fd7 100644--- a/src/web/api/channels.ts+++ b/src/web/api/channels.ts@@ -1,3 +1,4 @@+import { requireOwner } from '../owner-gate.js';import { Hono } from 'hono';import {approveDiscordPendingRequest, approveSignalPendingRequest, approveSlackPendingRequest, approveTelegramPendingRequest,@@ -172,6 +173,9 @@ channels.post('/api/channels/:type/check', async (c) => {const type = c.req.param('type');if (!isType(type)) return c.json({ ok: false, message: 'Unknown channel' }, 400);const body = (await c.req.json().catch(() => ({}))) as Draft;+ // A channel's token decides who can talk to Mercury as the owner.+ const wait = requireOwner(c, { id: `channels.settings:${type}`, title: `Change the ${type} channel's settings or token` });+ if (wait) return wait;const bad = maskedProblem(body);if (bad) return c.json({ ok: false, field: bad, message: 'That is the hidden form of the saved key. Paste the full key, or leave it empty to keep the saved one.' });return c.json(await check(type, merged(type, live(), body)));@@ -223,6 +227,11 @@ channels.post('/api/channels/:type/access', async (c) => {const body = (await c.req.json().catch(() => ({}))) as { action?: unknown; id?: unknown; role?: unknown };const action = String(body.action ?? '');const id = typeof body.id === 'string' ? body.id.trim() : typeof body.id === 'number' ? String(body.id) : '';+ // Letting someone in (or making them an admin) is the owner's call; removing people isn't gated.+ if (action === 'approve' || action === 'promote' || action === 'add') {+ const wait = requireOwner(c, { id: `channels.access:${type}:${action}:${id}`, title: `${action === 'promote' ? 'Make an admin' : 'Let someone in'} on ${type}`, detail: id || undefined });+ if (wait) return wait;+ }const config = live();const r = applyAccess(type, config, action, id, body.role === 'admin' ? 'admin' : body.role === 'member' ? 'member' : undefined);if (!r.ok) return c.json({ error: r.error }, r.status ?? 400);@@ -304,6 +313,8 @@ interface LinkState { status: 'starting' | 'waiting' | 'linked' | 'failed'; uri?let link: LinkState | null = null;channels.post('/api/channels/signal/link', async (c) => {+ const wait = requireOwner(c, { id: 'channels.signal.link', title: 'Link a Signal account to Mercury' });+ if (wait) return wait;if (link && (link.status === 'starting' || link.status === 'waiting') && Date.now() - link.startedAt < 120_000) return c.json(link);link = { status: 'starting', startedAt: Date.now() };const current = link;diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 2ee30ffa..4c177225 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -1,3 +1,7 @@+import { trackStream } from '../../security/live-streams.js';+import { isThisComputer, principalKey, principalOf } from '../middleware.js';+import { requireOwner } from '../owner-gate.js';+import { protectedReason } from '../../security/protected-paths.js';import { Hono } from 'hono';import { commandCatalog } from '../../core/commands/catalog.js';import { getPluginManager } from '../../plugins/manager.js';@@ -178,15 +182,15 @@ chat.get('/api/chat/activity', (c) => {}const stream = new ReadableStream({start(controller) {- const clientId = ch.addActivityClient(controller);+ const clientId = ch.addActivityClient(controller, isThisComputer(c));const encoder = new TextEncoder();const send = (data: string) => { try { controller.enqueue(encoder.encode(data)); } catch { /* closed */ } };send(`event: connected\ndata: ${JSON.stringify({ id: clientId })}\n\n`);const keepalive = setInterval(() => send(': keepalive\n\n'), 15000);- c.req.raw.signal.addEventListener('abort', () => {- clearInterval(keepalive);- ch.removeActivityClient(clientId);- });+ const cleanup = () => { clearInterval(keepalive); ch.removeActivityClient(clientId); untrack(); };+ // Revoking the device (or signing the browser out) ends this stream at once.+ const untrack = trackStream(principalKey(principalOf(c)), () => { cleanup(); try { controller.close(); } catch { /* closed */ } });+ c.req.raw.signal.addEventListener('abort', cleanup);},});return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' } });@@ -227,10 +231,10 @@ chat.get('/api/chat/events', (c) => {send(`: keepalive\n\n`);}, 15000);- c.req.raw.signal.addEventListener('abort', () => {- clearInterval(keepalive);- webChannel?.removeSSEClient(clientId);- });+ const cleanup = () => { clearInterval(keepalive); webChannel?.removeSSEClient(clientId); untrack(); };+ // Revoking the device (or signing the browser out) ends this stream at once.+ const untrack = trackStream(principalKey(principalOf(c)), () => { cleanup(); try { controller.close(); } catch { /* closed */ } });+ c.req.raw.signal.addEventListener('abort', cleanup);},cancel() {},});@@ -341,6 +345,15 @@ chat.put('/api/chat/settings', async (c) => {const body = await c.req.json<Partial<ChatWebSettings>>();const current = webChannel.getSettings();const stored = loadSettings();+ // Widening what Mercury may do, from another device, is the owner's call.+ if (body.bypassPermissions === true && !current.bypassPermissions) {+ const wait = requireOwner(c, { id: 'permissions.allow-all', title: 'Turn on Allow All (Mercury acts without asking)' });+ if (wait) return wait;+ }+ if (typeof body.workspace === 'string' && body.workspace !== stored.workspace) {+ const wait = requireOwner(c, { id: `workspace.root:${body.workspace}`, title: 'Change the workspace folder', detail: body.workspace });+ if (wait) return wait;+ }const next: ChatWebSettings = {bypassPermissions: body.bypassPermissions ?? current.bypassPermissions,restrictUser: body.restrictUser ?? current.restrictUser,@@ -658,6 +671,8 @@ chat.get('/api/workspace/file', (c) => {if (!isInsideWorkspace(fullPath, rootDir)) {return c.json({ error: 'Path outside workspace' }, 403);}+ const off = protectedReason(fullPath, !isThisComputer(c));+ if (off) return c.json({ error: off }, 403);if (!existsSync(fullPath)) {return c.json({ error: 'File not found' }, 404);@@ -700,6 +715,9 @@ chat.put('/api/workspace/root', async (c) => {if (!existsSync(resolvedPath)) {return c.json({ error: 'Directory does not exist' }, 404);}+ // The workspace bounds what the file endpoints reach: from another device, the owner decides where it is.+ const wait = requireOwner(c, { id: `workspace.root:${resolvedPath}`, title: 'Change the workspace folder', detail: resolvedPath });+ if (wait) return wait;const stat = statSync(resolvedPath);if (!stat.isDirectory()) {return c.json({ error: 'Path is not a directory' }, 400);diff --git a/src/web/api/cloud.ts b/src/web/api/cloud.tsindex 8bf169cd..d874d75d 100644--- a/src/web/api/cloud.ts+++ b/src/web/api/cloud.ts@@ -1,3 +1,4 @@+import { requireOwner } from '../owner-gate.js';import { Hono } from 'hono';import { getActiveProviders, isProviderConfigured, loadConfig, updateConfig, type MercuryConfig, type ProviderName } from '../../utils/config.js';import { isChatModelId } from '../../utils/provider-models.js';@@ -118,6 +119,9 @@ function publicPairing() {}cloud.post('/api/cloud/signin', async (c) => {+ // Signing in to a Cloud account lets that account send Mercury commands: the owner decides.+ const wait = requireOwner(c, { id: 'cloud.signin', title: 'Connect Mercury to a Mercury Cloud account' });+ if (wait) return wait;if (pairing?.status === 'pending' && Date.now() - pairing.startedAt < 290_000) return c.json(publicPairing());const config = loadConfig();const apiUrl = config.cloud.apiUrl || MERCURY_CLOUD_API_URL;diff --git a/src/web/api/devices.ts b/src/web/api/devices.tsindex 32804ba5..fa2f292b 100644--- a/src/web/api/devices.ts+++ b/src/web/api/devices.ts@@ -11,7 +11,7 @@* settings there, so it's accepted from this machine only.*/import { Hono, type Context } from 'hono';-import { isLoopbackRequest } from '../middleware.js';+import { isThisComputer } from '../middleware.js';import { getPluginManager } from '../../plugins/manager.js';import { deviceFeed } from '../../plugins/device-feed.js';@@ -20,7 +20,7 @@ const devices = new Hono();const KINDS = ['microphone', 'screen', 'accessibility', 'camera'] as const;function localOnly(c: Context): Response | null {- if (isLoopbackRequest(c)) return null;+ if (isThisComputer(c)) return null;return c.json({ error: 'Microphone and permissions are set on the computer Mercury runs on. Open Mercury there.', remote: true }, 403);}diff --git a/src/web/api/kanban.ts b/src/web/api/kanban.tsindex 878b1bfd..082e683d 100644--- a/src/web/api/kanban.ts+++ b/src/web/api/kanban.ts@@ -1,3 +1,6 @@+import { requireOwner } from '../owner-gate.js';+import { trackStream } from '../../security/live-streams.js';+import { principalKey, principalOf } from '../middleware.js';import { Hono } from 'hono';import { readFileSync, existsSync, statSync } from 'node:fs';import { generateText } from 'ai';@@ -138,10 +141,9 @@ app.get('/api/boards/:id/events', (c: any) => {}, 15000);// Cleanup on close (controller error signals disconnect)- c.req.raw.signal?.addEventListener('abort', () => {- clearInterval(keepalive);- sseClients.delete(client);- });+ const cleanup = () => { clearInterval(keepalive); sseClients.delete(client); untrack(); };+ const untrack = trackStream(principalKey(principalOf(c)), () => { cleanup(); try { controller.close(); } catch { /* closed */ } });+ c.req.raw.signal?.addEventListener('abort', cleanup);},cancel() {}});@@ -904,6 +906,9 @@ app.post('/api/boards/:id/context/directory', async (c: any) => {const boardId = c.req.param('id');const { directory } = await c.req.json();if (!directory) return c.json({ error: 'directory required' }, 400);+ // Board agents run in this folder.+ const wait = requireOwner(c, { id: `boards.directory:${boardId}:${directory}`, title: 'Change the folder a board’s agents work in', detail: String(directory) });+ if (wait) return wait;boardManager.setBoardWorkingDirectory(boardId, directory);boardManager.saveBatch(boardId);return c.json({ ok: true });diff --git a/src/web/api/lifecycle.ts b/src/web/api/lifecycle.tsindex fff862fa..e520554f 100644--- a/src/web/api/lifecycle.ts+++ b/src/web/api/lifecycle.ts@@ -1,6 +1,6 @@import { Hono } from 'hono';-import { readAttachToken } from '../auth.js';-import { isLoopbackRequest } from '../middleware.js';+import { authenticateRequest, isThisComputer } from '../middleware.js';+import { requireOwner } from '../owner-gate.js';import { spawnDetachedRestart } from '../../cli/daemon.js';let restartSpawner: () => boolean = spawnDetachedRestart;@@ -28,21 +28,15 @@ export function setShutdownHandler(handler: (() => void) | null): void {shutdownHandler = handler;}-function bearerToken(header: string | undefined): string | null {- if (!header) return null;- const match = /^Bearer\s+(.+)$/i.exec(header.trim());- return match ? match[1].trim() : null;-}-/**- * Apply saved configuration by restarting the runtime. Loopback only — the- * dashboard runs on this machine; the auth guard has already admitted the- * session (or attach token). Providers, channels and keys are read at boot,+ * Apply saved configuration by restarting the runtime. On this computer it+ * just happens; from another device the owner approves it first. Providers, channels and keys are read at boot,* so this is how a dashboard save actually takes effect.*/lifecycle.post('/api/restart', (c) => {- if (!isLoopbackRequest(c)) {- return c.json({ error: 'Restart is only accepted from this machine' }, 403);+ if (!isThisComputer(c)) {+ const wait = requireOwner(c, { id: 'runtime.restart', title: 'Restart Mercury' });+ if (wait) return wait;}if (!restartSpawner()) {return c.json({ error: 'Could not start the restart helper — run `mercury restart` in a terminal' }, 503);@@ -51,12 +45,8 @@ lifecycle.post('/api/restart', (c) => {});lifecycle.post('/api/shutdown', (c) => {- if (!isLoopbackRequest(c)) {- return c.json({ error: 'Shutdown is only accepted from this machine' }, 403);- }- const token = bearerToken(c.req.header('Authorization'));- const expected = readAttachToken();- if (!token || !expected || token !== expected) {+ // Only a process on this computer holding the attach token (`mercury stop`).+ if (authenticateRequest(c)?.kind !== 'attach') {return c.json({ error: 'Shutdown requires the local attach token' }, 403);}if (!shutdownHandler) {diff --git a/src/web/api/plugins.ts b/src/web/api/plugins.tsindex 501e71db..5918d358 100644--- a/src/web/api/plugins.ts+++ b/src/web/api/plugins.ts@@ -8,7 +8,8 @@* a LAN or Cloud-relayed session.*/import { Hono, type Context } from 'hono';-import { isLoopbackRequest } from '../middleware.js';+import { isThisComputer } from '../middleware.js';+import { requireOwner } from '../owner-gate.js';import { getPluginManager } from '../../plugins/manager.js';import { localService } from '../../plugins/service.js';import { qrSvg } from '../../plugins/qr-svg.js';@@ -19,9 +20,14 @@ function svc() {return localService(getPluginManager());}+/**+ * Plugins run code on this computer: changing them from another device waits+ * for the owner's approval (on this computer it just happens).+ */function localOnly(c: Context): Response | null {- if (isLoopbackRequest(c)) return null;- return c.json({ error: 'Plugins can only be installed or changed from this machine.' }, 403);+ if (isThisComputer(c)) return null;+ const path = new URL(c.req.url).pathname;+ return requireOwner(c, { id: `plugins:${c.req.method}:${path}`, title: `Change plugins (${c.req.method} ${path.replace('/api/plugins', '') || '/'})` });}function fail(c: Context, err: unknown) {diff --git a/src/web/api/providers.ts b/src/web/api/providers.tsindex 9852cbaf..c8d9213e 100644--- a/src/web/api/providers.ts+++ b/src/web/api/providers.ts@@ -1,3 +1,4 @@+import { requireOwner } from '../owner-gate.js';import { Hono } from 'hono';import { getActiveProviders, isProviderConfigured, loadConfig, saveConfig, type MercuryConfig, type ProviderConfig, type ProviderName } from '../../utils/config.js';import { PROVIDER_META, validateApiKey, validateBaseUrl, validateModelName } from '../../providers/provider-meta.js';@@ -80,11 +81,23 @@ function looksMasked(key: string): boolean {return key.includes('•');}-/** Merge what the user typed over what is saved; an omitted key keeps the saved one. */-function draft(saved: ProviderConfig, body: { apiKey?: unknown; baseUrl?: unknown; model?: unknown }): ProviderConfig {+/** The base URL the user typed differs from the saved one. */+function newBaseUrl(saved: ProviderConfig, body: { baseUrl?: unknown }): boolean {+ if (typeof body.baseUrl !== 'string' || !body.baseUrl.trim()) return false;+ return body.baseUrl.trim().replace(/\/+$/, '') !== String(saved.baseUrl ?? '').replace(/\/+$/, '');+}++/**+ * Merge what the user typed over what is saved; an omitted key keeps the+ * saved one — except for a check against a different address: the saved+ * key never goes to a server it wasn't saved for (a "test" of an attacker's+ * URL would otherwise hand it the key).+ */+function draft(saved: ProviderConfig, body: { apiKey?: unknown; baseUrl?: unknown; model?: unknown }, opts: { forCheck?: boolean } = {}): ProviderConfig {+ const typedKey = typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : null;return {...saved,- apiKey: typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : saved.apiKey,+ apiKey: typedKey ?? (opts.forCheck && newBaseUrl(saved, body) ? '' : saved.apiKey),baseUrl: typeof body.baseUrl === 'string' && body.baseUrl.trim() ? body.baseUrl.trim().replace(/\/+$/, '') : saved.baseUrl,model: typeof body.model === 'string' ? body.model.trim() : saved.model,};@@ -154,7 +167,7 @@ providers.post('/api/providers/:name/check', async (c) => {if (!isName(name)) return c.json({ ok: false, error: 'Unknown provider' }, 400);const body = (await c.req.json().catch(() => ({}))) as { apiKey?: unknown; baseUrl?: unknown };const config = loadConfig();- const pc = draft(config.providers[name], body);+ const pc = draft(config.providers[name], body, { forCheck: true });const issues = PROVIDER_META[name].signInOnly ? [] : problems(name, pc, body);if (issues.length) return c.json({ ok: false, error: issues[0].error, field: issues[0].field, problems: issues });const started = Date.now();@@ -231,6 +244,11 @@ providers.post('/api/providers/:name', async (c) => {return c.json({ error: `${meta.label} signs in with your account (run \`mercury doctor\`); it has no key to set.` }, 400);}+ // Pointing a saved key at another server, from another device, is the owner's call.+ if (newBaseUrl(p, body) && !(typeof body.apiKey === 'string' && body.apiKey.trim())) {+ const wait = requireOwner(c, { id: `providers.baseUrl:${name}`, title: `Send the ${meta.label} key to a different server`, detail: String(body.baseUrl) });+ if (wait) return wait;+ }const next = draft(p, body);if (body.apiKey === '' || body.apiKey === null) next.apiKey = '';if (body.baseUrl === '' || body.baseUrl === null) next.baseUrl = '';diff --git a/src/web/api/security.ts b/src/web/api/security.tsnew file mode 100644index 00000000..78a5e2b4--- /dev/null+++ b/src/web/api/security.ts@@ -0,0 +1,130 @@+import { Hono } from 'hono';+import { createDevice, getDevice, listDevices, revokeAllDevices, revokeDevice } from '../devices.js';+import { authenticateRequest, isThisComputer, lastRemoteRequest, principalKey } from '../middleware.js';+import { approvalRoutes } from '../owner-gate.js';+import { ownerApprovals } from '../../security/owner-approvals.js';+import { readRemoteSettings, writeRemoteSettings, type RemoteSettings } from '../../security/remote-settings.js';+import { parseIpRule } from '../../security/ip-match.js';+import { audit, readAudit } from '../../security/audit.js';+import { closeStreams } from '../../security/live-streams.js';+import { securityCheck, summarizeFindings } from '../../security/check.js';+import { sessionCount } from '../auth.js';++/**+ * Remote access and its security, for the owner on this computer (`/server`,+ * `mercury server`, Mercury Desktop's Security settings). Everything here+ * works only from this computer, except one read: a device waiting for the+ * owner can ask how its own question stands.+ *+ * GET /api/security/status settings, devices, waiting questions, last remote request, check+ * PUT /api/security/remote { enabled?, allowIps?, allowShell?, maxDevices?, idleDays? }+ * GET /api/security/approvals questions waiting for the owner+ * POST /api/security/approvals/:id { decision: "allow" | "deny" } (id or code)+ * GET /api/security/approvals/:id/status the asking device's own question+ * POST /api/security/devices { name } → a new token, shown once+ * DELETE /api/security/devices/:id | /devices revoke one / all+ * GET /api/security/audit?limit= the security log, newest first+ * GET /api/security/check the security check+ */++let cloudConnected: () => boolean = () => false;+export function setSecurityCloudState(fn: () => boolean): void { cloudConnected = fn; }++const security = new Hono();++security.use('/api/security/*', async (c, next) => {+ if (/\/approvals\/[^/]+\/status$/.test(new URL(c.req.url).pathname)) return next();+ if (!isThisComputer(c)) return c.json({ error: 'Remote access settings can only be changed on the computer Mercury runs on.', thisComputerOnly: true }, 403);+ return next();+});++function status() {+ const findings = securityCheck({ lastRemote: lastRemoteRequest(), cloudConnected: cloudConnected() });+ return {+ remote: readRemoteSettings(),+ devices: listDevices(),+ browsers: sessionCount(),+ pending: ownerApprovals().pending(),+ approvalRoutes: approvalRoutes(),+ lastRemote: lastRemoteRequest(),+ check: { summary: summarizeFindings(findings), findings },+ };+}++security.get('/api/security/status', (c) => c.json(status()));++security.put('/api/security/remote', async (c) => {+ const body = (await c.req.json().catch(() => ({}))) as Partial<RemoteSettings>;+ const patch: Partial<RemoteSettings> = {};+ if (typeof body.enabled === 'boolean') patch.enabled = body.enabled;+ if (typeof body.allowShell === 'boolean') patch.allowShell = body.allowShell;+ if (typeof body.maxDevices === 'number') patch.maxDevices = body.maxDevices;+ if (typeof body.idleDays === 'number') patch.idleDays = body.idleDays;+ if (Array.isArray(body.allowIps)) {+ const bad = body.allowIps.find((r) => !parseIpRule(String(r)));+ if (bad !== undefined) return c.json({ error: `“${bad}” is not an address or range (e.g. 203.0.113.7 or 100.64.0.0/10).` }, 400);+ patch.allowIps = body.allowIps.map(String);+ }+ const before = readRemoteSettings();+ const next = writeRemoteSettings(patch);+ const changes = (Object.keys(patch) as Array<keyof RemoteSettings>).filter((k) => JSON.stringify(before[k]) !== JSON.stringify(next[k]));+ if (changes.length) audit('remote.changed', { by: 'this computer', detail: changes.map((k) => `${k}: ${JSON.stringify(next[k])}`).join(', ') });+ return c.json(status());+});++security.get('/api/security/approvals', (c) => c.json({ pending: ownerApprovals().pending(), routes: approvalRoutes() }));++security.post('/api/security/approvals/:id', async (c) => {+ const body = (await c.req.json().catch(() => ({}))) as { decision?: unknown; by?: unknown };+ if (body.decision !== 'allow' && body.decision !== 'deny') return c.json({ error: 'decision must be "allow" or "deny"' }, 400);+ const by = typeof body.by === 'string' && /^[a-z -]{2,20}$/i.test(body.by) ? body.by : 'this computer';+ const a = ownerApprovals().decide(c.req.param('id'), body.decision, by);+ if (!a) return c.json({ error: 'That question was already answered or has expired.' }, 410);+ if (a.kind === 'action') audit(a.status === 'allowed' ? 'action.allowed' : 'action.denied', { who: a.who, ip: a.ip, detail: a.title, by });+ else if (a.status === 'denied') audit('pair.denied', { who: a.who, ip: a.ip, by });+ return c.json({ approval: a });+});++/** The asking device follows its own question (and only its own). */+security.get('/api/security/approvals/:id/status', (c) => {+ const a = ownerApprovals().get(c.req.param('id'));+ const me = principalKey(authenticateRequest(c));+ if (!a || a.kind !== 'action' || a.scope?.principal !== me) return c.json({ status: 'expired' }, 404);+ return c.json({ status: a.status, code: a.code, expiresAt: a.expiresAt });+});++security.post('/api/security/devices', async (c) => {+ const body = (await c.req.json().catch(() => ({}))) as { name?: unknown; platform?: unknown };+ try {+ const created = createDevice(body.name, body.platform ?? 'manual', 'this computer');+ audit('pair.local', { who: created.device.name, detail: 'token made on this computer' });+ return c.json(created);+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : 'Could not create the device' }, 409);+ }+});++security.delete('/api/security/devices/:id', (c) => {+ const id = c.req.param('id');+ const name = getDevice(id)?.name ?? id;+ if (!revokeDevice(id)) return c.json({ error: 'No such device' }, 404);+ closeStreams(`device:${id}`);+ audit('device.revoked', { who: name, by: 'this computer' });+ return c.json({ success: true });+});++security.delete('/api/security/devices', (c) => {+ const ids = revokeAllDevices();+ for (const id of ids) closeStreams(`device:${id}`);+ if (ids.length) audit('device.revoked', { who: `${ids.length} devices (all)`, by: 'this computer' });+ return c.json({ revoked: ids.length });+});++security.get('/api/security/audit', (c) => c.json({ entries: readAudit(Math.min(500, Math.max(1, Number(c.req.query('limit')) || 50))) }));++security.get('/api/security/check', (c) => {+ const findings = securityCheck({ lastRemote: lastRemoteRequest(), cloudConnected: cloudConnected() });+ return c.json({ summary: summarizeFindings(findings), findings });+});++export default security;diff --git a/src/web/api/system.ts b/src/web/api/system.tsindex 79616d97..37ba594c 100644--- a/src/web/api/system.ts+++ b/src/web/api/system.ts@@ -1,3 +1,4 @@+import { requireOwner } from '../owner-gate.js';import { Hono } from 'hono';import type { BaseProvider } from '../../providers/base.js';import { BUILDER_VERIFIED_NOTE, buildSkillDraft, draftProblem, type SkillDraft } from '../../skills/builder.js';@@ -101,6 +102,9 @@ system.post('/api/skills/install', async (c) => {} catch {return c.json({ success: false, error: 'invalid url' }, 400);}+ // A skill is instructions Mercury follows from then on: from another device, the owner decides.+ const wait = requireOwner(c, { id: `skills.install:${url}`, title: 'Install a skill from a web address', detail: url });+ if (wait) return wait;try {const loader = new SkillLoader();@@ -173,6 +177,8 @@ system.get('/api/permissions', (c) => {system.put('/api/permissions', async (c) => {const body = await c.req.json();+ const wait = requireOwner(c, { id: 'permissions.manifest', title: "Change what Mercury's shell, file and git tools may do" });+ if (wait) return wait;const manager = new PermissionManager();const current = manager.getManifest();const next: PermissionsManifest = {diff --git a/src/web/api/voice.ts b/src/web/api/voice.tsindex 3235aca9..2587507f 100644--- a/src/web/api/voice.ts+++ b/src/web/api/voice.ts@@ -1,3 +1,5 @@+import { trackStream } from '../../security/live-streams.js';+import { principalKey, principalOf } from '../middleware.js';import { Hono } from 'hono';import { voiceFeed, VOICE_ACTIONS, type VoiceAction } from '../../plugins/voice-feed.js';import { checkVoiceKey, VOICE_KEY_ENV, VOICE_VENDORS, type VoiceVendor } from '../../plugins/voice-check.js';@@ -43,7 +45,9 @@ voice.get('/api/voice/events', (c) => {const keepalive = setInterval(() => {try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }}, 15000);- c.req.raw.signal?.addEventListener('abort', () => { clearInterval(keepalive); unsubscribe(); });+ const cleanup = () => { clearInterval(keepalive); unsubscribe(); untrack(); };+ const untrack = trackStream(principalKey(principalOf(c)), () => { cleanup(); try { controller.close(); } catch { /* closed */ } });+ c.req.raw.signal?.addEventListener('abort', cleanup);},cancel() {},});diff --git a/src/web/api/workspace-ide.ts b/src/web/api/workspace-ide.tsindex 63bc239b..878ac436 100644--- a/src/web/api/workspace-ide.ts+++ b/src/web/api/workspace-ide.ts@@ -6,6 +6,10 @@ import { getMercuryHome, loadConfig } from '../../utils/config.js';import { generateText } from 'ai';import type { ProviderRegistry } from '../../providers/registry.js';import { resolveShell } from '../../utils/platform.js';+import { protectedReason, realInside } from '../../security/protected-paths.js';+import { isThisComputer } from '../middleware.js';+import { requireOwner } from '../owner-gate.js';+import { readRemoteSettings } from '../../security/remote-settings.js';let providerRegistry: ProviderRegistry | undefined;@@ -46,10 +50,15 @@ export function git(args: readonly string[], cwd?: string): string {}).trim();}-/** True when the path resolves inside the workspace (not merely shares its prefix). */+/**+ * True when the path resolves inside the workspace (not merely shares its+ * prefix), after following symlinks: a link in the workspace pointing at+ * ~/.ssh is outside it.+ */export function isInsideWorkspace(filePath: string, root: string = getWorkspaceRoot()): boolean {const rel = relative(resolve(root), resolve(root, filePath));- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));+ if (!(rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)))) return false;+ return realInside(resolve(root, filePath), root);}/**@@ -291,6 +300,8 @@ ide.put('/api/workspace/file', async (c) => {if (!isInsideWorkspace(fullPath, root)) {return c.json({ error: 'Path outside workspace' }, 403);}+ const off = protectedReason(fullPath, !isThisComputer(c));+ if (off) return c.json({ error: off }, 403);writeFileSync(fullPath, body.content, 'utf8');return c.json({ success: true, path: body.path });} catch (err: any) {@@ -306,6 +317,15 @@ ide.post('/api/terminal/exec', async (c) => {const body = await c.req.json<{ command: string; cwd?: string }>();try {if (!body.command?.trim()) return c.json({ error: 'command is required' }, 400);+ // A shell from another device: off unless the owner turned it on (/server),+ // and then every command waits for the owner's yes.+ if (!isThisComputer(c)) {+ if (!readRemoteSettings().allowShell) {+ return c.json({ error: 'The terminal is off for remote devices. The owner can turn it on with /server on the computer Mercury runs on.', remoteShellOff: true }, 403);+ }+ const wait = requireOwner(c, { id: `terminal.exec:${body.command.trim().slice(0, 200)}`, title: 'Run a shell command', detail: body.command.trim().slice(0, 300) });+ if (wait) return wait;+ }const root = getWorkspaceRoot();const cwd = body.cwd ? resolve(root, body.cwd) : root;diff --git a/src/web/auth.ts b/src/web/auth.tsindex d6946c38..97591e9e 100644--- a/src/web/auth.ts+++ b/src/web/auth.ts@@ -1,7 +1,7 @@-import { compareSync, hashSync, genSaltSync } from 'bcryptjs';+import { compare, compareSync, hashSync, genSaltSync } from 'bcryptjs';import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from 'node:fs';import { join } from 'node:path';-import { randomBytes } from 'node:crypto';+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';import { getMercuryHome, loadConfig } from '../utils/config.js';const SESSION_COOKIE = 'mercury_session';@@ -61,6 +61,15 @@ export function writeAttachToken(): void {}}+/** Constant-time check of a presented attach token. */+export function attachTokenMatches(presented: string): boolean {+ const expected = readAttachToken();+ if (!expected) return false;+ const a = Buffer.from(presented);+ const b = Buffer.from(expected);+ return a.length === b.length && timingSafeEqual(a, b);+}+export function readAttachToken(): string | null {try {const token = readFileSync(getAttachTokenPath(), 'utf-8').trim();@@ -127,17 +136,38 @@ export function setWebPassword(password: string): void {saveWebAuth(auth);}+// A hash to compare against when the username is wrong, so a wrong name+// takes as long as a wrong password (no "this user exists" timing signal).+const DUMMY_HASH = hashSync('mercury-dummy-password', 10);+export function authenticate(username: string, password: string): boolean {const auth = loadWebAuth();if (!auth) return false;- if (username !== auth.username) return false;try {- return compareSync(password, auth.password_hash);+ const ok = compareSync(password, username === auth.username ? auth.password_hash : DUMMY_HASH);+ return ok && username === auth.username;} catch {return false;}}+/** The same check without blocking the server while bcrypt runs (sign-in endpoints). */+export async function authenticateAsync(username: string, password: string): Promise<boolean> {+ const auth = loadWebAuth();+ if (!auth) return false;+ try {+ const ok = await compare(password, username === auth.username ? auth.password_hash : DUMMY_HASH);+ return ok && username === auth.username;+ } catch {+ return false;+ }+}++/** The username to sign in with (for the CLI's security screen). */+export function webUsername(): string | null {+ return loadWebAuth()?.username ?? null;+}+export function changePassword(currentPassword: string, newPassword: string): boolean {const auth = loadWebAuth();if (!auth) return false;@@ -162,13 +192,23 @@ export function createSessionToken(): string {}interface SessionEntry {- token: string;expiresAt: number;}+/**+ * Live browser sessions, by a SHA-256 of the token (the token itself is only+ * in the browser's cookie): a copied sessions file can't be replayed.+ */const sessions: Map<string, SessionEntry> = new Map();const SESSION_FILE = 'web-sessions.json';+const sessionHash = (token: string): string => createHash('sha256').update(token, 'utf8').digest('hex');++/** A short, non-secret key for a session (to find its open streams). */+export function sessionKey(token: string): string {+ return sessionHash(token).slice(0, 16);+}+function getSessionFilePath(): string {return join(getMercuryHome(), SESSION_FILE);}@@ -177,8 +217,8 @@ function persistSessions(): void {try {const dir = getMercuryHome();if (!existsSync(dir)) mkdirSync(dir, { recursive: true });- const entries = Object.fromEntries(sessions);- writeCredentialFile(getSessionFilePath(), JSON.stringify(entries, null, 2));+ const entries = Object.fromEntries([...sessions].map(([hash, e]) => [hash, { expiresAt: e.expiresAt }]));+ writeCredentialFile(getSessionFilePath(), JSON.stringify({ version: 2, sessions: entries }, null, 2));} catch {}}@@ -186,14 +226,16 @@ function restoreSessions(): void {try {const path = getSessionFilePath();if (!existsSync(path)) return;- const raw = readFileSync(path, 'utf-8');- const data = JSON.parse(raw) as Record<string, SessionEntry>;+ const raw = JSON.parse(readFileSync(path, 'utf-8')) as { version?: number; sessions?: Record<string, SessionEntry> } & Record<string, unknown>;const now = Date.now();- for (const [key, entry] of Object.entries(data)) {- if (entry.expiresAt > now) {- sessions.set(key, entry);- }+ // Version 1 kept the raw token as the key: hash it on the way in.+ const v2 = raw.version === 2 && raw.sessions && typeof raw.sessions === 'object';+ const entries = (v2 ? raw.sessions : raw) as Record<string, SessionEntry>;+ for (const [key, entry] of Object.entries(entries)) {+ if (!entry || typeof entry.expiresAt !== 'number' || entry.expiresAt <= now) continue;+ sessions.set(v2 ? key : sessionHash(key), { expiresAt: entry.expiresAt });}+ if (!v2) persistSessions();} catch {}}@@ -202,29 +244,45 @@ restoreSessions();export function createSession(): string {const token = createSessionToken();- sessions.set(token, {- token,- expiresAt: Date.now() + SESSION_MAX_AGE * 1000,- });+ sessions.set(sessionHash(token), { expiresAt: Date.now() + SESSION_MAX_AGE * 1000 });persistSessions();return token;}export function validateSession(token: string): boolean {- const entry = sessions.get(token);+ const hash = sessionHash(token);+ const entry = sessions.get(hash);if (!entry) return false;if (Date.now() > entry.expiresAt) {- sessions.delete(token);+ sessions.delete(hash);return false;}return true;}export function destroySession(token: string): void {- sessions.delete(token);+ sessions.delete(sessionHash(token));persistSessions();}+/** Sign every browser out (a password change), except `keep`; returns the keys of the sessions ended. */+export function destroyAllSessions(keep?: string): string[] {+ const keepHash = keep ? sessionHash(keep) : null;+ const ended: string[] = [];+ for (const hash of [...sessions.keys()]) {+ if (hash === keepHash) continue;+ sessions.delete(hash);+ ended.push(hash.slice(0, 16));+ }+ persistSessions();+ return ended;+}++export function sessionCount(): number {+ const now = Date.now();+ return [...sessions.values()].filter((e) => e.expiresAt > now).length;+}+export function getSessionCookieName(): string {return SESSION_COOKIE;}diff --git a/src/web/cors.ts b/src/web/cors.tsindex 2daf8751..c1c46085 100644--- a/src/web/cors.ts+++ b/src/web/cors.ts@@ -54,7 +54,7 @@ export function apiCors(extra: readonly string[] | undefined): MiddlewareHandlerreturn cors({origin: (origin) => (allowed.has(origin) ? origin : null),allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],- allowHeaders: ['Authorization', 'Content-Type', 'Accept', 'Last-Event-ID', 'Cache-Control'],+ allowHeaders: ['Authorization', 'Content-Type', 'Accept', 'Last-Event-ID', 'Cache-Control', 'X-Mercury-Approval'],exposeHeaders: ['Content-Type', 'Content-Disposition'],maxAge: 600,credentials: false,diff --git a/src/web/devices.ts b/src/web/devices.tsindex f7c6bd12..43b7c2ef 100644--- a/src/web/devices.ts+++ b/src/web/devices.ts@@ -2,15 +2,20 @@ 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';+import { readRemoteSettings } from '../security/remote-settings.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 web session? Sessions are cookie-shaped and end after a week;+ * a desktop app needs something it can keep in the OS keychain and present+ * as `Authorization: Bearer` from any address.+ *+ * Lifecycle: a remote device pairs only once the owner approves it+ * (owner-approvals), stops working after `idleDays` unused (/server), and+ * revoking it also closes its open event streams (live-streams).** Why not the attach token? That one is a per-boot, loopback-only secret* for `mercury attach` and must stay that way.@@ -31,6 +36,15 @@ export interface DeviceRecord {tokenHash: string;createdAt: string;lastSeenAt: string | null;+ /** The address it last connected from (as the tunnel reported it), and the app. */+ lastIp?: string;+ lastAgent?: string;+ /** Addresses it has connected from (newest last, up to 8): a new one is worth telling the owner. */+ knownIps?: string[];+ /** Who let it in: "cli" (made on this computer), "telegram", "desktop"… */+ approvedBy?: string;+ /** Set once by the upgrade that added idle expiry: the clock for old devices starts then. */+ idleSince?: string;}export interface DeviceSummary {@@ -39,6 +53,11 @@ export interface DeviceSummary {platform: string;createdAt: string;lastSeenAt: string | null;+ lastIp?: string;+ lastAgent?: string;+ approvedBy?: string;+ /** When it stops working if it isn't used (idle expiry), or null when it never does. */+ expiresAt: string | null;}interface DevicesFile {@@ -98,8 +117,35 @@ export function listDevices(): DeviceSummary[] {return readFile().devices.map(toSummary);}+/** The moment idle expiry counts from: last use, else when it was made (or the upgrade, for old devices). */+function idleFrom(d: DeviceRecord): number {+ return Math.max(...[d.lastSeenAt, d.createdAt, d.idleSince].map((t) => (t ? Date.parse(t) : 0)).filter((n) => Number.isFinite(n)));+}++function expiresAtOf(d: DeviceRecord, idleDays = readRemoteSettings().idleDays): number | null {+ return idleDays > 0 ? idleFrom(d) + idleDays * 86_400_000 : null;+}+function toSummary(d: DeviceRecord): DeviceSummary {- return { id: d.id, name: d.name, platform: d.platform, createdAt: d.createdAt, lastSeenAt: d.lastSeenAt };+ const exp = expiresAtOf(d);+ return {+ id: d.id, name: d.name, platform: d.platform, createdAt: d.createdAt, lastSeenAt: d.lastSeenAt,+ ...(d.lastIp ? { lastIp: d.lastIp } : {}), ...(d.lastAgent ? { lastAgent: d.lastAgent } : {}), ...(d.approvedBy ? { approvedBy: d.approvedBy } : {}),+ expiresAt: exp ? new Date(exp).toISOString() : null,+ };+}++/**+ * Devices made before idle expiry existed keep working: their clock starts+ * now, once, instead of expiring them on upgrade for being old.+ */+export function migrateDevices(now = Date.now()): number {+ const data = readFile();+ const old = data.devices.filter((d) => !d.idleSince);+ if (!old.length) return 0;+ for (const d of old) d.idleSince = new Date(now).toISOString();+ writeFile(data);+ return old.length;}export interface CreatedDevice {@@ -109,7 +155,6 @@ export interface CreatedDevice {}const MAX_NAME_LENGTH = 64;-const MAX_DEVICES = 200;export function normalizeDeviceName(name: unknown): string {// eslint-disable-next-line no-control-regex -- strips control characters on purpose@@ -122,10 +167,11 @@ export function normalizePlatform(platform: unknown): string {return p || 'unknown';}-export function createDevice(name: unknown, platform?: unknown): CreatedDevice {+export function createDevice(name: unknown, platform?: unknown, approvedBy?: string): CreatedDevice {const data = readFile();- if (data.devices.length >= MAX_DEVICES) {- throw new Error(`Too many devices (${MAX_DEVICES}); revoke one first`);+ const max = readRemoteSettings().maxDevices;+ if (data.devices.length >= max) {+ throw new Error(`This Mercury already has ${data.devices.length} devices (the limit is ${max}). Revoke one, or raise the limit with /server.`);}let id = randomBytes(4).toString('hex');while (data.devices.some((d) => d.id === id)) id = randomBytes(4).toString('hex');@@ -137,6 +183,8 @@ export function createDevice(name: unknown, platform?: unknown): CreatedDevice {tokenHash: hashSecret(secret),createdAt: new Date().toISOString(),lastSeenAt: null,+ idleSince: new Date().toISOString(),+ ...(approvedBy ? { approvedBy } : {}),};data.devices.push(record);writeFile(data);@@ -158,23 +206,79 @@ export function looksLikeDeviceToken(token: string): boolean {return TOKEN_RE.test(token);}+export type DeviceCheck =+ | { ok: true; device: DeviceSummary }+ | { ok: false; expired?: DeviceSummary };+/**- * 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.+ * Resolve a bearer token to its device. Constant-time on the secret; the id+ * lookup is by equality, which only reveals whether an id exists — ids are+ * not secret. A device unused for longer than the idle limit has expired:+ * its record goes (so it can't come back), and the caller is told so it can+ * ask the owner to approve it again.*/-export function validateDeviceToken(token: string): DeviceSummary | null {+export function checkDeviceToken(token: string, now = Date.now()): DeviceCheck {const match = TOKEN_RE.exec(token);- if (!match) return null;+ if (!match) return { ok: false };const [, id, secret] = match;const data = readFile();const record = data.devices.find((d) => d.id === id);- if (!record) return null;+ if (!record) return { ok: false };const expected = Buffer.from(record.tokenHash, 'hex');const actual = Buffer.from(hashSecret(secret), 'hex');- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return { ok: false };+ const exp = expiresAtOf(record);+ if (exp !== null && now > exp) {+ const summary = toSummary(record);+ data.devices = data.devices.filter((d) => d.id !== id);+ try { writeFile(data); } catch { /* still refused */ }+ return { ok: false, expired: summary };+ }touchLastSeen(data, record);- return toSummary(record);+ return { ok: true, device: toSummary(record) };+}++/** Resolve a bearer token to its device, or null (expired counts as no). */+export function validateDeviceToken(token: string): DeviceSummary | null {+ const r = checkDeviceToken(token);+ return r.ok ? r.device : null;+}++/**+ * Where a device connected from. Returns true when it's an address this+ * device hasn't used before (and it has used others): worth telling the owner.+ */+export function noteDeviceSeen(id: string, ip: string | null, agent: string | null): boolean {+ const data = readFile();+ const d = data.devices.find((x) => x.id === id);+ if (!d) return false;+ const ua = agent ? agent.replace(/[^\x20-\x7e]/g, '').slice(0, 120) : undefined;+ const known = d.knownIps ?? [];+ const isNew = !!ip && !known.includes(ip);+ if (!isNew && d.lastIp === (ip ?? d.lastIp) && d.lastAgent === (ua ?? d.lastAgent)) return false;+ if (ip) {+ d.lastIp = ip;+ d.knownIps = [...known.filter((k) => k !== ip), ip].slice(-8);+ }+ if (ua) d.lastAgent = ua;+ try { writeFile(data); } catch { /* cosmetic */ }+ return isNew && known.length > 0;+}++/** Revoke every device; how many. */+export function revokeAllDevices(): string[] {+ const data = readFile();+ const ids = data.devices.map((d) => d.id);+ if (!ids.length) return [];+ data.devices = [];+ writeFile(data);+ for (const id of ids) lastSeenWrites.delete(id);+ return ids;+}++export function getDevice(id: string): DeviceSummary | null {+ const d = readFile().devices.find((x) => x.id === id);+ return d ? toSummary(d) : null;}function touchLastSeen(data: DevicesFile, record: DeviceRecord): void {diff --git a/src/web/lifecycle-restart.test.ts b/src/web/lifecycle-restart.test.tsindex e269edbf..117fb1d6 100644--- a/src/web/lifecycle-restart.test.ts+++ b/src/web/lifecycle-restart.test.ts@@ -10,11 +10,12 @@ import lifecycle, { setRestartSpawner } from './api/lifecycle.js';* must offer the restart and the CLI must do it when the file changed.*/describe('POST /api/restart', () => {- it('is loopback-only and hands off to a detached restart', async () => {+ it('asks the owner from another device, and hands off to a detached restart here', async () => {let spawned = 0;setRestartSpawner(() => { spawned++; return true; });const remote = await lifecycle.request('http://127.0.0.1:6174/api/restart', { method: 'POST' }, { incoming: { socket: { remoteAddress: '10.0.0.7' } } });- expect(remote.status).toBe(403);+ expect(remote.status).toBe(428);+ expect(spawned).toBe(0);const local = await lifecycle.request('http://127.0.0.1:6174/api/restart', { method: 'POST' }, { incoming: { socket: { remoteAddress: '127.0.0.1' } } });expect(local.status).toBe(202);expect(spawned).toBe(1);diff --git a/src/web/middleware.ts b/src/web/middleware.tsindex d2f9d96e..ccd04db4 100644--- a/src/web/middleware.ts+++ b/src/web/middleware.ts@@ -1,29 +1,40 @@import { Context, Next } from 'hono';import { getCookie } from 'hono/cookie';-import { validateSession, getSessionCookieName, readAttachToken } from './auth.js';-import { looksLikeDeviceToken, validateDeviceToken } from './devices.js';+import { attachTokenMatches, getSessionCookieName, sessionKey, validateSession } from './auth.js';+import { checkDeviceToken, looksLikeDeviceToken, noteDeviceSeen } from './devices.js';+import { requestOrigin, hostName, type RequestOrigin } from '../security/request-origin.js';+import { readRemoteSettings } from '../security/remote-settings.js';+import { ipAllowed } from '../security/ip-match.js';+import { audit } from '../security/audit.js';+import { loadConfig } from '../utils/config.js';+import { logger } from '../utils/logger.js';-const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout', '/api/auth/token', '/api/health']);+const PUBLIC_PATHS = new Set(['/login', '/api/auth/login', '/api/auth/logout', '/api/auth/token', '/api/auth/token/pending', '/api/health']);++export type Principal =+ | { kind: 'session'; key: string; via: 'cookie' | 'bearer' }+ | { kind: 'attach' }+ | { kind: 'device'; deviceId: string; deviceName: string };++const origins = new WeakMap<Request, RequestOrigin>();+const principals = new WeakMap<Request, Principal | null>();+const expiredDevices = new WeakMap<Request, { name: string }>();++/** Where this request really comes from (see security/request-origin.ts). Computed once per request. */+export function originOf(c: Context): RequestOrigin {+ let o = origins.get(c.req.raw);+ if (!o) { o = requestOrigin(c); origins.set(c.req.raw, o); }+ return o;+}/**- * The attach token is only honored from loopback connections. Defense in- * depth: the secret itself is an owner-only file, but a matching token from- * a non-loopback peer must not open the API even if a future bug leaks it.+ * From this machine, not through a tunnel or proxy. (Kept under its old name:+ * it used to look only at the socket, which every same-host tunnel passes.)*/export function isLoopbackRequest(c: Context): boolean {- try {- const address: string = (c.env as any)?.incoming?.socket?.remoteAddress || '';- return ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address);- } catch {- return false;- }+ return originOf(c).local;}-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;@@ -36,38 +47,174 @@ export function bearerToken(c: Context): string | 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.+ * - attach token: Bearer, this machine only (never through a tunnel).*/export function authenticateRequest(c: Context): Principal | null {+ if (principals.has(c.req.raw)) return principals.get(c.req.raw) ?? null;+ const p = resolvePrincipal(c);+ principals.set(c.req.raw, p);+ return p;+}++function resolvePrincipal(c: Context): Principal | null {const cookieToken = getCookie(c, getSessionCookieName());- if (cookieToken && validateSession(cookieToken)) return { kind: 'session' };+ if (cookieToken && validateSession(cookieToken)) return { kind: 'session', key: sessionKey(cookieToken), via: 'cookie' };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;+ const r = checkDeviceToken(bearer);+ if (r.ok) return { kind: 'device', deviceId: r.device.id, deviceName: r.device.name };+ if (r.expired) expiredDevices.set(c.req.raw, { name: r.expired.name });+ return 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' };+ if (validateSession(bearer)) return { kind: 'session', key: sessionKey(bearer), via: 'bearer' };+ // Attach clients (`mercury attach`, Mercury Desktop on this machine)+ // authenticate with the machine-local token instead of the web login.+ const o = originOf(c);+ if (o.socketLocal && !o.proxied && attachTokenMatches(bearer)) return { kind: 'attach' };return null;}+/** The principal of an authenticated request (set by authGuard). */+export function principalOf(c: Context): Principal | null {+ return authenticateRequest(c);+}++/** "device:<id>" / "session:<key>" / "attach": who to close streams for, who an approval is for. */+export function principalKey(p: Principal | null): string | null {+ if (!p) return null;+ return p.kind === 'device' ? `device:${p.deviceId}` : p.kind === 'session' ? `session:${p.key}` : 'attach';+}++/** A name for the security log and approval questions. */+export function principalLabel(p: Principal | null): string {+ if (!p) return 'someone';+ return p.kind === 'device' ? p.deviceName : p.kind === 'session' ? 'a browser' : 'this computer';+}++/**+ * The caller is on this computer: Mercury Desktop or the CLI here (attach+ * token), or a browser here that signed in (not through a tunnel).+ */+export function isThisComputer(c: Context): boolean {+ const p = authenticateRequest(c);+ const o = originOf(c);+ if (p?.kind === 'attach') return true;+ if (p?.kind === 'session') return o.local;+ // No principal on a protected route only happens when a route is called+ // without authGuard in front (in-process route tests, which also carry no+ // socket): then the origin decides, and no socket at all counts as here.+ if (p === null) return o.local || !hasSocket(c);+ return false;+}++function hasSocket(c: Context): boolean {+ return !!(c.env as { incoming?: { socket?: unknown } } | undefined)?.incoming?.socket;+}++/** Only on this computer; otherwise the 403 to return. */+export function requireThisComputer(c: Context, what = 'This'): Response | null {+ if (isThisComputer(c)) return null;+ return c.json({ error: `${what} only works on the computer Mercury runs on.`, thisComputerOnly: true }, 403);+}++function allowedHosts(): Set<string> {+ try {+ return new Set((loadConfig().web?.allowedHosts ?? []).map((h) => hostName(String(h))));+ } catch {+ return new Set();+ }+}++const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);++/** A cookie-authenticated change must come from a page this server (or an allowed app) served. */+function crossSite(c: Context): boolean {+ const origin = c.req.header('origin') ?? (() => { try { return new URL(c.req.header('referer') ?? '').origin; } catch { return ''; } })();+ if (!origin || origin === 'null') return true;+ try {+ const host = c.req.header('x-forwarded-host') || c.req.header('host') || '';+ return new URL(origin).host.toLowerCase() !== host.toLowerCase();+ } catch {+ return true;+ }+}++/** The last request from outside this computer: what the security screen says about the tunnel. */+let lastRemote: { at: number; proxied: boolean; clientIpKnown: boolean; ip: string } | null = null;+export function lastRemoteRequest(): typeof lastRemote { return lastRemote; }++const blockedLogged = new Map<string, number>();+function logBlocked(ip: string, detail: string): void {+ const now = Date.now();+ if ((blockedLogged.get(ip) ?? 0) > now - 10 * 60_000) return;+ blockedLogged.set(ip, now);+ if (blockedLogged.size > 1000) blockedLogged.clear();+ audit('device.blocked', { ip, detail });+}++/** Tell the owner, once per new address per device. */+let newLocationHook: ((device: { id: string; name: string }, ip: string) => void) | null = null;+export function onDeviceNewLocation(fn: typeof newLocationHook): void { newLocationHook = fn; }+export async function authGuard(c: Context, next: Next) {const path = new URL(c.req.url).pathname;+ const origin = originOf(c);+ const api = path.startsWith('/api/');++ // DNS rebinding: a request straight to this machine must name this machine.+ // (Through a tunnel the Host is its public name; that's what `proxied` covers.)+ if (origin.socketLocal && !origin.proxied && !origin.hostLocal && !allowedHosts().has(hostName(c.req.header('host') || new URL(c.req.url).host))) {+ return api ? c.json({ error: 'Unknown host. Add it to web.allowedHosts if you put Mercury behind your own proxy.' }, 421) : c.text('Unknown host', 421);+ }++ // Remote clients: remote access has to be on, and their address allowed.+ if (!origin.local) {+ lastRemote = { at: Date.now(), proxied: origin.proxied, clientIpKnown: origin.clientIpKnown, ip: origin.clientIp };+ const remote = readRemoteSettings();+ if (!remote.enabled) {+ logBlocked(origin.clientIp, 'remote access is off');+ return api ? c.json({ error: 'Remote access is turned off on this Mercury. Turn it on with /server on the computer it runs on.', remoteOff: true }, 403) : c.text('Remote access is turned off on this Mercury.', 403);+ }+ if (remote.allowIps.length && (!origin.clientIpKnown || !ipAllowed(origin.clientIp, remote.allowIps))) {+ logBlocked(origin.clientIp, origin.clientIpKnown ? 'address not allowed' : 'address unknown (the tunnel did not pass it)');+ return api ? c.json({ error: 'This address is not allowed to connect to this Mercury.', addressBlocked: true }, 403) : c.text('This address is not allowed to connect.', 403);+ }+ }+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')) {return next();}if (PUBLIC_PATHS.has(path)) {+ // The sign-in form posts from its own page; anything else posting a password is forged.+ if (!SAFE_METHODS.has(c.req.method) && path === '/api/auth/login' && crossSite(c)) return c.text('Forbidden', 403);return next();}- if (path.startsWith('/api/')) {- if (authenticateRequest(c)) {- return next();+ if (api) {+ const principal = authenticateRequest(c);+ if (!principal) {+ const expired = expiredDevices.get(c.req.raw);+ if (expired) {+ audit('device.expired', { who: expired.name, ip: origin.clientIp });+ return c.json({ error: `This device wasn't used for ${readRemoteSettings().idleDays} days, so it was signed out. Sign in again; the owner approves it once more.`, expired: true }, 401);+ }+ return c.json({ error: 'Unauthorized' }, 401);+ }+ // Cookies ride along with any request the browser makes; a change needs a same-site page.+ if (principal.kind === 'session' && principal.via === 'cookie' && !SAFE_METHODS.has(c.req.method) && crossSite(c)) {+ return c.json({ error: 'Cross-site request refused' }, 403);}- return c.json({ error: 'Unauthorized' }, 401);+ if (principal.kind === 'device') {+ try {+ const fresh = noteDeviceSeen(principal.deviceId, origin.clientIpKnown ? origin.clientIp : null, c.req.header('user-agent') ?? null);+ if (fresh && origin.clientIpKnown) {+ audit('device.new-location', { who: principal.deviceName, ip: origin.clientIp });+ newLocationHook?.({ id: principal.deviceId, name: principal.deviceName }, origin.clientIp);+ }+ } catch { /* bookkeeping only */ }+ }+ return next();}const token = getCookie(c, getSessionCookieName());if (!token || !validateSession(token)) {@@ -79,11 +226,11 @@ export async function authGuard(c: Context, next: Next) {export async function errorHandler(c: Context, next: Next) {try {return await next();- } catch (err: any) {- console.error('[web] Error:', err.message);- if (c.req.url.includes('/api/')) {- return c.json({ error: err.message || 'Internal server error' }, 500);- }+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ logger.error({ err: message, path: new URL(c.req.url).pathname }, 'Web request failed');+ // The detail stays in the log: error text can name files, keys and internals.+ if (c.req.url.includes('/api/')) return c.json({ error: 'Internal server error' }, 500);return c.html('<h1>500 — Internal Server Error</h1>', 500);}}diff --git a/src/web/owner-gate.ts b/src/web/owner-gate.tsnew file mode 100644index 00000000..ab11ef33--- /dev/null+++ b/src/web/owner-gate.ts@@ -0,0 +1,67 @@+import type { Context } from 'hono';+import { audit } from '../security/audit.js';+import { ownerApprovals } from '../security/owner-approvals.js';+import { isThisComputer, originOf, principalKey, principalLabel, principalOf } from './middleware.js';++/**+ * Sensitive actions from a remote device: things that could outlive the+ * device's access or hand out secrets (a shell, Allow All, a new channel+ * admin, Cloud sign-in, a skill from a URL…). On this computer they just+ * run. From anywhere else they wait for the owner: the first call returns+ * 428 with an approval id and code; once the owner allows it (on their+ * messaging channel, the CLI or Mercury Desktop here), the client repeats the+ * call with `X-Mercury-Approval: <id>`, which works once, for that device+ * and that action.+ */++export const ACTION_APPROVAL_TTL_MS = 10 * 60_000;++/** Where approvals reach the owner ("Telegram", "this computer"), for the message the device shows. */+let routes: () => string[] = () => ['this computer'];+export function setApprovalRoutes(fn: () => string[]): void { routes = fn; }+export function approvalRoutes(): string[] {+ try { return routes(); } catch { return ['this computer']; }+}++export function whereToApprove(): string {+ const r = approvalRoutes();+ return r.length > 1 ? `${r.slice(0, -1).join(', ')} or ${r[r.length - 1]}` : r[0] ?? 'this computer';+}++export interface SensitiveAction {+ /** Stable id: what the grant is for ("terminal.exec", "permissions.allow-all"). */+ id: string;+ /** For the owner, in plain words: "Run a shell command". */+ title: string;+ detail?: string;+}++/** Null = go ahead; otherwise the response to return (428 waiting for the owner, 403 denied). */+export function requireOwner(c: Context, action: SensitiveAction): Response | null {+ if (isThisComputer(c)) return null;+ const principal = principalOf(c);+ const key = principalKey(principal) ?? 'unknown';+ const who = principalLabel(principal);+ const ip = originOf(c).clientIpKnown ? originOf(c).clientIp : undefined;+ const approvals = ownerApprovals();+ const presented = c.req.header('x-mercury-approval');+ if (presented) {+ if (approvals.consume(presented, { principal: key, action: action.id })) {+ audit('action.allowed', { who, ip, detail: action.title });+ return null;+ }+ const known = approvals.get(presented);+ if (known && known.status === 'denied') return c.json({ error: `The owner said no to: ${action.title}.`, approvalDenied: true }, 403);+ if (known && known.status === 'pending') return c.json({ error: `Still waiting for the owner to approve: ${action.title}.`, approvalRequired: true, approvalId: known.id, code: known.code, where: whereToApprove() }, 428);+ }+ const a = approvals.request({ kind: 'action', title: action.title, detail: action.detail, who, ip, scope: { principal: key, action: action.id } }, ACTION_APPROVAL_TTL_MS);+ audit('action.requested', { who, ip, detail: action.title });+ return c.json({+ error: `Waiting for the owner to approve: ${action.title}. Approve it on ${whereToApprove()} (code ${a.code}), then try again.`,+ approvalRequired: true,+ approvalId: a.id,+ code: a.code,+ where: whereToApprove(),+ expiresAt: a.expiresAt,+ }, 428);+}diff --git a/src/web/server.ts b/src/web/server.tsindex 910231f1..f70ffd6c 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -32,6 +32,9 @@ import mcpRoutes, { setMcpManager } from './api/mcp.js';import pluginRoutes from './api/plugins.js';import voiceRoutes from './api/voice.js';import deviceRoutes from './api/devices.js';+import securityRoutes from './api/security.js';+import { bodyLimit } from 'hono/body-limit';+import { migrateDevices } from './devices.js';import { BoardManager } from '../core/board-manager.js';import { isBetterSqlite3Available } from '../memory/second-brain-db.js';@@ -89,6 +92,19 @@ const spaIndexPath = join(uiDir, 'index.html');const spaAvailable = existsSync(spaIndexPath);app.use('*', errorHandler);+// Baseline headers on everything; pages also refuse to be framed (clickjacking).+app.use('*', async (c, next) => {+ await next();+ c.res.headers.set('X-Content-Type-Options', 'nosniff');+ c.res.headers.set('Referrer-Policy', 'no-referrer');+ if ((c.res.headers.get('Content-Type') ?? '').startsWith('text/html')) {+ c.res.headers.set('X-Frame-Options', 'DENY');+ if (!c.res.headers.has('Content-Security-Policy')) c.res.headers.set('Content-Security-Policy', "frame-ancestors 'none'");+ }+});+// Sign-in bodies are tiny: refuse big ones before reading them (they arrive without a credential).+app.use('/api/auth/*', bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: 'Request too large' }, 413) }));+app.use('/login', bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.text('Request too large', 413) }));// 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.@@ -119,6 +135,7 @@ app.route('/', mcpRoutes);app.route('/', pluginRoutes);app.route('/', voiceRoutes);app.route('/', deviceRoutes);+app.route('/', securityRoutes);// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──app.get('/vendor/*', (c) => {@@ -277,6 +294,8 @@ process.on('unhandledRejection', (reason: any) => {export function startWebServer(): { port: number; url: string } {const port = getWebPort();initWebAuth();+ // Devices from before idle expiry start their clock now (they keep working).+ try { migrateDevices(); } catch { /* checked again next start */ }if (spaAvailable) {logger.info(`React UI loaded from: ${uiDir}`);diff --git a/website/docs/integrations/web-dashboard.mdx b/website/docs/integrations/web-dashboard.mdxindex 189e6427..4a43ba4e 100644--- a/website/docs/integrations/web-dashboard.mdx+++ b/website/docs/integrations/web-dashboard.mdx@@ -28,10 +28,7 @@ The server binds to `127.0.0.1` only and is not exposed to the network. The webThe dashboard is protected by username/password authentication.-**Default credentials:**--- Username: `mercury`-- Password: `Mercury@123`+There is no default password. `mercury setup` asks you for one (at least 10 characters) or generates a strong one and shows it once. The username is `mercury`. Lost it? Run `mercury web-reset-password`.You will be redirected to `/login` for any unauthenticated request. After logging in, an HTTP-only session cookie is set. Sign out from **Settings → Account** or by closing the session in your browser.diff --git a/website/docs/reference/configuration.mdx b/website/docs/reference/configuration.mdxindex f48d11ed..278fba8d 100644--- a/website/docs/reference/configuration.mdx+++ b/website/docs/reference/configuration.mdx@@ -26,8 +26,8 @@ Add to `~/.mercury/mercury.yaml`:web:enabled: trueport: 6174 # default- username: mercury- password: Mercury@123```-Or use environment variables: `MERCURY_PORT`, `MERCURY_WEB_USER`, `MERCURY_WEB_PASS`.\ No newline at end of file+The sign-in password is set during `mercury setup` (or `mercury web-reset-password`) and stored as a bcrypt hash, never in this file. The port can also come from `MERCURY_PORT`.++Remote access (other devices, the IP allow-list, device limits) is managed with `/server` in the terminal or `mercury server`.\ No newline at end of file