Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(security): /server, mercury server, doctor --security, and the desktop side of approvals

Salman Qureshi9923e350a5aa
diff --git a/DECISIONS.md b/DECISIONS.md
index b3650305..1c12eea5 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -345,3 +345,17 @@
- **Context**: The daemon runs from the home folder (so it doesn't write into a repo), and a chat's tools resolve paths against that folder, so every file a chat made without a full path landed loose in `~` (`how-to-programming-research.md`, `open-source-articles-….txt`). Models also wrote absolute home paths, because the prompt said the working directory was `~`. The artifact store's copies under `~/.mercury/artifacts` are for the apps, not for browsing, and research reports went to the hidden `~/.mercury/research`.
- **Decision**: One visible output folder, `~/mercury-artifacts` (the owner's choice of name; `artifacts.outputDir` changes it, `~` paths allowed): `Research/` for reports, and `Chats/<date> <chat title or its first words>/` for each chat that makes something. A normal chat turn whose working directory would be the home folder works in its chat's folder instead (tools, `run_command`, and the prompt's "Working directory", plus one line telling the model to keep files there unless the owner names another place). Not changed: Code sessions and workspaces (their project folder), a terminal opened inside a project (its folder), bots (their own folders), internal turns, and any path the owner gives. A chat's folder is named once and recorded in `~/.mercury/artifacts/chat-folders.json`, so a title generated later never moves files; same-name chats get "(2)". The folder is created when the turn starts and removed when it ends if nothing was saved (a lone `.DS_Store` counts as empty), so there are no empty folders. `GET /api/artifacts/folder` reports the folder and files Mercury made that sit loose in the home folder; `POST /api/artifacts/folder/tidy` (this computer only) moves those into their chats' folders and updates the artifact records, so Open and Show in Finder still work. It moves only files in the artifact store, never anything else in the home folder. The desktop Artifacts view shows where files are saved, has Open folder, and offers the move once.
- **Consequence**: The home folder stays clean, and what Mercury made is grouped the way the owner remembers it, by conversation. A relative path in a normal chat ("read notes.md") now means the chat's folder, not `~`; full paths and `~/…` are unaffected. Not here: moving files written before the artifact store existed (Mercury can't know it made them), and per-bot output under the same folder (bots keep `~/.mercury/bots/<id>`).
+
+## ADR-035: Remote access the owner controls — this computer is the only "local", new devices and sensitive remote actions need the owner
+
+- **Context**: Mercury binds `127.0.0.1`, so remote access always goes through a same-host tunnel or proxy, and those connect from 127.0.0.1. Every "this machine only" gate trusted the socket address, so through a tunnel any request was local: plugin install (code execution), restart, export-anywhere, and the attach token was honoured. Any device token or session also had `/api/terminal/exec` (a shell with no approval), a workspace root settable to `/` (read and write any file, including planting a token in `devices.json`), Allow All and the permissions manifest, full-tier bots, skill installs from any URL, channel admin and token changes, Cloud sign-in, and a provider "check" that sent the saved key to any base URL. Pairing needed only the password, with no approval or notice; tokens never expired; revoking left open streams running; any device could revoke all others; a password change revoked nothing. The browser sign-in had no attempt limit and ran bcrypt synchronously. There was no CSRF or Host check, no audit trail, and the setup wizard claimed a default password (`Mercury@123`) it never set.
+- **Decision**:
+ - **Origin** (`security/request-origin.ts`): local means a loopback socket **and** no proxy/tunnel header (`Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP`, `Tailscale-*`…) **and** a localhost Host. The client address is the proxy's right-most `X-Forwarded-For` entry (or `CF-Connecting-IP`…), or a direct peer's socket. "This computer" for an action means the attach token (Mercury Desktop / the CLI here; never honoured through a tunnel) or a browser session from a local origin. A direct request naming another host is refused (421, DNS rebinding) unless it's in `web.allowedHosts`.
+ - **Remote settings** (`~/.mercury/remote.json`, read live): `enabled` (default on, so existing setups keep working), `allowIps` (addresses/CIDR ranges; with a list set, a client whose address the tunnel hid is refused, fail closed), `allowShell` (default off), `maxDevices` (10), `idleDays` (30; devices from before this change start their clock at upgrade).
+ - **Owner approvals** (`security/owner-approvals.ts`): a question with a 5-character code, answered once by the owner, never by the device that asked; unanswered in 10 minutes = no. Delivered to every connected messaging channel ("approve K7Q2M" / "deny K7Q2M", accepted only from an admin of that chat), to the CLI here, and to Mercury Desktop on this computer (an `owner_approval` event sent only to activity streams opened from this computer; Approve/Deny calls `/api/security/approvals/:id`, this-computer only).
+ - **Pairing**: `POST /api/auth/token` from this computer issues a token at once; from anywhere else it returns 202 `{ pairingId, pollToken, code, where }` and the client polls `POST /api/auth/token/pending` (long poll) until approved (the token, once), denied or expired.
+ - **Sensitive remote actions** (`web/owner-gate.ts`) return 428 `{ approvalId, code, where }`; once allowed, the same device repeats the call with `X-Mercury-Approval` (one use, that device, that action). Gated: terminal exec (and off entirely unless `allowShell`), workspace root, Allow All on, the permissions manifest, operator/full bot tiers, raw bot permissions, bot imports, skills from a URL, plugins, channel settings/tokens, letting someone in or promoting on a channel, Signal linking, Cloud sign-in, a provider base URL change without a new key, restart, password and username changes, revoking another device, board working folders. Mercury Cloud's `permission.mode allow-all` and `skill.install` ask the owner the same way.
+ - **Lifecycle**: devices record last address and app and known addresses (a new one tells the owner); expired devices get 401 `{ expired }`; revoke and logout close the principal's open SSE streams (`security/live-streams.ts`); a password change signs other browsers out and can revoke all devices; the device limit is enforced before the owner is asked.
+ - **Hardening**: file endpoints follow symlinks and refuse Mercury's credentials always and keys/shell start-up files for remote callers; Mercury's own file and shell tools can't touch its login files; sign-in is limited per client on both endpoints (this computer never locked out), bcrypt is async with no username timing signal; sessions are stored hashed and cookies are `Secure` over https; cookie-authenticated changes need a same-origin Origin; nosniff/Referrer-Policy everywhere and `frame-ancestors 'none'` on pages; 64 KB body limit on sign-in; generic 500s; the provider check never sends the saved key to a different base URL; Discord and Slack approval buttons check who clicked.
+ - **Owner tools**: `/server` (terminal chat; also Mercury Desktop and attached terminals on this computer), `mercury server` (through the running Mercury when it's up, directly otherwise), `mercury doctor --security` and a one-line summary on every doctor run, the security log `~/.mercury/security/audit.jsonl`, and `/api/security/*`. Feature flag `security.remote`.
+- **Consequence**: Through a tunnel, a remote device can do what the owner does in chat (subject to the permission mode), but it can't escalate, persist past revocation, or read secrets without the owner saying yes on a device they hold. Pairing a new device takes one tap. Known limits: a proxy that adds no forwarding header and rewrites Host to localhost looks local (the attach token still guards the most sensitive operations, and the docs/security check say to configure forwarding headers); an IP allow-list needs a tunnel that passes the client address; Ask Me prompts are answered by whoever is using the session, so a paired device is trusted like the owner while paired. Follow-ups: a Security section in Mercury Desktop's settings, QR pairing, per-device scopes (read-only devices), and the full remote-access docs.
diff --git a/SECURITY.md b/SECURITY.md
index 84334ab5..4b887da5 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -50,9 +50,34 @@ Out of scope:
- The content and behaviour of skills you install yourself.
- Attacks that require an already-compromised host account or the Mercury
config directory (`~/.mercury`), or a dashboard deliberately exposed beyond
- `127.0.0.1` without a reverse proxy and authentication.
+ `127.0.0.1` without a tunnel or proxy and authentication.
+- What a device you approved does while it is approved (revoke it with
+ `/server`).
- A model being persuaded to *ask* for something that you then approve.
+## Remote access
+
+Mercury listens on `127.0.0.1` only; other devices reach it through a tunnel
+or VPN you set up (Tailscale Serve, Cloudflare Tunnel…). What protects it then
+(ADR-035 in `DECISIONS.md`):
+
+- **Only this computer counts as local.** A request is local only when it
+ comes straight from this machine, with no proxy headers and a localhost
+ Host. Everything through a tunnel is remote, even though the tunnel itself
+ connects from 127.0.0.1.
+- **New devices need your approval.** Signing in from another device asks
+ you (on your Telegram/WhatsApp/Discord/Slack/Signal chat, or `/server` and
+ Mercury Desktop on this computer) before a token is issued. Unused devices
+ expire after 30 days; revoking one closes its live connections.
+- **A paired device is trusted like you, but can't make itself permanent.**
+ Actions that could outlive its access or hand out secrets — the terminal,
+ Allow All, the workspace folder, Mercury's permissions, powerful bots,
+ skills from a URL, plugins, channel tokens and admins, Cloud sign-in, a
+ provider's server address, restart, the password — wait for your approval.
+- **`/server`** (or `mercury server`) turns remote access off, limits it to
+ addresses you list, and manages devices; `mercury doctor --security` checks
+ the setup.
+
## A note on the permission model
Mercury's "Ask Me" mode is the real security boundary: risky commands and
diff --git a/apps/desktop/src/api/approval.test.ts b/apps/desktop/src/api/approval.test.ts
new file mode 100644
index 00000000..2077da88
--- /dev/null
+++ b/apps/desktop/src/api/approval.test.ts
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiError, configureApi, http, setApprovalHandler } from "./client";
+import { insecureRemote } from "~/shell/AddRemote";
+
+vi.mock("~/shell/tauri", () => ({ desktop: {} }));
+
+const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+
+afterEach(() => { setApprovalHandler(null); vi.unstubAllGlobals(); });
+
+describe("a remote Mercury that asks its owner first", () => {
+ it("waits for the approval, then repeats the request once with it", async () => {
+ configureApi({ baseUrl: "https://m.example", token: "mdt_x" });
+ const calls: Array<Record<string, string>> = [];
+ vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => {
+ const headers = init.headers as Record<string, string>;
+ calls.push(headers);
+ return headers["X-Mercury-Approval"] === "ap1" ? json(200, { ok: true }) : json(428, { approvalRequired: true, approvalId: "ap1", code: "K7Q2M", where: "Telegram", error: "Waiting for the owner to approve: Turn on Allow All." });
+ }));
+ const seen: string[] = [];
+ setApprovalHandler(async (n) => { seen.push(`${n.code}@${n.where}`); return true; });
+ expect(await http.put("/api/chat/settings", { bypassPermissions: true })).toEqual({ ok: true });
+ expect(seen).toEqual(["K7Q2M@Telegram"]);
+ expect(calls).toHaveLength(2);
+ expect(calls[1]["X-Mercury-Approval"]).toBe("ap1");
+ });
+
+ it("a denial is an error that says so, and nothing is repeated", async () => {
+ configureApi({ baseUrl: "https://m.example", token: "mdt_x" });
+ const fetchMock = vi.fn(async () => json(428, { approvalRequired: true, approvalId: "ap2", code: "AAAAA", where: "this computer", error: "Waiting…" }));
+ vi.stubGlobal("fetch", fetchMock);
+ setApprovalHandler(async () => false);
+ await expect(http.post("/api/terminal/exec", { command: "ls" })).rejects.toMatchObject({ status: 403, message: "The owner didn't approve this." });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("an expired device is told why", async () => {
+ configureApi({ baseUrl: "https://m.example", token: "mdt_x" });
+ vi.stubGlobal("fetch", vi.fn(async () => json(401, { expired: true, error: "This device wasn't used for 30 days, so it was signed out." })));
+ const err = await http.get("/api/ping").catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(ApiError);
+ expect((err as ApiError).message).toMatch(/wasn't used for 30 days/);
+ });
+});
+
+describe("plain http to another machine", () => {
+ it("is flagged, except on this machine and on a tailnet", () => {
+ expect(insecureRemote("http://203.0.113.7:6174")).toBe(true);
+ expect(insecureRemote("http://home.example.com")).toBe(true);
+ expect(insecureRemote("https://home.example.com")).toBe(false);
+ expect(insecureRemote("http://127.0.0.1:6174")).toBe(false);
+ expect(insecureRemote("http://100.101.2.3:6174")).toBe(false);
+ expect(insecureRemote("http://mercury.tail1234.ts.net")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index d147e6d3..6c8b9a59 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -12,6 +12,17 @@ export interface ApiTarget {
let target: ApiTarget = { baseUrl: "", token: null };
let unauthorizedHandler: (() => void) | null = null;
+/**
+ * A remote runtime asks its owner before some actions (428 + an approval id).
+ * The app waits for the owner's answer (approvalHandler shows that), then
+ * repeats the request once with the approval. False = denied or given up.
+ */
+export type ApprovalHandler = (needed: { approvalId: string; code: string; where: string; error: string; expiresAt?: number }) => Promise<boolean>;
+let approvalHandler: ApprovalHandler | null = null;
+export function setApprovalHandler(fn: ApprovalHandler | null): void {
+ approvalHandler = fn;
+}
+
export function configureApi(next: Partial<ApiTarget> & { onUnauthorized?: (() => void) | null }): void {
target = {
baseUrl: next.baseUrl === undefined ? target.baseUrl : normalizeBaseUrl(next.baseUrl),
@@ -56,10 +67,18 @@ export async function request<T>(path: string, init: RequestInit = {}): Promise<
});
if (res.status === 401) {
unauthorizedHandler?.();
- throw new ApiError("Unauthorized", 401);
+ // An expired device (unused too long) is told why.
+ const body = (await res.json().catch(() => ({}))) as { error?: string; expired?: boolean };
+ throw new ApiError(body.expired && body.error ? body.error : "Unauthorized", 401, null, body);
}
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string } & Record<string, unknown>;
+ const asked = (init.headers as Record<string, string> | undefined)?.["X-Mercury-Approval"];
+ if (res.status === 428 && body.approvalRequired === true && typeof body.approvalId === "string" && approvalHandler && !asked) {
+ const ok = await approvalHandler({ approvalId: body.approvalId, code: String(body.code ?? ""), where: String(body.where ?? "the computer Mercury runs on"), error: String(body.error ?? ""), expiresAt: typeof body.expiresAt === "number" ? body.expiresAt : undefined });
+ if (!ok) throw new ApiError("The owner didn't approve this.", 403, null, { approvalDenied: true });
+ return request<T>(path, { ...init, headers: { ...(init.headers as Record<string, string> | undefined), "X-Mercury-Approval": body.approvalId } });
+ }
const retry = res.headers.get("Retry-After");
throw new ApiError(body.error || `Request failed (${res.status})`, res.status, retry ? Number(retry) : null, body);
}
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index a58062e3..eab4895a 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -7,7 +7,7 @@ import { http, ApiError } from "./client";
import type { CommandEntry } from "~/views/chat/picker";
import type { SkillDraft,
BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
- McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PluginItem, ReasoningChoice, Skill, DeviceSummary,
+ McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PendingPair, OwnerApproval, PluginItem, ReasoningChoice, Skill, DeviceSummary,
} from "./types";
export const health = {
@@ -27,24 +27,47 @@ export const health = {
};
export const auth = {
- pair: async (baseUrl: string, username: string, password: string, deviceName: string, platform: string): Promise<PairResponse> => {
+ /** Sign in for a device token. From another device the owner approves it first (a PendingPair). */
+ pair: async (baseUrl: string, username: string, password: string, deviceName: string, platform: string): Promise<PairResponse | PendingPair> => {
const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/auth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, deviceName, platform }),
});
- const body = (await res.json().catch(() => ({}))) as Partial<PairResponse> & { error?: string };
+ const body = (await res.json().catch(() => ({}))) as Partial<PairResponse & PendingPair> & { error?: string };
if (!res.ok) {
const retry = res.headers.get("Retry-After");
throw new ApiError(body.error || `Pairing failed (${res.status})`, res.status, retry ? Number(retry) : null);
}
- return body as PairResponse;
+ return body as PairResponse | PendingPair;
+ },
+ /** Ask how a pairing stands; the runtime answers within ~25 s if the owner decides meanwhile. */
+ pollPair: async (baseUrl: string, pairingId: string, pollToken: string, signal?: AbortSignal): Promise<{ status: "pending" | "approved" | "denied" | "expired" | "error"; token?: string; device?: DeviceSummary; error?: string }> => {
+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/auth/token/pending`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ pairingId, pollToken }),
+ signal,
+ });
+ return (await res.json().catch(() => ({ status: "error", error: `Mercury answered ${res.status}` }))) as { status: "pending" | "approved" | "denied" | "expired" | "error"; token?: string; device?: DeviceSummary; error?: string };
+ },
+ /** Sign a device out on a runtime it may not be connected to right now (removing a remote connection). */
+ revokeAt: async (baseUrl: string, token: string): Promise<void> => {
+ await fetch(`${baseUrl.replace(/\/+$/, "")}/api/auth/token/revoke`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(4000) });
},
devices: () => http.get<{ devices: DeviceSummary[]; current: string | null }>("/api/auth/devices"),
revokeDevice: (id: string) => http.delete<{ success: boolean }>(`/api/auth/devices/${encodeURIComponent(id)}`),
revokeSelf: () => http.post<{ success: boolean }>("/api/auth/token/revoke"),
};
+/** The owner's security questions, on the runtime's own computer. */
+export const security = {
+ approvals: () => http.get<{ pending: OwnerApproval[]; routes: string[] }>("/api/security/approvals"),
+ decide: (id: string, decision: "allow" | "deny") => http.post<{ approval: OwnerApproval }>(`/api/security/approvals/${encodeURIComponent(id)}`, { decision, by: "desktop" }),
+ /** A question this device asked (a 428): how it stands. */
+ status: (id: string) => http.get<{ status: OwnerApproval["status"]; code?: string }>(`/api/security/approvals/${encodeURIComponent(id)}/status`),
+};
+
export const chat = {
threads: () => http.get<{ threads: ChatThread[] }>("/api/chat/threads"),
thread: (id: string) => http.get<ChatThread>(`/api/chat/threads/${encodeURIComponent(id)}`),
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 47f2ae66..6f0c52e3 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -27,6 +27,41 @@ export interface PairResponse {
features: string[];
}
+/** Pairing from another device: the runtime's owner approves it first. */
+export interface PendingPair {
+ pending: true;
+ pairingId: string;
+ pollToken: string;
+ /** Short code the owner sees ("approve K7Q2M"). */
+ code: string;
+ /** Where the owner approves it ("Telegram or this computer…"). */
+ where: string;
+ expiresAt: number;
+}
+
+/** A remote device asked for something sensitive: the owner approves it first. */
+export interface ApprovalNeeded {
+ approvalRequired: true;
+ approvalId: string;
+ code: string;
+ where: string;
+ error: string;
+ expiresAt?: number;
+}
+
+/** A security question waiting for the owner (Mercury Desktop on the runtime's own computer). */
+export interface OwnerApproval {
+ id: string;
+ code: string;
+ kind: "pair" | "action";
+ title: string;
+ detail?: string;
+ who: string;
+ ip?: string;
+ expiresAt: number;
+ status: "pending" | "allowed" | "denied" | "expired";
+}
+
// ── Chat ──
export interface ChatThread {
id: string;
diff --git a/apps/desktop/src/app/App.tsx b/apps/desktop/src/app/App.tsx
index 6ecfa661..27dad6ee 100644
--- a/apps/desktop/src/app/App.tsx
+++ b/apps/desktop/src/app/App.tsx
@@ -10,6 +10,10 @@ import { Button } from "~/components/ui/Button";
import { desktop } from "~/shell/tauri";
import { updateLocalRuntime } from "~/shell/updateLocal";
import { configureApi } from "~/api/client";
+import { installApprovalHandler } from "~/components/OwnerApprovals";
+
+// A remote Mercury asks its owner before some actions: wait for the answer, then carry on.
+installApprovalHandler();
import { useRuntimeState } from "./store";
/**
diff --git a/apps/desktop/src/app/notify/notify.ts b/apps/desktop/src/app/notify/notify.ts
index 8370fd39..1bf14b65 100644
--- a/apps/desktop/src/app/notify/notify.ts
+++ b/apps/desktop/src/app/notify/notify.ts
@@ -264,6 +264,15 @@ export function useNotifications(enabled: boolean): void {
if (!enabled) return;
const stream = openStream("/api/chat/activity", {
onEvent: (event, raw) => {
+ if (event === "owner_approval") {
+ // A device or a remote action waiting for the owner (only sent to an app on the Mercury computer).
+ try {
+ const data = JSON.parse(raw) as Record<string, unknown>;
+ void import("~/components/OwnerApprovals").then(({ onOwnerApprovalEvent }) => onOwnerApprovalEvent(data));
+ if (data.change === "new" && !windowFocused()) tell("needs", "security", data.kind === "pair" ? "A new device wants to connect" : "Mercury needs your approval", `${String(data.kind === "pair" ? data.who : data.title ?? "")} · code ${String(data.code ?? "")}`);
+ } catch { /* ignore a bad line */ }
+ return;
+ }
if (event !== "activity") return;
try { handleActivity(JSON.parse(raw) as ActivityEvent); } catch { /* ignore a bad line */ }
},
diff --git a/apps/desktop/src/components/OwnerApprovals.tsx b/apps/desktop/src/components/OwnerApprovals.tsx
new file mode 100644
index 00000000..8624ac77
--- /dev/null
+++ b/apps/desktop/src/components/OwnerApprovals.tsx
@@ -0,0 +1,121 @@
+import { KeyRound, ShieldAlert, ShieldCheck, X } from "lucide-react";
+import { useEffect, useState } from "react";
+import { create } from "zustand";
+import * as api from "~/api/mercury";
+import { setApprovalHandler } from "~/api/client";
+import type { OwnerApproval } from "~/api/types";
+import { Button } from "~/components/ui/Button";
+
+/**
+ * Security questions, both sides of them:
+ *
+ * - WaitingForOwner: this app (connected to a remote Mercury) asked for
+ * something sensitive; the owner must approve it on their channel or that
+ * computer. Shown until they answer; the request then goes through by itself.
+ * - OwnerApprovalCards: this app IS on the Mercury computer; a device or a
+ * remote action is waiting for the owner here: Approve / Deny.
+ */
+
+interface Waiting { approvalId: string; code: string; where: string; error: string; expiresAt?: number; resolve: (ok: boolean) => void }
+
+const useWaiting = create<{ waiting: Waiting | null; set: (w: Waiting | null) => void }>((set) => ({ waiting: null, set: (waiting) => set({ waiting }) }));
+
+const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** Installed once: every 428 from the runtime waits here for the owner. */
+export function installApprovalHandler(): void {
+ setApprovalHandler(async (needed) => new Promise<boolean>((resolve) => {
+ let done = false;
+ const finish = (ok: boolean) => { if (done) return; done = true; useWaiting.getState().set(null); resolve(ok); };
+ useWaiting.getState().set({ ...needed, resolve: finish });
+ void (async () => {
+ const until = needed.expiresAt ?? Date.now() + 10 * 60_000;
+ while (!done && Date.now() < until + 5_000) {
+ await pause(2000);
+ if (done) return;
+ try {
+ const s = await api.security.status(needed.approvalId);
+ if (s.status === "allowed") return finish(true);
+ if (s.status === "denied" || s.status === "expired") return finish(false);
+ } catch { /* keep waiting */ }
+ }
+ finish(false);
+ })();
+ }));
+}
+
+export function WaitingForOwner() {
+ const w = useWaiting((s) => s.waiting);
+ if (!w) return null;
+ const what = w.error.replace(/^Waiting for the owner to approve: /, "").replace(/\. Approve it on[\s\S]*$/, "");
+ return (
+ <div className="fixed bottom-6 left-1/2 z-50 w-[min(520px,92vw)] -translate-x-1/2 rounded-xl border border-line bg-raised p-4 shadow-2xl" role="status">
+ <div className="flex items-start gap-3">
+ <KeyRound size={18} className="mt-0.5 shrink-0 text-amber" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">Waiting for the owner's approval</p>
+ <p className="mt-0.5 text-sm text-ink2">{what || "This needs the owner's OK."}</p>
+ <p className="mt-1.5 text-xs text-ink3">Approve it on {w.where}. Code <span className="font-mono font-medium text-ink">{w.code}</span>. It continues by itself once approved.</p>
+ </div>
+ <Button size="sm" variant="ghost" onClick={() => w.resolve(false)} aria-label="Stop waiting"><X size={13} /> Cancel</Button>
+ </div>
+ </div>
+ );
+}
+
+const useLocalApprovals = create<{ items: OwnerApproval[]; upsert: (a: OwnerApproval) => void; remove: (id: string) => void; replace: (a: OwnerApproval[]) => void }>((set) => ({
+ items: [],
+ upsert: (a) => set((s) => ({ items: [...s.items.filter((x) => x.id !== a.id), a] })),
+ remove: (id) => set((s) => ({ items: s.items.filter((x) => x.id !== id) })),
+ replace: (items) => set({ items }),
+}));
+
+/** From the activity stream (sent only to apps on the Mercury computer). */
+export function onOwnerApprovalEvent(data: Record<string, unknown>): void {
+ const a = data as unknown as OwnerApproval & { change?: string };
+ if (typeof a.id !== "string") return;
+ if (a.change === "new" && a.status === "pending") useLocalApprovals.getState().upsert(a);
+ else useLocalApprovals.getState().remove(a.id);
+}
+
+/** Questions already waiting when the app connects. */
+export async function loadOwnerApprovals(): Promise<void> {
+ try { useLocalApprovals.getState().replace((await api.security.approvals()).pending); } catch { /* remote, or an older Mercury */ }
+}
+
+export function OwnerApprovalCards({ local }: { local: boolean }) {
+ const items = useLocalApprovals((s) => s.items);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { if (!items.length) return; const t = setInterval(() => setNow(Date.now()), 15_000); return () => clearInterval(t); }, [items.length]);
+ useEffect(() => { if (local) void loadOwnerApprovals(); else useLocalApprovals.getState().replace([]); }, [local]);
+ const live = items.filter((a) => a.expiresAt > now);
+ if (!local || !live.length) return null;
+ async function decide(a: OwnerApproval, d: "allow" | "deny") {
+ setBusy(a.id);
+ try { await api.security.decide(a.id, d); } catch { /* already answered elsewhere */ }
+ useLocalApprovals.getState().remove(a.id);
+ setBusy(null);
+ }
+ return (
+ <div className="fixed right-4 top-14 z-50 flex w-[min(400px,92vw)] flex-col gap-2">
+ {live.map((a) => (
+ <div key={a.id} className="rounded-xl border border-amber/40 bg-raised p-3.5 shadow-2xl" role="alertdialog" aria-label={a.title}>
+ <div className="flex items-start gap-2.5">
+ <ShieldAlert size={17} className="mt-0.5 shrink-0 text-amber" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">{a.kind === "pair" ? "A new device wants to connect" : `${a.who} wants to…`}</p>
+ <p className="mt-0.5 text-sm text-ink2">{a.kind === "pair" ? a.who : a.title}</p>
+ {(a.detail || a.ip) && <p className="mt-0.5 break-words font-mono text-xs text-ink3">{[a.detail, a.ip && a.kind === "action" ? `from ${a.ip}` : null].filter(Boolean).join(" · ")}</p>}
+ <p className="mt-1 text-xs text-ink4">Code {a.code} · expires in {Math.max(1, Math.round((a.expiresAt - now) / 60_000))} min{a.kind === "pair" ? " · deny it if you didn't just sign in somewhere" : ""}</p>
+ </div>
+ </div>
+ <div className="mt-2.5 flex justify-end gap-2">
+ <Button size="sm" variant="ghost" loading={busy === a.id} onClick={() => void decide(a, "deny")}>Deny</Button>
+ <Button size="sm" variant="primary" loading={busy === a.id} onClick={() => void decide(a, "allow")}><ShieldCheck size={13} /> {a.kind === "pair" ? "Approve device" : "Allow once"}</Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsx
index a7efbcc4..fa309224 100644
--- a/apps/desktop/src/layout/Workspace.tsx
+++ b/apps/desktop/src/layout/Workspace.tsx
@@ -23,6 +23,7 @@ import { CloudBanner } from "~/views/settings/Cloud";
import { CallLayer } from "~/views/call/Call";
import { useNotifications } from "~/app/notify/notify";
import { Alerts } from "~/components/Alerts";
+import { OwnerApprovalCards, WaitingForOwner } from "~/components/OwnerApprovals";
registerBuiltinStatusItems();
@@ -34,6 +35,8 @@ registerBuiltinStatusItems();
*/
export function Workspace({ connection, health, onSwitchConnection }: { connection: Connection; health: HealthInfo; onSwitchConnection: () => void }) {
const view = useUi((s) => s.view);
+ // Security questions are answered here only when this app runs on the Mercury computer.
+ const localConnection = connection.kind === "local";
useRuntimeEvents(true);
useNotifications(true);
usePulsePolling(connection.id);
@@ -67,6 +70,8 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti
<StatusBar />
<CallLayer />
<Alerts />
+ <WaitingForOwner />
+ <OwnerApprovalCards local={localConnection} />
</div>
);
}
diff --git a/apps/desktop/src/shell/AddRemote.tsx b/apps/desktop/src/shell/AddRemote.tsx
index 6a115b21..e4506519 100644
--- a/apps/desktop/src/shell/AddRemote.tsx
+++ b/apps/desktop/src/shell/AddRemote.tsx
@@ -1,4 +1,5 @@
-import { useState, type FormEvent } from "react";
+import { useRef, useState, type FormEvent } from "react";
+import { KeyRound } from "lucide-react";
import * as api from "~/api/mercury";
import { ApiError, normalizeBaseUrl } from "~/api/client";
import { Button } from "~/components/ui/Button";
@@ -13,6 +14,20 @@ import { newConnectionId, useConnections } from "./connections";
* paste a token made there with `mercury devices add`. Only the token is
* kept, in the OS keychain.
*/
+/** Another machine over plain http (a tailnet address is encrypted by the VPN itself). */
+export function insecureRemote(baseUrl: string): boolean {
+ try {
+ const u = new URL(baseUrl);
+ if (u.protocol !== "http:") return false;
+ const h = u.hostname;
+ if (h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]") return false;
+ if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h) || h.endsWith(".ts.net")) return false;
+ return true;
+ } catch {
+ return false;
+ }
+}
+
export function AddRemote({ onAdded }: { onAdded: () => void }) {
const [mode, setMode] = useState<"password" | "token">("password");
const [url, setUrl] = useState("");
@@ -22,6 +37,11 @@ export function AddRemote({ onAdded }: { onAdded: () => void }) {
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
+ // Pairing from here waits for the runtime's owner to approve this device.
+ const [waiting, setWaiting] = useState<{ code: string; where: string } | null>(null);
+ const cancel = useRef<AbortController | null>(null);
+ // Plain http to another machine sends the password readable on the way: warn once.
+ const [httpOk, setHttpOk] = useState(false);
const add = useConnections((s) => s.add);
const setActive = useConnections((s) => s.setActive);
@@ -30,6 +50,11 @@ export function AddRemote({ onAdded }: { onAdded: () => void }) {
setError(null);
const baseUrl = normalizeBaseUrl(url);
if (!/^https?:\/\//i.test(baseUrl)) { setError("Enter the runtime's address, starting with http:// or https://"); return; }
+ if (insecureRemote(baseUrl) && !httpOk) {
+ setError("This address isn't https, so your password and token would cross the network unencrypted. Use the https address of your tunnel (Tailscale, Cloudflare), or press Connect again to continue anyway.");
+ setHttpOk(true);
+ return;
+ }
setBusy(true);
try {
const platform = await desktop.platform();
@@ -38,8 +63,26 @@ export function AddRemote({ onAdded }: { onAdded: () => void }) {
let deviceId: string | undefined;
if (mode === "password") {
const paired = await api.auth.pair(baseUrl, username.trim(), password, `${host} · Mercury Desktop`, platform);
- credential = paired.token;
- deviceId = paired.device.id;
+ if ("pending" in paired) {
+ // The owner approves this device on their channel or that computer.
+ setWaiting({ code: paired.code, where: paired.where });
+ const ac = new AbortController();
+ cancel.current = ac;
+ let approved: { token: string; device: { id: string } } | null = null;
+ while (!ac.signal.aborted && Date.now() < paired.expiresAt + 5_000) {
+ const r = await api.auth.pollPair(baseUrl, paired.pairingId, paired.pollToken, ac.signal).catch((e) => (ac.signal.aborted ? null : { status: "pending" as const, error: String(e) }));
+ if (!r || ac.signal.aborted) break;
+ if (r.status === "approved" && r.token && r.device) { approved = { token: r.token, device: r.device }; break; }
+ if (r.status === "denied" || r.status === "expired" || r.status === "error") throw new Error(r.error || (r.status === "denied" ? "The owner didn't approve this device." : "Nobody approved this device in time. Connect again to ask again."));
+ }
+ setWaiting(null);
+ if (!approved) { if (!ac.signal.aborted) throw new Error("Nobody approved this device in time. Connect again to ask again."); return; }
+ credential = approved.token;
+ deviceId = approved.device.id;
+ } else {
+ credential = paired.token;
+ deviceId = paired.device.id;
+ }
} else {
credential = token.trim();
if (!/^mdt_[0-9a-f]{8}_[0-9a-f]{64}$/.test(credential)) throw new Error("That does not look like a device token (mdt_…).");
@@ -59,9 +102,29 @@ export function AddRemote({ onAdded }: { onAdded: () => void }) {
else setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
+ setWaiting(null);
+ cancel.current = null;
}
}
+ if (waiting) {
+ return (
+ <div className="flex flex-col gap-3" role="status">
+ <div className="flex items-start gap-3 rounded-lg border border-line bg-soft p-3.5">
+ <KeyRound size={18} className="mt-0.5 shrink-0 text-amber" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">Waiting for the owner to approve this device</p>
+ <p className="mt-1 text-sm text-ink2">Approve it on {waiting.where}.</p>
+ <p className="mt-2 text-xs text-ink3">Code</p>
+ <p className="font-mono text-2xl font-semibold tracking-[0.2em] text-ink">{waiting.code}</p>
+ <p className="mt-2 text-xs text-ink4">On Telegram or WhatsApp, reply “approve {waiting.code}”. On that computer: /server approve {waiting.code}, or the prompt in Mercury Desktop.</p>
+ </div>
+ </div>
+ <Button variant="outline" size="lg" onClick={() => cancel.current?.abort()}>Cancel</Button>
+ </div>
+ );
+ }
+
return (
<form onSubmit={(e) => void submit(e)} className="flex flex-col gap-3">
<Field label="Address" htmlFor="remote-url">
@@ -74,7 +137,7 @@ export function AddRemote({ onAdded }: { onAdded: () => void }) {
<Field label="Password" htmlFor="remote-pass"><Input id="remote-pass" type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" /></Field>
</>
) : (
- <Field label="Device token" htmlFor="remote-token" hint="Made on that machine with: mercury devices add">
+ <Field label="Device token" htmlFor="remote-token" hint="Made on that machine with: /server token <name> (or mercury devices add)">
<Input id="remote-token" type="password" value={token} onChange={(e) => setToken(e.target.value)} autoComplete="off" mono />
</Field>
)}
diff --git a/apps/desktop/src/shell/connections.ts b/apps/desktop/src/shell/connections.ts
index a128e87d..074efd5b 100644
--- a/apps/desktop/src/shell/connections.ts
+++ b/apps/desktop/src/shell/connections.ts
@@ -107,6 +107,12 @@ export const useConnections = create<ConnectionsState>((set, get) => ({
},
async remove(id) {
+ // Sign this app out on the remote too, so the token stops working there, not only here.
+ const conn = get().connections.find((c) => c.id === id);
+ if (conn?.kind === "remote") {
+ const token = await desktop.secretGet(secretKeyFor(id)).catch(() => null);
+ if (token) await import("~/api/mercury").then(({ auth }) => auth.revokeAt(conn.baseUrl, token)).catch(() => { /* offline: it expires when unused */ });
+ }
await desktop.secretDelete(secretKeyFor(id)).catch(() => {});
const connections = get().connections.filter((c) => c.id !== id);
const activeId = get().activeId === id ? null : get().activeId;
diff --git a/apps/desktop/src/views/chat/picker.ts b/apps/desktop/src/views/chat/picker.ts
index 2689c618..9b741a49 100644
--- a/apps/desktop/src/views/chat/picker.ts
+++ b/apps/desktop/src/views/chat/picker.ts
@@ -31,6 +31,7 @@ export type PickerItem =
const DESKTOP_COMMANDS = new Set([
"/help", "/whatsnew", "/status", "/progress", "/log",
"/models", "/models use ", "/cloud models", "/cloud use ",
+ "/server", "/server status", "/server approve ", "/server devices", "/server check", "/server log",
"/research", "/research on", "/research off", "/research plan ", "/research continue", "/research retry", "/research ",
"/budget", "/saver", "/saver toggle", "/memory", "/tools", "/mcp",
"/skills", "/skills search ", "/skills install ",
diff --git a/src/channels/web.ts b/src/channels/web.ts
index 97a8cfe2..ee5dc535 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -580,7 +580,7 @@ export class WebChannel extends BaseChannel {
* `attachments` are files already on disk (see `web/api/uploads.ts`); them being
* present is what lets the runtime hand a photo to a vision model instead of a path.
*/
- emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[], scope?: { programming?: string; cwd?: string }): void {
+ emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string, attachments?: ChannelAttachment[], scope?: { programming?: string; cwd?: string; thisComputer?: boolean }): void {
if (this.restrictUser) {
throw new Error('Web user is restricted. Disable restrict mode to continue.');
}
@@ -603,6 +603,8 @@ export class WebChannel extends BaseChannel {
// folder apply to this turn only; the agent restores the rest after.
...(scope?.programming ? { programming: scope.programming } : {}),
...(scope?.cwd ? { programmingCwd: scope.cwd } : {}),
+ // Sent from this computer (Mercury Desktop or an attached terminal here): /server is allowed.
+ ...(scope?.thisComputer ? { thisComputer: true } : {}),
},
};
this.emit(msg);
diff --git a/src/cli/server-cli.ts b/src/cli/server-cli.ts
new file mode 100644
index 00000000..6773c846
--- /dev/null
+++ b/src/cli/server-cli.ts
@@ -0,0 +1,55 @@
+import type { Command } from 'commander';
+import chalk from 'chalk';
+import { getWebPort, readAttachToken } from '../web/auth.js';
+import { httpServerOps, localServerOps } from '../security/server-ops.js';
+import { runServerCommand, type ServerOps } from '../security/server-menu.js';
+
+/**
+ * `mercury server` — remote access and its security, from a shell on this
+ * computer: the same menu and commands as `/server` in the terminal chat.
+ *
+ * mercury server the menu
+ * mercury server approve K7Q2M let a waiting device in
+ * mercury server off refuse every other device
+ *
+ * With Mercury running it works through Mercury (so approvals and revokes
+ * take effect at once, and revoked devices' live connections close); with
+ * Mercury stopped it edits the settings and device list directly.
+ */
+
+async function opsForThisComputer(): Promise<{ ops: ServerOps; live: boolean }> {
+ const token = readAttachToken();
+ const base = `http://127.0.0.1:${getWebPort()}`;
+ if (token) {
+ try {
+ const res = await fetch(`${base}/api/security/status`, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(2500) });
+ if (res.ok) return { ops: httpServerOps(base, token), live: true };
+ } catch { /* not running */ }
+ }
+ return { ops: localServerOps({ by: 'cli' }), live: false };
+}
+
+export function registerServerCli(program: Command): void {
+ program
+ .command('server [args...]')
+ .description('Remote access and security: devices, approvals, allowed addresses, the security check')
+ .action(async (args: string[] = []) => {
+ const { ops, live } = await opsForThisComputer();
+ if (!live) console.log(chalk.dim(' Mercury is not running: changing settings directly (nothing is waiting for approval).'));
+ const { selectWithArrowKeys } = await import('../utils/arrow-select.js');
+ const tty = !!(process.stdin.isTTY && process.stdout.isTTY);
+ try {
+ await runServerCommand(args.join(' '), ops, {
+ choose: async (title, options) => (tty ? (await selectWithArrowKeys(title, options).catch(() => '')) || null : null),
+ say: async (text) => { console.log(`\n${text.replace(/\*\*(.+?)\*\*/g, (_m, t: string) => chalk.bold(t))}\n`); },
+ secret: async (text) => {
+ console.log(`\n${text}\n`);
+ if (tty) await selectWithArrowKeys('Copy the token now: it is not shown again.', [{ value: 'ok', label: "I've copied it" }]).catch(() => '');
+ },
+ });
+ } catch (err) {
+ console.error(chalk.red(` ${err instanceof Error ? err.message : String(err)}`));
+ process.exitCode = 1;
+ }
+ });
+}
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index 2b53baf9..67b67b94 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -1202,6 +1202,43 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
return true;
}
+ if (cmd === '/server' || cmd.startsWith('/server ')) {
+ // Remote access is managed on the computer Mercury runs on: the terminal
+ // here, or Mercury Desktop / an attached terminal on this computer —
+ // never from a phone chat or a remote device.
+ const here = channelType === 'cli' || agent.currentMessage?.metadata?.thisComputer === true;
+ if (!here) {
+ await channel.send('`/server` works only on the computer Mercury runs on (its terminal, or Mercury Desktop there).', channelId);
+ return true;
+ }
+ const { runServerCommand } = await import('../../security/server-menu.js');
+ const { localServerOps } = await import('../../security/server-ops.js');
+ const ops = localServerOps({ cloudConnected: () => !!ctx.config().cloud?.enabled, by: channelType === 'cli' ? 'cli' : 'desktop' });
+ const args = trimmed.slice('/server'.length);
+ const prompt = channel as typeof channel & { presentChoicePrompt?: (q: string, o: Array<{ value: string; label: string }>, t?: string) => Promise<string> };
+ const say = async (text: string) => { await channel.send(text, channelId); };
+ if (channel instanceof CLIChannel) {
+ await channel.withMenu(async (select) => {
+ await runServerCommand(args, ops, {
+ choose: async (title, options) => (await select(title, options)) || null,
+ say,
+ // Shown in the menu, not the transcript.
+ secret: async (text) => { await select(text, [{ value: 'ok', label: "I've copied it" }]); },
+ });
+ });
+ return true;
+ }
+ await runServerCommand(args, ops, {
+ choose: async (title, options) => (typeof prompt.presentChoicePrompt === 'function' ? (await prompt.presentChoicePrompt(title, options, channelId)) || null : null),
+ say,
+ secret: async (text) => {
+ if (typeof prompt.presentChoicePrompt === 'function') await prompt.presentChoicePrompt(text, [{ value: 'ok', label: "I've copied it" }], channelId);
+ else await say(text);
+ },
+ });
+ return true;
+ }
+
if (cmd.startsWith('/research')) {
const rawArgs = trimmed.slice('/research'.length).trim();
const sub = rawArgs.toLowerCase();
diff --git a/src/core/commands/slash-list.ts b/src/core/commands/slash-list.ts
index b5ee39be..0a991570 100644
--- a/src/core/commands/slash-list.ts
+++ b/src/core/commands/slash-list.ts
@@ -70,6 +70,18 @@ export const SLASH_COMMANDS: readonly string[] = [
'/code exit',
'/code chat',
'/code back',
+ '/server',
+ '/server status',
+ '/server approve ',
+ '/server deny ',
+ '/server devices',
+ '/server revoke ',
+ '/server token ',
+ '/server on',
+ '/server off',
+ '/server allow-ip ',
+ '/server check',
+ '/server log',
'/research',
'/research on',
'/research off',
diff --git a/src/index.ts b/src/index.ts
index 89539425..0b15826f 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -61,6 +61,7 @@ import { registerPluginsCli } from './cli/plugins-cli.js';
import { PersonVerifier, personCheckPrompt, parsePersonCheck } from './memory/person-verifier.js';
import { setPersonVerifier } from './web/api/brain.js';
import { registerDevicesCli } from './cli/devices-cli.js';
+import { registerServerCli } from './cli/server-cli.js';
import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';
import { isSqliteAvailable } from './utils/sqlite-driver.js';
import { runStorageDoctor } from './utils/storage-doctor.js';
@@ -4214,7 +4215,18 @@ program
.option('--storage', 'Show SQLite backend, database files and row counts')
.option('--mcp', 'Connect to each configured MCP server and report its status')
.option('--plugins', 'Check installed plugins and why any are turned off')
+ .option('--security', 'Check remote access and security (password, devices, file permissions, tunnel)')
.action(async (opts) => {
+ if (opts.security) {
+ const { securityCheck, summarizeFindings } = await import('./security/check.js');
+ const { findingsText } = await import('./security/server-menu.js');
+ const findings = securityCheck({ cloudConnected: loadConfig().cloud?.enabled === true });
+ console.log(`\n Security: ${summarizeFindings(findings)}\n`);
+ console.log(findingsText(findings).split('\n').map((l) => ` ${l}`).join('\n'));
+ console.log(chalk.dim('\n Manage remote access with `mercury server` (or /server in the terminal chat).\n'));
+ if (findings.some((f) => f.level === 'risk')) process.exitCode = 1;
+ return;
+ }
{
// Keys that cannot be right — say so before anything is tried.
const { checkKeyShapes } = await import('./providers/key-shape.js');
@@ -4237,6 +4249,14 @@ program
}
const mcpSummary = summarizeMcpConfig(loadConfig().mcp);
if (mcpSummary) console.log(chalk.dim(` ${mcpSummary}`));
+ {
+ // One line about security on every doctor run; details with --security.
+ const { securityCheck, summarizeFindings } = await import('./security/check.js');
+ const findings = securityCheck({ cloudConnected: loadConfig().cloud?.enabled === true });
+ const summary = summarizeFindings(findings);
+ const line = ` Security: ${summary}${summary === 'All good' ? '' : ' — run `mercury doctor --security`'}`;
+ console.log(findings.some((f) => f.level === 'risk') ? chalk.yellow(line) : chalk.dim(line));
+ }
if (opts.plugins) {
const { runPluginDoctor } = await import('./cli/plugins-cli.js');
await runPluginDoctor();
@@ -5096,6 +5116,7 @@ serviceCmd
});
registerDevicesCli(program);
+registerServerCli(program);
program
.command('upgrade')
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 27cd8446..a2164f01 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -37,7 +37,7 @@ export const RESERVED_PLUGIN_IDS: ReadonlySet<string> = new Set(['mcp']);
*/
export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
- 'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'saver', 'session', 'sessions', 'skills', 'spotify',
+ 'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'server', 'saver', 'session', 'sessions', 'skills', 'spotify',
'status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear',
'approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',
'usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about', 'mcp',
diff --git a/src/security/owner-approvals.ts b/src/security/owner-approvals.ts
index c5c62569..1bd688a3 100644
--- a/src/security/owner-approvals.ts
+++ b/src/security/owner-approvals.ts
@@ -122,6 +122,17 @@ export class OwnerApprovals {
return true;
}
+ /** A question this principal already has waiting for this action (asking again doesn't ask again). */
+ pendingFor(scope: { principal: string; action: string }): OwnerApproval | null {
+ const a = [...this.items.values()].find((x) => x.status === 'pending' && x.scope?.principal === scope.principal && x.scope?.action === scope.action && this.now() <= x.expiresAt);
+ return a ? { ...a } : null;
+ }
+
+ /** How many questions this principal has waiting. */
+ pendingCount(principal: string): number {
+ return [...this.items.values()].filter((x) => x.status === 'pending' && x.scope?.principal === principal && this.now() <= x.expiresAt).length;
+ }
+
pending(): OwnerApproval[] {
this.sweep();
return [...this.items.values()].filter((a) => a.status === 'pending').sort((x, y) => x.at - y.at).map((a) => ({ ...a }));
diff --git a/src/security/remote-security.test.ts b/src/security/remote-security.test.ts
index 69003fa3..633c2900 100644
--- a/src/security/remote-security.test.ts
+++ b/src/security/remote-security.test.ts
@@ -130,6 +130,26 @@ describe('the owner approves sensitive actions from other devices', () => {
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("asking again reuses the waiting question, and a device can't flood the owner", async () => {
+ const a = await app();
+ const phone = await device();
+ const sent: string[] = [];
+ ownerApprovals().onChange((q, change) => { if (change === 'new') sent.push(q.id); });
+ const one = (await (await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token) }, LAN)).json()) as { approvalId: string };
+ const two = (await (await a.request('http://127.0.0.1/api/danger', { method: 'POST', ...bearer(phone.token) }, LAN)).json()) as { approvalId: string };
+ expect(two.approvalId).toBe(one.approvalId);
+ expect(sent).toHaveLength(1);
+ const { requireOwner } = await import('../web/owner-gate.js');
+ const b = new Hono();
+ const { authGuard } = await import('../web/middleware.js');
+ b.use('*', authGuard);
+ b.post('/api/x/:n', (c) => requireOwner(c, { id: `x.${c.req.param('n')}`, title: 'x' }) ?? c.json({}));
+ expect((await b.request('http://127.0.0.1/api/x/1', { method: 'POST', ...bearer(phone.token) }, LAN)).status).toBe(428);
+ expect((await b.request('http://127.0.0.1/api/x/2', { method: 'POST', ...bearer(phone.token) }, LAN)).status).toBe(428);
+ expect((await b.request('http://127.0.0.1/api/x/3', { method: 'POST', ...bearer(phone.token) }, LAN)).status).toBe(429);
+ expect(sent).toHaveLength(3);
+ });
+
it('a denial is a 403 that says so; on this computer nothing is asked', async () => {
const a = await app();
const phone = await device();
diff --git a/src/security/server-menu.test.ts b/src/security/server-menu.test.ts
new file mode 100644
index 00000000..74c8dfe8
--- /dev/null
+++ b/src/security/server-menu.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { OwnerApprovals, _setOwnerApprovals, ownerApprovals } from './owner-approvals.js';
+import { runServerCommand, type ServerUi } from './server-menu.js';
+import { localServerOps } from './server-ops.js';
+import { readRemoteSettings } from './remote-settings.js';
+import { readAudit } from './audit.js';
+
+let home: string;
+const previous = process.env.MERCURY_HOME;
+beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'mercury-server-')); 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 }); });
+
+function screen(picks: string[] = []) {
+ const said: string[] = [];
+ const secrets: string[] = [];
+ const titles: string[] = [];
+ const ui: ServerUi = {
+ choose: async (title, options) => { titles.push(title); const p = picks.shift() ?? 'done'; return options.find((o) => o.value === p || o.value.startsWith(p))?.value ?? null; },
+ say: async (t) => { said.push(t); },
+ secret: async (t) => { secrets.push(t); },
+ };
+ return { ui, said, secrets, titles };
+}
+
+describe('/server', () => {
+ it('turns remote access off and on, and logs who did it', async () => {
+ const ops = localServerOps({ by: 'cli' });
+ const s = screen();
+ await runServerCommand('off', ops, s.ui);
+ expect(readRemoteSettings().enabled).toBe(false);
+ await runServerCommand('on', ops, s.ui);
+ expect(readRemoteSettings().enabled).toBe(true);
+ expect(readAudit(5).map((e) => [e.kind, e.by])).toContainEqual(['remote.changed', 'cli']);
+ });
+
+ it('makes a token shown once (as a secret, never said), lists and revokes it', async () => {
+ const ops = localServerOps();
+ const s = screen();
+ await runServerCommand('token Office laptop', ops, s.ui);
+ expect(s.secrets[0]).toMatch(/mdt_[0-9a-f]{8}_[0-9a-f]{64}/);
+ expect(s.said.join('\n')).not.toMatch(/mdt_/);
+ await runServerCommand('devices', ops, s.ui);
+ expect(s.said.at(-1)).toMatch(/Office laptop/);
+ await runServerCommand('revoke office laptop', ops, s.ui);
+ expect((await ops.status()).devices).toHaveLength(0);
+ });
+
+ it('approves a waiting device by its code', async () => {
+ const q = ownerApprovals().request({ kind: 'pair', title: 'New device: Phone', who: 'Phone' }, 60_000);
+ const s = screen();
+ await runServerCommand(`approve ${q.code.toLowerCase()}`, localServerOps(), s.ui);
+ expect(ownerApprovals().get(q.id)?.status).toBe('allowed');
+ expect(s.said.at(-1)).toMatch(/Approved/);
+ await runServerCommand(`deny ${q.code}`, localServerOps(), s.ui);
+ expect(s.said.at(-1)).toMatch(/No question is waiting/);
+ });
+
+ it('validates addresses and settings', async () => {
+ const ops = localServerOps();
+ const s = screen();
+ await runServerCommand('allow-ip not-an-ip', ops, s.ui);
+ expect(readRemoteSettings().allowIps).toEqual([]);
+ await runServerCommand('allow-ip 100.64.0.0/10', ops, s.ui);
+ await runServerCommand('allow-ip 203.0.113.7', ops, s.ui);
+ expect(readRemoteSettings().allowIps).toEqual(['100.64.0.0/10', '203.0.113.7']);
+ await runServerCommand('remove-ip 203.0.113.7', ops, s.ui);
+ expect(readRemoteSettings().allowIps).toEqual(['100.64.0.0/10']);
+ await runServerCommand('expire never', ops, s.ui);
+ await runServerCommand('limit 3', ops, s.ui);
+ await runServerCommand('shell on', ops, s.ui);
+ expect(readRemoteSettings()).toMatchObject({ idleDays: 0, maxDevices: 3, allowShell: true });
+ await runServerCommand('nonsense', ops, s.ui);
+ expect(s.said.at(-1)).toMatch(/\/server approve <code>/);
+ });
+
+ it('the menu walks: waiting → approve, then Done', async () => {
+ const q = ownerApprovals().request({ kind: 'action', title: 'Run a shell command', who: 'Phone', scope: { principal: 'device:x', action: 'a' } }, 60_000);
+ const s = screen(['pending', q.id, 'allow', 'done']);
+ await runServerCommand('', localServerOps(), s.ui);
+ expect(ownerApprovals().get(q.id)?.status).toBe('allowed');
+ expect(s.titles[0]).toMatch(/Remote access: on · 0 devices · 1 waiting for you · Security:/);
+ });
+});
diff --git a/src/security/server-menu.ts b/src/security/server-menu.ts
new file mode 100644
index 00000000..3cb74c1f
--- /dev/null
+++ b/src/security/server-menu.ts
@@ -0,0 +1,303 @@
+import type { DeviceSummary } from '../web/devices.js';
+import type { OwnerApproval } from './owner-approvals.js';
+import type { RemoteSettings } from './remote-settings.js';
+import type { AuditEntry } from './audit.js';
+import type { SecurityFinding } from './check.js';
+import { parseIpRule } from './ip-match.js';
+
+/**
+ * The owner's remote-access screen: `/server` in the terminal (and in
+ * Mercury Desktop on this computer), and `mercury server`. One menu over two
+ * kinds of plumbing (the running Mercury's own state, or its API from a
+ * separate process) and two kinds of screen (arrow-key menus, choice prompts).
+ */
+
+export interface ServerStatus {
+ remote: RemoteSettings;
+ devices: DeviceSummary[];
+ browsers: number;
+ pending: OwnerApproval[];
+ approvalRoutes: string[];
+ lastRemote: { at: number; proxied: boolean; clientIpKnown: boolean; ip: string } | null;
+ check: { summary: string; findings: SecurityFinding[] };
+}
+
+export interface ServerOps {
+ status(): Promise<ServerStatus>;
+ setRemote(patch: Partial<RemoteSettings>): Promise<void>;
+ decide(idOrCode: string, decision: 'allow' | 'deny'): Promise<OwnerApproval | null>;
+ createDevice(name: string): Promise<{ token: string; device: DeviceSummary }>;
+ revoke(id: string): Promise<boolean>;
+ revokeAll(): Promise<number>;
+ audit(limit: number): Promise<AuditEntry[]>;
+}
+
+export interface ServerUi {
+ choose(title: string, options: Array<{ value: string; label: string }>): Promise<string | null>;
+ say(text: string): Promise<void>;
+ /** Something that must not stay in a transcript (a new token): shown until acknowledged. */
+ secret(text: string): Promise<void>;
+}
+
+const ago = (iso: string | null | undefined, now = Date.now()): string => {
+ if (!iso) return 'never used';
+ const s = Math.round((now - Date.parse(iso)) / 1000);
+ if (s < 90) return 'just now';
+ if (s < 5400) return `${Math.round(s / 60)} min ago`;
+ if (s < 129_600) return `${Math.round(s / 3600)} h ago`;
+ return `${Math.round(s / 86_400)} days ago`;
+};
+
+export function deviceLine(d: DeviceSummary, now = Date.now()): string {
+ return `${d.name} · ${d.platform} · ${ago(d.lastSeenAt, now)}${d.lastIp ? ` · ${d.lastIp}` : ''}`;
+}
+
+export function statusLine(s: ServerStatus): string {
+ const r = s.remote;
+ const parts = [
+ r.enabled ? 'Remote access: on' : 'Remote access: off',
+ `${s.devices.length} device${s.devices.length === 1 ? '' : 's'}`,
+ s.pending.length ? `${s.pending.length} waiting for you` : null,
+ `Security: ${s.check.summary}`,
+ ].filter(Boolean);
+ return parts.join(' · ');
+}
+
+export function statusText(s: ServerStatus): string {
+ const r = s.remote;
+ const lines = [
+ `**Remote access** ${r.enabled ? 'on' : 'off'}${r.enabled ? (r.allowIps.length ? ` · only from ${r.allowIps.join(', ')}` : ' · from any address') : ''}`,
+ `**Devices** ${s.devices.length} of ${r.maxDevices}${r.idleDays ? ` · unused ones expire after ${r.idleDays} days` : ' · never expire'}`,
+ ...s.devices.map((d) => ` · ${deviceLine(d)}`),
+ `**Remote terminal** ${r.allowShell ? 'on (each command asks you)' : 'off'}`,
+ `**Approvals reach you on** ${s.approvalRoutes.join(', ')}`,
+ s.lastRemote ? `**Last remote request** ${ago(new Date(s.lastRemote.at).toISOString())}${s.lastRemote.proxied ? ' through a tunnel' : ''}${s.lastRemote.clientIpKnown ? ` from ${s.lastRemote.ip}` : ' (the tunnel did not say from where)'}` : '**Last remote request** none since Mercury started',
+ `**Security check** ${s.check.summary}`,
+ ];
+ if (s.pending.length) lines.push('', '**Waiting for you**', ...s.pending.map((p) => ` · ${p.title} (code ${p.code})${p.ip ? ` from ${p.ip}` : ''}`));
+ return lines.join('\n');
+}
+
+export function findingsText(f: SecurityFinding[]): string {
+ const mark = { ok: '✓', info: '·', warn: '!', risk: '✗' } as const;
+ return f.map((x) => `${mark[x.level]} ${x.title}${x.detail ? `\n ${x.detail}` : ''}${x.fix ? `\n → ${x.fix}` : ''}`).join('\n');
+}
+
+export function auditText(entries: AuditEntry[]): string {
+ if (!entries.length) return 'Nothing in the security log yet.';
+ const label: Record<string, string> = {
+ 'pair.requested': 'asked to pair', 'pair.approved': 'paired (approved)', 'pair.denied': 'pairing denied', 'pair.expired': 'pairing expired', 'pair.local': 'paired on this computer',
+ 'device.revoked': 'signed out', 'device.expired': 'expired (unused)', 'device.new-location': 'connected from a new address', 'device.blocked': 'refused',
+ 'action.requested': 'asked to', 'action.allowed': 'allowed', 'action.denied': 'denied',
+ 'remote.changed': 'remote access changed', 'login.failed': 'wrong password', 'login.locked': 'sign-in locked (too many tries)', 'password.changed': 'password changed',
+ };
+ const local = (iso: string): string => {
+ const d = new Date(iso);
+ const p = (n: number) => String(n).padStart(2, '0');
+ return Number.isNaN(d.getTime()) ? iso : `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
+ };
+ return entries.map((e) => `${local(e.at)} ${e.who ? `${e.who}: ` : ''}${label[e.kind] ?? e.kind}${e.detail ? ` ${e.detail}` : ''}${e.ip ? ` (${e.ip})` : ''}${e.by ? ` · by ${e.by}` : ''}`).join('\n');
+}
+
+/** `/server <words>`: the menu's actions as one-line commands (and the ones that need typed input). */
+export async function runServerCommand(args: string, ops: ServerOps, ui: ServerUi): Promise<boolean> {
+ const [sub = '', ...rest] = args.trim().split(/\s+/).filter(Boolean);
+ const arg = rest.join(' ');
+ switch (sub.toLowerCase()) {
+ case '':
+ await serverMenu(ops, ui);
+ return true;
+ case 'status':
+ await ui.say(statusText(await ops.status()));
+ return true;
+ case 'on':
+ case 'off':
+ await ops.setRemote({ enabled: sub === 'on' });
+ await ui.say(sub === 'on' ? 'Remote access is on: approved devices can connect.' : 'Remote access is off: only this computer can use Mercury. Devices stay paired; turn it on again any time.');
+ return true;
+ case 'approve':
+ case 'allow':
+ case 'deny': {
+ if (!arg) { await ui.say(`Usage: /server ${sub} <code>`); return true; }
+ const a = await ops.decide(arg, sub === 'deny' ? 'deny' : 'allow');
+ await ui.say(a ? `${a.status === 'allowed' ? '✓ Approved' : '✗ Denied'}: ${a.title}${a.kind === 'action' ? ` for ${a.who}` : ''}.` : 'No question is waiting with that code (it may have expired).');
+ return true;
+ }
+ case 'devices':
+ await ui.say((await ops.status()).devices.map((d) => `${d.id} ${deviceLine(d)}`).join('\n') || 'No devices are paired.');
+ return true;
+ case 'revoke': {
+ const s = await ops.status();
+ const d = s.devices.find((x) => x.id === arg || x.name.toLowerCase() === arg.toLowerCase());
+ if (!d) { await ui.say('No device with that id or name. /server devices lists them.'); return true; }
+ await ops.revoke(d.id);
+ await ui.say(`Signed out “${d.name}”. It can't connect any more.`);
+ return true;
+ }
+ case 'revoke-all': {
+ const n = await ops.revokeAll();
+ await ui.say(n ? `Signed out all ${n} devices.` : 'No devices were paired.');
+ return true;
+ }
+ case 'token': {
+ const created = await ops.createDevice(arg || 'Manual token');
+ await ui.secret(`Token for “${created.device.name}” (shown only now):\n\n${created.token}\n\nPaste it into the device (Mercury Desktop → Add a remote → Token).`);
+ return true;
+ }
+ case 'allow-ip': {
+ const rule = parseIpRule(arg);
+ if (!rule) { await ui.say('Give an address or range, e.g. /server allow-ip 203.0.113.7 or /server allow-ip 100.64.0.0/10 (a Tailscale network).'); return true; }
+ const s = await ops.status();
+ await ops.setRemote({ allowIps: [...new Set([...s.remote.allowIps, rule])] });
+ await ui.say(`Allowed ${rule}. Only listed addresses can connect now${s.lastRemote && !s.lastRemote.clientIpKnown ? ' — but your tunnel does not pass client addresses, so remote devices will be refused until it does.' : '.'}`);
+ return true;
+ }
+ case 'remove-ip': {
+ const s = await ops.status();
+ const rule = parseIpRule(arg) ?? arg;
+ await ops.setRemote({ allowIps: s.remote.allowIps.filter((r) => r !== rule) });
+ await ui.say(s.remote.allowIps.includes(rule) ? `Removed ${rule}.` : `${rule} wasn't on the list.`);
+ return true;
+ }
+ case 'allow-any':
+ await ops.setRemote({ allowIps: [] });
+ await ui.say('Any address may connect again (devices still need to be approved).');
+ return true;
+ case 'shell': {
+ if (arg !== 'on' && arg !== 'off') { await ui.say('Usage: /server shell on|off'); return true; }
+ await ops.setRemote({ allowShell: arg === 'on' });
+ await ui.say(arg === 'on' ? 'Remote devices may use the terminal; each command asks you first.' : 'The terminal is off for remote devices.');
+ return true;
+ }
+ case 'expire': {
+ const days = arg === 'never' ? 0 : Number(arg);
+ if (!Number.isFinite(days) || days < 0) { await ui.say('Usage: /server expire <days> | never'); return true; }
+ await ops.setRemote({ idleDays: Math.round(days) });
+ await ui.say(days ? `Devices unused for ${Math.round(days)} days now stop working until you approve them again.` : 'Devices no longer expire when unused.');
+ return true;
+ }
+ case 'limit': {
+ const n = Number(arg);
+ if (!Number.isFinite(n) || n < 1) { await ui.say('Usage: /server limit <number>'); return true; }
+ await ops.setRemote({ maxDevices: Math.round(n) });
+ await ui.say(`Up to ${Math.round(n)} devices can be paired.`);
+ return true;
+ }
+ case 'check':
+ await ui.say(findingsText((await ops.status()).check.findings));
+ return true;
+ case 'log':
+ await ui.say(auditText(await ops.audit(Number(arg) || 20)));
+ return true;
+ default:
+ await ui.say(SERVER_HELP);
+ return true;
+ }
+}
+
+export const SERVER_HELP = [
+ '/server — remote access and its security (this computer only):',
+ ' /server open the menu',
+ ' /server status what can connect, and how',
+ ' /server on | off allow or refuse other devices',
+ ' /server approve <code> let a waiting device or action through (deny <code> to refuse)',
+ ' /server devices paired devices · /server revoke <id|name> · /server revoke-all',
+ ' /server token <name> make a token for a device by hand (shown once)',
+ ' /server allow-ip <ip|range> · remove-ip <ip|range> · allow-any',
+ ' /server shell on|off the terminal for remote devices (each command still asks you)',
+ ' /server expire <days>|never · /server limit <n>',
+ ' /server check the security check · /server log the security log',
+].join('\n');
+
+/** The interactive menu. Returns when the owner picks Done (or closes it). */
+export async function serverMenu(ops: ServerOps, ui: ServerUi): Promise<void> {
+ for (let guard = 0; guard < 200; guard++) {
+ const s = await ops.status();
+ const r = s.remote;
+ const pick = await ui.choose(statusLine(s), [
+ ...(s.pending.length ? [{ value: 'pending', label: `Waiting for you (${s.pending.length})` }] : []),
+ { value: 'devices', label: `Devices (${s.devices.length})` },
+ { value: 'toggle', label: r.enabled ? 'Turn remote access off' : 'Turn remote access on' },
+ { value: 'ips', label: `Allowed addresses: ${r.allowIps.length ? r.allowIps.join(', ') : 'any'}` },
+ { value: 'shell', label: `Terminal for remote devices: ${r.allowShell ? 'on' : 'off'}` },
+ { value: 'check', label: `Security check: ${s.check.summary}` },
+ { value: 'log', label: 'Security log' },
+ { value: 'status', label: 'Show everything' },
+ { value: 'done', label: 'Done' },
+ ]);
+ if (!pick || pick === 'done') return;
+ if (pick === 'status') await ui.say(statusText(s));
+ if (pick === 'toggle') await runServerCommand(r.enabled ? 'off' : 'on', ops, ui);
+ if (pick === 'check') await ui.say(findingsText(s.check.findings));
+ if (pick === 'log') await ui.say(auditText(await ops.audit(20)));
+ if (pick === 'shell') {
+ const v = await ui.choose('The terminal for remote devices', [
+ { value: 'off', label: `Off${!r.allowShell ? ' (now)' : ''} — remote devices can't run commands` },
+ { value: 'on', label: `On${r.allowShell ? ' (now)' : ''} — each command asks you first` },
+ { value: 'back', label: 'Back' },
+ ]);
+ if (v === 'on' || v === 'off') await runServerCommand(`shell ${v}`, ops, ui);
+ }
+ if (pick === 'ips') {
+ const v = await ui.choose(`Allowed addresses: ${r.allowIps.length ? r.allowIps.join(', ') : 'any (approved devices from anywhere)'}`, [
+ ...r.allowIps.map((ip) => ({ value: `remove:${ip}`, label: `Remove ${ip}` })),
+ ...(r.allowIps.length ? [{ value: 'any', label: 'Allow any address' }] : []),
+ { value: 'how', label: 'Add an address or range…' },
+ { value: 'back', label: 'Back' },
+ ]);
+ if (v === 'any') await runServerCommand('allow-any', ops, ui);
+ else if (v?.startsWith('remove:')) await runServerCommand(`remove-ip ${v.slice(7)}`, ops, ui);
+ else if (v === 'how') await ui.say(`Type /server allow-ip <address or range>, e.g. 203.0.113.7, or 100.64.0.0/10 for a Tailscale network.${s.lastRemote && !s.lastRemote.clientIpKnown ? '\nNote: your tunnel does not pass client addresses yet, so a list would refuse every remote device.' : ''}`);
+ }
+ if (pick === 'pending') {
+ const v = await ui.choose('Waiting for you', [...s.pending.map((p) => ({ value: p.id, label: `${p.title}${p.ip ? ` · ${p.ip}` : ''} · code ${p.code}` })), { value: 'back', label: 'Back' }]);
+ const q = s.pending.find((p) => p.id === v);
+ if (q) {
+ const d = await ui.choose(`${q.title}${q.detail ? ` — ${q.detail}` : ''}`, [{ value: 'allow', label: q.kind === 'pair' ? 'Approve this device' : 'Allow it, once' }, { value: 'deny', label: 'Deny' }, { value: 'back', label: 'Back' }]);
+ if (d === 'allow' || d === 'deny') {
+ const a = await ops.decide(q.id, d);
+ await ui.say(a ? `${a.status === 'allowed' ? '✓ Approved' : '✗ Denied'}: ${a.title}.` : 'That question has expired.');
+ }
+ }
+ }
+ if (pick === 'devices') await devicesMenu(ops, ui);
+ }
+}
+
+async function devicesMenu(ops: ServerOps, ui: ServerUi): Promise<void> {
+ for (let guard = 0; guard < 100; guard++) {
+ const s = await ops.status();
+ const r = s.remote;
+ const v = await ui.choose(`Devices (${s.devices.length} of ${r.maxDevices})`, [
+ ...s.devices.map((d) => ({ value: `dev:${d.id}`, label: deviceLine(d) })),
+ { value: 'token', label: 'Make a token for a device…' },
+ ...(s.devices.length > 1 ? [{ value: 'all', label: 'Sign out every device' }] : []),
+ { value: 'expire', label: `Unused devices expire: ${r.idleDays ? `after ${r.idleDays} days` : 'never'}` },
+ { value: 'limit', label: `Device limit: ${r.maxDevices}` },
+ { value: 'back', label: 'Back' },
+ ]);
+ if (!v || v === 'back') return;
+ if (v === 'token') await runServerCommand('token Manual token', ops, ui);
+ if (v === 'all') {
+ const sure = await ui.choose('Sign out every device? Each one needs your approval to come back.', [{ value: 'yes', label: 'Sign them all out' }, { value: 'no', label: 'Cancel' }]);
+ if (sure === 'yes') await runServerCommand('revoke-all', ops, ui);
+ }
+ if (v === 'expire') {
+ const e = await ui.choose('Unused devices stop working after', [7, 30, 90, 365].map((d) => ({ value: String(d), label: `${d} days${r.idleDays === d ? ' (now)' : ''}` })).concat([{ value: 'never', label: `Never${r.idleDays === 0 ? ' (now)' : ''}` }]));
+ if (e) await runServerCommand(`expire ${e}`, ops, ui);
+ }
+ if (v === 'limit') {
+ const l = await ui.choose('How many devices can be paired', [3, 5, 10, 20, 50].map((n) => ({ value: String(n), label: `${n}${r.maxDevices === n ? ' (now)' : ''}` })));
+ if (l) await runServerCommand(`limit ${l}`, ops, ui);
+ }
+ if (v.startsWith('dev:')) {
+ const d = s.devices.find((x) => x.id === v.slice(4));
+ if (!d) continue;
+ const a = await ui.choose(`${d.name} — paired ${d.createdAt.slice(0, 10)}${d.approvedBy ? ` (approved on ${d.approvedBy})` : ''}, last used ${ago(d.lastSeenAt)}${d.lastIp ? ` from ${d.lastIp}` : ''}${d.expiresAt ? `, expires ${d.expiresAt.slice(0, 10)} if unused` : ''}`, [
+ { value: 'revoke', label: 'Sign this device out' },
+ { value: 'back', label: 'Back' },
+ ]);
+ if (a === 'revoke') await runServerCommand(`revoke ${d.id}`, ops, ui);
+ }
+ }
+}
diff --git a/src/security/server-ops.ts b/src/security/server-ops.ts
new file mode 100644
index 00000000..4725fc33
--- /dev/null
+++ b/src/security/server-ops.ts
@@ -0,0 +1,90 @@
+import { createDevice, getDevice, listDevices, revokeAllDevices, revokeDevice } from '../web/devices.js';
+import { lastRemoteRequest } from '../web/middleware.js';
+import { approvalRoutes } from '../web/owner-gate.js';
+import { sessionCount } from '../web/auth.js';
+import { ownerApprovals } from './owner-approvals.js';
+import { readRemoteSettings, writeRemoteSettings, type RemoteSettings } from './remote-settings.js';
+import { audit, readAudit } from './audit.js';
+import { closeStreams } from './live-streams.js';
+import { securityCheck, summarizeFindings } from './check.js';
+import type { ServerOps, ServerStatus } from './server-menu.js';
+
+/**
+ * The /server operations inside the running Mercury (the chat command and
+ * the /api/security routes): its own state, directly.
+ */
+export function localServerOps(opts: { cloudConnected?: () => boolean; by?: string } = {}): ServerOps {
+ const by = opts.by ?? 'this computer';
+ return {
+ async status(): Promise<ServerStatus> {
+ const findings = securityCheck({ lastRemote: lastRemoteRequest(), cloudConnected: opts.cloudConnected?.() ?? false });
+ return {
+ remote: readRemoteSettings(),
+ devices: listDevices(),
+ browsers: sessionCount(),
+ pending: ownerApprovals().pending(),
+ approvalRoutes: approvalRoutes(),
+ lastRemote: lastRemoteRequest(),
+ check: { summary: summarizeFindings(findings), findings },
+ };
+ },
+ async setRemote(patch: Partial<RemoteSettings>) {
+ 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, detail: changes.map((k) => `${k}: ${JSON.stringify(next[k])}`).join(', ') });
+ },
+ async decide(idOrCode, decision) {
+ const a = ownerApprovals().decide(idOrCode, decision, by);
+ 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 a;
+ },
+ async createDevice(name) {
+ const created = createDevice(name, 'manual', by);
+ audit('pair.local', { who: created.device.name, detail: 'token made on this computer' });
+ return created;
+ },
+ async revoke(id) {
+ const name = getDevice(id)?.name ?? id;
+ if (!revokeDevice(id)) return false;
+ closeStreams(`device:${id}`);
+ audit('device.revoked', { who: name, by });
+ return true;
+ },
+ async revokeAll() {
+ const ids = revokeAllDevices();
+ for (const id of ids) closeStreams(`device:${id}`);
+ if (ids.length) audit('device.revoked', { who: `${ids.length} devices (all)`, by });
+ return ids.length;
+ },
+ async audit(limit) {
+ return readAudit(limit);
+ },
+ };
+}
+
+/**
+ * The same operations from another process on this computer (`mercury
+ * server` while Mercury runs): through its API, with the local attach token.
+ */
+export function httpServerOps(base: string, token: string): ServerOps {
+ const call = async <T>(path: string, init: RequestInit = {}): Promise<T> => {
+ const res = await fetch(`${base}${path}`, { ...init, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...(init.headers ?? {}) } });
+ const body = await res.json().catch(() => ({})) as T & { error?: string };
+ if (!res.ok && res.status !== 410) throw new Error(body.error ?? `Mercury answered ${res.status}`);
+ return body;
+ };
+ return {
+ status: () => call<ServerStatus>('/api/security/status'),
+ async setRemote(patch) { await call('/api/security/remote', { method: 'PUT', body: JSON.stringify(patch) }); },
+ async decide(idOrCode, decision) {
+ const r = await call<{ approval?: import('./owner-approvals.js').OwnerApproval }>(`/api/security/approvals/${encodeURIComponent(idOrCode)}`, { method: 'POST', body: JSON.stringify({ decision, by: 'cli' }) });
+ return r.approval ?? null;
+ },
+ createDevice: (name) => call('/api/security/devices', { method: 'POST', body: JSON.stringify({ name }) }),
+ async revoke(id) { await call(`/api/security/devices/${encodeURIComponent(id)}`, { method: 'DELETE' }); return true; },
+ async revokeAll() { return (await call<{ revoked: number }>('/api/security/devices', { method: 'DELETE' })).revoked; },
+ async audit(limit) { return (await call<{ entries: import('./audit.js').AuditEntry[] }>(`/api/security/audit?limit=${limit}`)).entries; },
+ };
+}
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 098d44d3..66263e82 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -134,6 +134,11 @@ export const CHAT_COMMAND_HELP: ReadonlyArray<readonly [string, string]> = [
['/code chat', 'Switch back to regular chat instantly (alias: /code back)'],
['/chat', 'Return to chat mode (tears down Mercury Code if active)'],
['/code toggle', 'Cycle through: off → auto → plan → execute → off'],
+ ['/server', 'Remote access and security: devices, approvals, allowed addresses (this computer only)'],
+ ['/server approve <code>', 'Let a waiting device or remote action through (/server deny <code> refuses)'],
+ ['/server devices', 'Paired devices; /server revoke <id|name> signs one out'],
+ ['/server on | off', 'Allow or refuse other devices'],
+ ['/server check', 'The security check'],
['/research', 'Show research status'],
['/research on', 'Research your next message here (live sources, full report), then switch off'],
['/research off', 'Cancel research for your next message'],
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 2ffee8ef..1a359e64 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -54,6 +54,7 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'artifacts.convert', // GET /api/artifacts/:id/file?as=pdf|docx, POST /api/artifacts/:id/export { dest, as } — Markdown/text as PDF or Word
'artifacts.folder', // GET /api/artifacts/folder (the output folder, loose files), POST /api/artifacts/folder/tidy
'chat.favicon', // GET /api/chat/favicon?domain= — a site's icon (204 when it has none), fetched and cached by the runtime
+ 'security.remote', // device pairing needs the owner (202 + POST /api/auth/token/pending), sensitive remote actions 428 + X-Mercury-Approval, /api/security/* (this computer), SSE 'owner_approval' (local activity), expired devices 401 { expired }
'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }
]);
diff --git a/src/web/api/auth.ts b/src/web/api/auth.ts
index 8aa31fa5..9b91f957 100644
--- a/src/web/api/auth.ts
+++ b/src/web/api/auth.ts
@@ -157,6 +157,8 @@ interface PendingPairing {
deviceName: unknown;
platform: unknown;
ip?: string;
+ /** Who asked (the sign-in limiter's key), so one client can't pile up questions. */
+ client: string;
/** Set once the token was handed out: a second poll can't mint another. */
done?: boolean;
}
@@ -208,6 +210,9 @@ auth.post('/api/auth/token', async (c) => {
}
}
+ // One waiting sign-in per client at a time: asking again doesn't message the owner again.
+ const waitingHere = [...pairings.values()].filter((p) => !p.done && p.client === key && ownerApprovals().get(p.approvalId)?.status === 'pending');
+ if (waitingHere.length >= 2) return c.json({ error: 'A sign-in from here is already waiting for the owner. Wait for their answer.' }, 429);
// 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);
@@ -224,7 +229,7 @@ auth.post('/api/auth/token', async (c) => {
}, 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 });
+ pairings.set(pairingId, { approvalId: approval.id, pollHash: sha(pollToken), deviceName: body.deviceName, platform: body.platform, ip, client: key });
const timer = setTimeout(() => pairings.delete(pairingId), PAIRING_TTL_MS + 5 * 60_000);
timer.unref?.();
audit('pair.requested', { who: name, ip });
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 4c177225..01f00fb4 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -300,7 +300,7 @@ chat.post('/api/chat/send', async (c) => {
}
codeCwd = resolvedCwd;
}
- webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments, programming ? { programming, cwd: codeCwd } : undefined);
+ webChannel.emitMessageInThread(text, session.id, session.id, undefined, undefined, undefined, upload.attachments, { ...(programming ? { programming, cwd: codeCwd } : {}), thisComputer: isThisComputer(c) });
return c.json({
sent: true,
sessionId: session.id,
diff --git a/src/web/owner-gate.ts b/src/web/owner-gate.ts
index ab11ef33..8b82ba8a 100644
--- a/src/web/owner-gate.ts
+++ b/src/web/owner-gate.ts
@@ -15,6 +15,7 @@ import { isThisComputer, originOf, principalKey, principalLabel, principalOf } f
*/
export const ACTION_APPROVAL_TTL_MS = 10 * 60_000;
+const MAX_OPEN_PER_DEVICE = 3;
/** Where approvals reach the owner ("Telegram", "this computer"), for the message the device shows. */
let routes: () => string[] = () => ['this computer'];
@@ -54,8 +55,15 @@ export function requireOwner(c: Context, action: SensitiveAction): Response | nu
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 });
+ // Asking again (a retry, a double click) reuses the question already waiting:
+ // a device can't flood the owner's phone. Three open questions per device at most.
+ const scope = { principal: key, action: action.id };
+ const open = approvals.pendingFor(scope);
+ if (!open && approvals.pendingCount(key) >= MAX_OPEN_PER_DEVICE) {
+ return c.json({ error: 'Too many questions are waiting for the owner from this device. Wait for an answer first.', tooManyApprovals: true }, 429);
+ }
+ const a = open ?? approvals.request({ kind: 'action', title: action.title, detail: action.detail, who, ip, scope }, ACTION_APPROVAL_TTL_MS);
+ if (!open) 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,