8000 fix(security): same-origin and host checks on routes that write to agents (#222) by simon-inkie · Pull Request #227 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions .specs/222-origin-checks-agent-routes/SPEC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# #222: Check request origins on agent write routes

- Issue: https://github.com/simon-inkie/inkie-deck/issues/222
- Branch: origin-checks-agent-routes
- Started: 2026-11-19

## TL;DR

Reuse the Nudges origin and Host checks before Deck sends terminal input or
writes to threads, agent settings, project cards or workspace drafts. Keep
same-origin browser access through trusted tunnels and direct loopback scripts
working without changing Nudges' stricter remote admin policy.

## Scope

In scope:
- Guard `/api/tmux-send`, `/threads/:agent`, `/`, `/api/agent-model`,
`/projects` and `/api/drafts` before any write, upload or terminal call.
- Guard the chat loader's inbox read receipt as well as the thread action.
- Approve loopback, the configured bind host and explicitly listed extra
hosts. Check fetch metadata and match any Origin against Host, not the
server-side URL or forwarding headers.

Out of scope:
- Changes to Nudge permissions, read routes, data-only actions or authentication.
- Live agent, terminal, tunnel or browser-server testing.

## Test plan

- Exercise the route actions with stubbed tmux and side effects. Check 403
before side effects for cross-site, same-site, mismatched Origin and an
unapproved Host. Check same-origin browser writes, including via an
approved proxy host, and direct header-less loopback writes.
- Verify that chat navigation still returns 200 without writing a receipt
when the write checks fail, including over plain HTTP on an approved LAN
host with neither browser header. Verify that allowed requests still mark
the thread read.
- Run the touched Vitest files and Nudge tests:

```sh
pnpm -C packages/deck exec vitest run test/request-origin-routes.test.ts \
test/tmux-send.test.ts test/threads-compose-subject.test.ts \
test/thread-pane-hints.test.ts test/agent-model.test.ts test/drafts.test.ts \
test/api-cron.test.ts test/scheduler-route.test.ts test/cron.server.test.ts \
test/cron-validate.test.ts
```

- Run `pnpm typecheck`, `node scripts/leak-gate.mjs`, `pnpm check:leaks`,
`node packages/deck/scripts/check-dashes.mjs`, and `git diff --check`.

## Follow-ups

None.

## Log

### 2026-11-19: Trace write actions
- What changed: Identified terminal sends, thread actions (including uploads),
home action-card writebacks, model settings, projects and drafts. Scheduler
and the cron API already use the Nudge guard.
- Why: Drafts already check a voice origin allowlist, but the request also
needs an approved Host and matching Origin. Keep additional write hosts
separate from the remote cron opt-in so tunnels do not enable cron admin.
- Supersedes: nothing, additive
- Commits: pending

### 2026-11-19: Guard the chat receipt and document proxy hosts
- What changed: Applied the guard to the chat loader before marking messages
read. Terminal view still does not write receipts. Added MC_ALLOWED_HOSTS
for tunnel names and documented that a proxy must preserve Host.
- Why: The chat loader writes outside DATA_ROOT even on GET. The UI's form
actions and fetch URLs are relative to Deck, so they remain same-origin.
- Supersedes: nothing, additive
- Commits: pending

### 2026-11-19: Verify the route matrix
- What changed: Targeted Vitest run passed 495 tests with 11 skipped. Both
leak scans, the direct dash scan, typecheck and diff checks passed.
- Why: Route tests stub tmux and verify rejected requests never reach a write.
Validation used closed stdin and file-backed capture for sandboxed child
processes that could not use Node's default sync subprocess pipes.
- Supersedes: nothing, additive
- Commits: 4a406e7 fix(security): same-origin and host checks on routes that write to agents (#222)

### 2026-11-19: Keep chat navigation readable without origin proof
- What changed: The chat loader skips the read receipt when the write checks
fail and still serves the thread. Explicit write actions still return 403.
- Why: The PR review found that browsers can omit both Origin and fetch
metadata on plain HTTP LAN navigation, even when the Host is approved.
- Supersedes: Guard the chat receipt and document proxy hosts (loader refusal only)
- Commits: pending
20 changes: 18 additions & 2 deletions INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -675,8 +675,8 @@ shell variable does not survive one.

### Reaching it from another machine

When `HOST` is not loopback, anyone who can open this page can message your
agents and, if enabled, create scheduled jobs on this machine.
Anyone who can open Deck through an approved Host can message your agents.
Scheduled jobs have a separate admin check, covered under Scheduled nudges.

Skip this unless you need it. Deck binds loopback by default and that default
is doing real work: **there is no authentication in front of the thing you are
Expand All @@ -692,6 +692,21 @@ This is also the line a container image needs. A published port against a
loopback bind is silent: you get a connection refused from a launcher that is
still reporting a healthy start.

Writes to agent threads, terminals, model settings, project cards and drafts
require an approved `Host`. Deck accepts `localhost`, supported loopback IPs
and the host configured in `HOST`. For other addresses, set `MC_ALLOWED_HOSTS`
to a comma-separated list of trusted hostnames or IP addresses, without schemes
or ports. A proxy or tunnel must preserve the public Host, including the port
if present, so that it matches the browser's Origin. This does not enable remote
Nudge editing or replace access control.

Deck refuses cross-site and same-site writes. If a chat navigation fails the
write checks, Deck still opens the thread without marking messages as read.
This can happen on plain HTTP over a LAN even with an approved `Host`, because
browsers may omit both `Origin` and `Sec-Fetch-Site`. Without either header,
only a direct loopback connection can write. Drafts use these same checks
rather than the separate voice origin allowlist.

### Build, and start

```sh
Expand Down Expand Up @@ -827,6 +842,7 @@ Then tell the proxy about the origin and the browser about the proxy, where
the admin console show it:

```text
MC_ALLOWED_HOSTS=<tailnet-host>
VOICE_ALLOWED_ORIGINS=https://<tailnet-host>
VOICE_PROXY_URL=wss://<tailnet-host>:8443/voice
```
Expand Down
11 changes: 8 additions & 3 deletions packages/deck/.env.example
8000
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ MC_USER=
# line at boot whenever it binds loopback, so you are not left guessing.
HOST=

# Optional: extra trusted hostnames or IP addresses for agent, project and
# draft writes. Comma-separated, no schemes or ports. Proxies must preserve
# the public Host. This does not allow remote Nudge administration.
# MC_ALLOWED_HOSTS=deck.example.com
MC_ALLOWED_HOSTS=

# Optional: the port the production launcher binds. Default 4242.
PORT=

Expand Down Expand Up @@ -202,8 +208,7 @@ MC_LIVE_SILO_ROOT=
# Optional: absolute path to the workspace. Setting it turns on the Drafts
# editor: Markdown files under <WORKSPACE_ROOT>/drafts/, editable in the Deck
# and by agents as ordinary files. Unset = no Drafts link.
# Saving from the browser also requires the page's origin to be listed in
# VOICE_ALLOWED_ORIGINS above (the Drafts editor reuses that allowlist so a
# hostile page cannot write drafts); the default covers http://localhost:$PORT.
# Browser saves require a same-origin request and an approved Host, as for
# agent writes. Use MC_ALLOWED_HOSTS above for extra trusted hosts.
# WORKSPACE_ROOT=/home/you/deck/workspace
WORKSPACE_ROOT=
44 changes: 4 additions & 40 deletions packages/deck/app/lib/nudge-admin.server.ts
10000
Original file line number Diff line number Diff line change
@@ -1,54 +1,18 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { isIP } from "node:net";
8BD0 import type { AppLoadContext } from "react-router";
import { isLoopbackAddress, isLoopbackHost } from "../../server/bind-host.mjs";
import { hasSameOriginProof, isAllowedHost, isDirectLoopback } from "./request-origin.server";

export const devSocketAddress = new AsyncLocalStorage<string | undefined>();
export { devSocketAddress } from "./request-origin.server";

export const NUDGES_READ_ONLY =
"Nudges editing requires an allowed Host, such as localhost. Remote editing also requires MC_CRON_ALLOW_REMOTE_ADMIN=1 on the server. With that setting, IP addresses and names in MC_CRON_ALLOWED_HOSTS are also allowed.";

function isDirectLoopback(request: Request, context: AppLoadContext) {
const address = context?.socketAddress ?? devSocketAddress.getStore();
return isLoopbackAddress(address) &&
!["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-real-ip"]
.some((header) => request.headers.has(header));
}

function isAllowedHost(host: string | null, allowRemote: boolean) {
if (!host) return false;
const rawHostname = host.match(/^(\[[\da-f:.]+\]|[a-z\d.-]+)(?::\d+)?$/i)?.[1];
if (!rawHostname) return false;
const hostname = URL.parse(`http://${host}`)?.hostname.replace(/^\[|\]$/g, "");
if (hostname === undefined) return false;
if (isLoopbackHost(hostname) || hostname === "::ffff:7f00:1" ||
hostname === process.env["HOST"]?.toLowerCase()
) return true;
if (!allowRemote) return false;

return isIP(rawHostname.replace(/^\[|\]$/g, "")) !== 0 ||
(process.env["MC_CRON_ALLOWED_HOSTS"]?.split(",")
.some((allowedHost) => allowedHost.trim().toLowerCase() === hostname) ?? false);
}

export function canManageNudges(request: Request, context: AppLoadContext) {
const allowRemote = process.env["MC_CRON_ALLOW_REMOTE_ADMIN"] === "1";
return isAllowedHost(request.headers.get("host"), allowRemote) &&
const extraHosts = allowRemote ? process.env["MC_CRON_ALLOWED_HOSTS"] : undefined;
return isAllowedHost(request.headers.get("host"), extraHosts, allowRemote) &&
(allowRemote || isDirectLoopback(request, context));
}

function hasSameOriginProof(request: Request, context: AppLoadContext) {
const site = request.headers.get("sec-fetch-site");
if (site !== null && site !== "same-origin" && site !== "none") return false;

const origin = request.headers.get("origin");
if (origin === null) return site !== null || isDirectLoopback(request, context);

const parsed = URL.parse(origin);
if (!parsed || !/^https?:$/.test(parsed.protocol) || parsed.origin !== origin.toLowerCase()) return false;
return parsed.host === URL.parse(`${parsed.protocol}//${request.headers.get("host")}`)?.host;
}

export function requireNudgeAdmin(request: Request, context: AppLoadContext) {
if (!canManageNudges(request, context)) {
throw new Response(NUDGES_READ_ONLY, { status: 403 });
Expand Down
59 changes: 59 additions & 0 deletions packages/deck/app/lib/request-origin.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { isIP } from "node:net";
import type { AppLoadContext } from "react-router";
import { isLoopbackAddress, isLoopbackHost } from "../../server/bind-host.mjs";

export const devSocketAddress = new AsyncLocalStorage<string | undefined>();

export function isDirectLoopback(request: Request, context: AppLoadContext) {
const address = context?.socketAddress ?? devSocketAddress.getStore();
return isLoopbackAddress(address) &&
!["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-real-ip"]
.some((header) => request.headers.has(header));
}

export function isAllowedHost(host: string | null, extraHosts?: string, allowAnyIp = false) {
if (!host) return false;
const rawHostname = host.match(/^(\[[\da-f:.]+\]|[a-z\d.-]+)(?::\d+)?$/i)?.[1];
if (!rawHostname) return false;
const hostname = URL.parse(`http://${host}`)?.hostname.replace(/^\[|\]$/g, "");
if (hostname === undefined) return false;
if (isLoopbackHost(hostname) || hostname === "::ffff:7f00:1" ||
hostname === process.env["HOST"]?.toLowerCase()
) return true;

return (allowAnyIp && isIP(rawHostname.replace(/^\[|\]$/g, "")) !== 0) ||
(extraHosts?.split(",").some((allowedHost) => allowedHost.trim().toLowerCase() === hostname) ?? false);
}

export function hasSameOriginProof(request: Request, context: AppLoadContext) {
const site = request.headers.get("sec-fetch-site");
if (site !== null && site !== "same-origin" && site !== "none") return false;

const origin = request.headers.get("origin");
if (origin === null) return site !== null || isDirectLoopback(request, context);

const parsed = URL.parse(origin);
if (!parsed || !/^https?:$/.test(parsed.protocol) || parsed.origin !== origin.toLowerCase()) return false;
return parsed.host === URL.parse(`${parsed.protocol}//${request.headers.get("host")}`)?.host;
}

function hasAllowedWriteHost(request: Request): boolean {
return isAllowedHost(request.headers.get("host"), process.env["MC_ALLOWED_HOSTS"]);
}

export function canWriteFromRequest(request: Request, context: AppLoadContext): boolean {
return hasAllowedWriteHost(request) && hasSameOriginProof(request, context);
}

export function requireSameOriginWrite(request: Request, context: AppLoadContext) {
if (canWriteFromRequest(request, context)) return;

const error = hasAllowedWriteHost(request)
? "Writes require a same-origin request."
: "Writes require an allowed Host. Add trusted public hostnames to MC_ALLOWED_HOSTS.";
throw Response.json({ ok: false, error }, {
status: 403,
headers: { "Cache-Control": "private, no-store" },
});
}
4 changes: 3 additions & 1 deletion packages/deck/app/routes/api.agent-model.tsx
< 10BC8 td class="blob-code blob-code-context js-file-line"> import { AGENT_NAME_RE } from "~/lib/safe-fs.server";
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import { z } from "zod";
import { data } from "react-router";
import type { Route } from "./+types/api.agent-model";
import { requireSameOriginWrite } from "~/lib/request-origin.server";
import { getAgentModelInfo, setAgentModel } from "~/lib/agent-model.server";
import { modelSelectorEnabled } from "~/lib/instance.server";
Expand Down Expand Up @@ -58,7 +59,8 @@ export async function loader({ request }: Route.LoaderArgs) {
};
}

export async function action({ request }: Route.ActionArgs) {
export async function action({ request, context }: Route.ActionArgs) {
requireSameOriginWrite(request, context);
if (!modelSelectorEnabled(process.env)) {
return data({ error: GATE_MESSAGE }, { status: 403 });
}
Expand Down
36 changes: 4 additions & 32 deletions packages/deck/app/routes/api.drafts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
* -> { ok: true, draft } or { ok: false, error, conflict?, current? } with a
* 409 on a conflict (the file changed outside the editor).
*
* SEAM RULE: imports only drafts.server; no fs in the route.
* SEAM RULE: no fs in the route.
* ASCII only - no em-dashes.
*/
import type { Route } from "./+types/api.drafts";
import { resolveAllowedOrigins } from "../../server/voice-relay.mjs";
import { requireSameOriginWrite } from "~/lib/request-origin.server";
import {
draftsEnabled,
listDrafts,
Expand Down Expand Up @@ -45,36 +45,8 @@ export async function loader({ request }: Route.LoaderArgs) {
return res.ok ? json(res) : json(res, res.status);
}

/**
* Refuse a browser-initiated write from an origin Deck does not expect. Deck
* has no authentication, so a page on another origin that the person's browser
* can use to reach this server could otherwise POST (even with force=1) and
* overwrite a draft by name.
*
* The Origin header is checked against an ALLOWLIST (the same mechanism and
* env var as the voice proxy: VOICE_ALLOWED_ORIGINS, default
* http://localhost:$PORT plus the dev port), not against the Host header.
* Comparing against Host is defeated by DNS rebinding, where the attacker
* controls both. Browsers always send Origin on POSTs, so a browser request
* with a missing-from-list or "null" Origin is refused; so is any
* Sec-Fetch-Site other than same-origin or none. Requests with neither header
* (an agent using curl) are not browser cross-site requests and pass.
*
* Reaching Deck by another name (a tailnet host, a Host-rewriting proxy)
* requires listing that origin in VOICE_ALLOWED_ORIGINS, exactly as for voice.
*/
function crossOriginWrite(request: Request): boolean {
const site = request.headers.get("sec-fetch-site");
if (site && site !== "same-origin" && site !== "none") return true;
const origin = request.headers.get("origin");
if (origin === null) return false;
return !resolveAllowedOrigins(process.env).includes(origin);
}

export async function action({ request }: Route.ActionArgs) {
if (crossOriginWrite(request)) {
return json({ ok: false, error: "Cross-origin writes are not allowed. If you reach Deck by another name, list that origin in VOICE_ALLOWED_ORIGINS." }, 403);
}
export async function action({ request, context }: Route.ActionArgs) {
requireSameOriginWrite(request, context);
if (!draftsEnabled(process.env)) {
return json({ ok: false, error: "Drafts are not configured." }, 404);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/deck/app/routes/api.tmux-send.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
SEND_KEYS_MAX_LEN,
} from "~/lib/tmux.server";
import { tmuxEnabled } from "~/lib/instance.server";
import { requireSameOriginWrite } from "~/lib/request-origin.server";

const windowSchema = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
const sendSchema = z.union([
Expand All @@ -43,7 +44,8 @@ const sendSchema = z.union([
z.object({ window: windowSchema, key: z.enum(SEND_KEYS_ALLOWED_KEYS) }).strict(),
]);

export async function action({ request }: Route.ActionArgs) {
export async function action({ request, context }: Route.ActionArgs) {
requireSameOriginWrite(request, context);
// Server-side gate, not just hidden UI - a tmux-disabled instance (such as a
// second user's) refuses sends even if the endpoint is POSTed directly.
if (!tmuxEnabled(process.env)) {
Expand Down
4 changes: 3 additions & 1 deletion packages/deck/app/routes/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { RouteErrorPanel } from "~/components/RouteErrorPanel";
import { useFetcher, Link, useSearchParams } from "react-router";
import { useCallback } from "react";
import { makeStores } from "~/lib/stores.server";
import { requireSameOriginWrite } from "~/lib/request-origin.server";
import { resolveNow } from "~/lib/time";
import { mcUser, filterCardsForInstance } from "~/lib/instance.server";
import { listCards } from "~/lib/projects.server";
Expand Down Expand Up @@ -98,7 +99,8 @@ const homeActionSchema = z.discriminatedUnion("intent", [
// Action
// ---------------------------------------------------------------------------

export async function action({ request }: Route.ActionArgs) {
export async function action({ request, context }: Route.ActionArgs) {
requireSameOriginWrite(request, context);
const formData = await request.formData();
const raw = Object.fromEntries(formData);
const parsed = homeActionSchema.safeParse(raw);
Expand Down
Loading
Loading
0