8000 feat(nudges): enable Nudges by default with a loopback-only admin guard (#212) by simon-inkie · Pull Request #219 · 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
90 changes: 90 additions & 0 deletions .specs/212-nudges-default-on/SPEC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# #212: Nudges on by default

- Issue: #212
- Branch: nudges-default-on
- Started: 2026-11-18

## TL;DR
`cronAdminEnabled` only opened for two hard-coded MC_USER names, so Nudges
(`/scheduler`, `api/cron`) was hidden on any install that sets MC_USER, as
INSTALL.md tells people to. It is now on by default for everyone, with
`MC_CRON_ADMIN_ENABLED=0`/`false` as the off switch. The page and API now say
plainly when `crontab` is missing and refuse writes before anything is
written, a throwing write comes back as an error instead of a 500, and the
`pnpm dev` sandbox turns Nudges off so it cannot touch the real crontab.
Writes require a direct loopback socket unless `MC_CRON_ALLOW_REMOTE_ADMIN=1`
is set. Either way, writes require an allowed Host and same-origin browser
headers; direct loopback clients can omit both browser headers. Other
connections can still view Nudges without editing controls.
With remote admin enabled, IP literals and names in `MC_CRON_ALLOWED_HOSTS`
are also allowed, including when `HOST` is a wildcard bind address.

## Scope
In scope:
- Gate: default on, explicit opt-out, generic doc comments.
- `api/cron` GET now behind the same gate (404 when off); it was ungated.
- Missing `crontab` (PATH lookup, never runs it) and throwing seam handling.
- Dev sandbox default off; INSTALL.md section and `.env.example` entry.
- Socket, Host and browser-origin write guards for both routes, plus
network-bind warnings.
Out of scope:
- README (separate PR).
- The nudge script's hard-coded `agents` tmux session name (same limitation
as `boot-agents.sh`, already in INSTALL.md known limitations).

## Test plan
- `test/instance.test.ts`: default on for any MC_USER; 0/false (any case,
padded) off; other values stay on.
- `test/api-cron.test.ts`: real seam bound to in-memory fake deps; GET 404
when off; POST refused when off; missing crontab; throwing seam; injection.
- `test/scheduler-route.test.ts`: same for the page loader and action.
- Both route suites cover local and remote access with fake cron seams;
the scheduler suite also renders the remote read-only view.
- Browser writes cover same-origin, cross-site, same-site, mismatched Origin
and DNS rebinding, plus direct loopback CLI compatibility.
- The cron API suite covers IPv4, bracketed IPv6 and explicitly listed names
on a wildcard bind, with and without the remote opt-in.
- `test/cron.server.test.ts`: `crontabAvailable` against temp-dir PATHs.
No test reads or writes the real crontab.

## Follow-ups
None filed.

## Log
### 2026-11-18: default on, degrade without crontab
- What changed: gate rewritten; crontab check and try/catch in both routes;
sandbox default off; api-cron tests moved off the real seam deps.
- Why: the old api-cron suite ran the real `createCron` with default deps and
relied on the gate or an unknown target to stop before a write; with the
gate open by default that was one fixture change from writing the real
crontab.

### 2026-11-19: restrict Nudges writes to direct loopback
- What changed: pass the socket peer through the production adapter and Vite
middleware, refuse non-local writes by default, and warn on network binds.
- Why: the default adapters do not expose the peer to routes, and forwarded
addresses cannot grant write access. A loopback proxy must mark forwarded
requests or have Nudges disabled, as documented in INSTALL.md.
- Supersedes: nothing, additive
- Commits: e864545 feat(nudges): loopback-only admin guard and network bind warning (#212)

### 2026-11-19: verify the Host and origin of Nudges writes
- What changed: both actions require an allowed Host and reject cross-origin
writes even with remote admin enabled. Direct loopback clients can still
omit both browser headers.
- Why: Devin review found that the socket alone does not distinguish a local
visitor from a cross-origin form submitted by that visitor's browser.
Comparing Origin to Host alone would also allow DNS rebinding. No other
route writes crontab; terminal sends and thread-to-tmux delivery still lack
an origin check and are outside this fix.
- Supersedes: 2026-11-19 socket-only write guard; keeps the socket check.
- Commits: 2fa6d1b fix(nudges): refuse cross-origin and unapproved-host nudge writes (#212)

### 2026-11-19: allow remote IP literals and configured hostnames
- What changed: remote admin opt-in also allows IP literals and hostnames in
`MC_CRON_ALLOWED_HOSTS`. Unknown hostnames are still refused, and the
same-origin checks are unchanged.
- Why: Devin review found that a wildcard bind such as `HOST=0.0.0.0` does not
match the LAN address in a request's Host header, blocking opted-in writes.
- Supersedes: the remote Host rules in the 2026-11-19 Host and origin guard.
- Commits: 71dd799 fix(nudges): accept IP-literal and listed hosts when remote admin is on (#212)
55 changes: 53 additions & 2 deletions INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -607,8 +607,8 @@ questions, and only the second one matters.

Two things this tier does not do. It is reachable only from the machine it
runs on (the dev server binds loopback, and a container port map published
against it gets nothing); and it has no tmux, no agents and no clock that
moves. For those, keep going.
against it gets nothing); and it has no tmux, no agents, no Nudges and no
clock that moves. For those, keep going.

## 4. Run it for real

Expand Down Expand Up @@ -675,6 +675,9 @@ 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.

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
about to publish**, so read the warning at the top of this document again
Expand Down Expand Up @@ -1251,6 +1254,54 @@ The reply is now in the thread, which you can see from Deck:
curl -sS http://localhost:4242/threads/inkie | grep -c 'the whole protocol'
```

### Scheduled nudges

The Nudges page (`/scheduler`, linked from the top bar) sends an agent a
prompt, or runs a shell script, on a cron schedule. Each nudge is a line in the
system crontab of the user Deck runs as, tagged `# MC-CRON:<id>`, plus a script
in `~/agents/<agent>/bin/`. Lines without that tag are never touched. It needs
`crontab` on `PATH`; without it the page says so and saves nothing. An agent
nudge is pasted into the agent's window in the `agents` tmux session, and if
that session is not running when it fires, the run is skipped and the page
shows it as fired but not delivered.

Nudges is on by default. To edit nudges, connect directly from the Deck
machine over loopback (`127.0.0.1`, `::1` or `::ffff:127.0.0.1`). Other
visitors can view the page but cannot change anything. Deck uses the socket
address, never a forwarded address; requests carrying forwarding headers
are read-only by default. If a reverse proxy connects over loopback, make
sure it adds a forwarding header such as `X-Forwarded-For`, or disable
Nudges: without that header Deck cannot distinguish the proxy from a local
visitor.

Writes also require a `Host` of `localhost`, a supported loopback IP, or
the hostname configured in `HOST`. The browser's `Sec-Fetch-Site` must be
`same-origin` or `none` if present, and any `Origin` must match the request
`Host` (including the port). Command-line clients such as `curl` can omit
both headers only on a direct loopback connection, so local scripts keep
working.

To allow remote writes deliberately, set `MC_CRON_ALLOW_REMOTE_ADMIN=1` in
the server environment (or `packages/deck/.env` for the documented launcher)
and restart Deck. This also accepts any IPv4 or bracketed IPv6 address in
`Host`, including the LAN address when Deck binds to `0.0.0.0`. To allow
extra hostnames, set `MC_CRON_ALLOWED_HOSTS` to a comma-separated list such as
`deck.example.com,nudges.example.com`, without schemes or ports. The list is
ignored without the remote opt-in, and unknown hostnames are still refused.
The origin checks still apply. A reverse proxy should validate and preserve
the public Host rather than rewrite it to localhost. Only enable remote
writes behind access control you trust: a visitor who passes those checks can
schedule jobs as the user running Deck.

To turn Nudges off entirely:

```sh
echo "MC_CRON_ADMIN_ENABLED=0" >> packages/deck/.env
```

That removes the nav entry, makes the page and `api/cron` answer 404, and
refuses every write. `pnpm dev` already turns it off for the sandbox.

### What is still missing, and it is the important part

Everything above works with no model CLI. What none of it proves:
Expand Down
16 changes: 16 additions & 0 deletions packages/deck/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ ACTIVITY_ROOT=
# Unset = the panel follows ACTIVITY_ROOT.
MC_ACTIVITY_ENABLED=

# Optional: the Nudges page, which schedules agent prompts and scripts in the
# crontab of the user Deck runs as. On by default. Set to 0 or false to hide
# it and refuse every write. See "Scheduled nudges" in INSTALL.md.
MC_CRON_ADMIN_ENABLED=

# Set to 1 to allow remote Nudges writes (including through a reverse proxy).
# This also allows IPv4 and bracketed IPv6 Hosts. Same-origin proof is still
# required. Leave unset for direct loopback access only. Deck does not
# authenticate visitors.
MC_CRON_ALLOW_REMOTE_ADMIN=

# Optional: extra hostnames for remote Nudges writes, as a comma-separated
# list without schemes or ports. Only used when remote writes are enabled.
# MC_CRON_ALLOWED_HOSTS=deck.example.com,nudges.example.com
MC_CRON_ALLOWED_HOSTS=

# Optional: comma-separated list of agent names the application may write to.
# UNSET or empty = all agents (the default; a message sent from the application
# is your own message). Set this the moment a concrete per-agent risk shows; no
Expand Down
28 changes: 28 additions & 0 deletions packages/deck/app/lib/cron.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,34 @@ export function deleteCron(
return { ok: true };
}

// ---------------------------------------------------------------------------
// crontabAvailable
// ---------------------------------------------------------------------------

/**
* Whether an executable `crontab` is on PATH. Lets the Nudges page say so
* plainly and refuse writes up front on a machine without cron, instead of
* listing nothing (readCrontab maps every failure to "empty") and then
* failing a create half way through, after the script files were written.
*
* Looks at PATH only; it never runs `crontab`, so it cannot read or change
* anyone's crontab. Tests pass their own PATH.
*/
export function crontabAvailable(pathEnv: string | undefined = process.env["PATH"]): boolean {
if (!pathEnv) return false;
return pathEnv
.split(path.delimiter)
.filter((dir) => dir !== "")
.some((dir) => {
try {
fs.accessSync(path.join(dir, "crontab"), fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}

// ---------------------------------------------------------------------------
// listAgentDirs (exported for use in route loaders)
// ---------------------------------------------------------------------------
Expand Down
20 changes: 13 additions & 7 deletions packages/deck/app/lib/instance.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
* disable. Gates the nav item, the thread toggle, the /tmux route body,
* and the api/tmux-send action (server-side, not just UI).
*
* - MC_CRON_ADMIN_ENABLED: the Nudges page. Default enabled; set "0" or
* "false" to disable. See cronAdminEnabled below.
*
* - ACTIVITY_ROOT / MC_ACTIVITY_ENABLED: the agent-activity panel.
* Presence of the root IS the gate; see activityEnabled below.
*
Expand Down Expand Up @@ -94,17 +97,20 @@ export function modelSelectorEnabled(env: Env): boolean {
}

/**
* Whether the cron admin page is enabled on this instance.
* Whether the Nudges page (/scheduler, api/cron) is enabled on this instance.
*
* Enabled for the known trusted principals by default. Writing the system
* crontab is operator-grade, so the list is deliberately short. Set
* MC_CRON_ADMIN_ENABLED=0 or "false" to explicitly disable on any instance.
* Default enabled, whatever MC_USER is. Nudges writes the crontab of the OS
* user the server runs as. MC_USER is a self-declared name, not an identity
* check, and Deck has no authentication: the protection is that the server
* binds to loopback, so only that machine can reach it. A per-name allowlist
* therefore protected nothing and hid the feature on ordinary installs. Set
* MC_CRON_ADMIN_ENABLED=0 or "false" (any case) to turn it off; that hides
* the nav entry, 404s the page and the api/cron read, and refuses every write.
* Any other value, including unset, leaves it on.
*/
export function cronAdminEnabled(env: Env): boolean {
const explicit = env["MC_CRON_ADMIN_ENABLED"]?.trim().toLowerCase();
if (explicit === "0" || explicit === "false") return false;
const user = mcUser(env);
return user === "alex" || user === "robin";
return !(explicit === "0" || explicit === "false");
}

/**
Expand Down
59 changes: 59 additions & 0 deletions packages/deck/app/lib/nudge-admin.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 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) &&
(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 });
}
if (!hasSameOriginProof(request, context)) {
throw new Response("Nudges writes require a same-origin request.", { status: 403 });
}
}
Loading
Loading
0