a credential can be narrower than its holder

a commander is an agent working unattended for months, and the only
credential in the tree lived in the MCP tool server's environment where
the agent's own shell cannot see it. so the first one built here curled
the whisper container directly on localhost: right answer, wrong door, and
a door the platform does not control.

api_keys.permissions. null is what every key a human minted still is —
their full authority, exactly what the password that made it could do. a
list narrows: the credential reaches only those permission keys, and still
only where the account itself could. intersection, never union.

checked BEFORE the owner bypass, which is the whole point. a Super Admin
consults no grants table, so a token carrying the owner's identity is
unbounded by construction — fine for a browser session somebody is sitting
in front of, not fine for a process that runs for months. this is the only
thing in the platform that can bound them. verified against the running
server: an owner key scoped to [account] gets 200 on /api/user/settings
and 403 on /api/users, /api/tasks and /api/plugins.

it propagates. a narrowed credential can write a task and run it, so the
token buildTaskApiEnv hands that script carries the same narrowing —
otherwise the script comes back through the API with full authority and
the limit bought nothing. the gate stashes it on the request for the one
kind of route that passes authority onward.

POST /tasks/:name/run: runs a script task, waits, returns code and output.
both existing runners need something watching them — the socket needs a
live connection, a job needs somebody to open Jobs. a commander has
neither. deliberately not a job: transcribing a memo takes seconds and
produces a file, and a queue plus a row plus a progress bar is a screen
nobody opened between the request and the result.

script-run.ts is the third thing this needed and the one worth having on
its own. the socket runner, the job runner and now this each carried the
same twenty lines — materialize, INPUT_ env, positional args, resolve cwd,
mint the api env — identical, with nothing saying they had to stay that
way. they differ in how they REPORT, which is real and stays with each of
them. what the script SEES is now decided once.

a commander gets its key at creation, in officer.env at 0600 inside its own
directory, and CLAUDE.md tells it where and says plainly that a sidecar
listening on localhost with no auth is still the wrong door. a file rather
than an env var because the detached loop a commander arms is spawned by
the agent and inherits nothing the platform chose. deleting the commander
revokes the row — the directory removal takes the secret, not the thing
that makes it work.

default scope is everything except `admin`: a commander that can reach
nothing gets widened in a hurry rather than thought about, and installing
plugins, managing users and changing server settings are never part of a
watcher's job. it is a default, stored per key, and for a member it
narrows itself against their role.

also fixed: POST /command-hq/commanders/new never awaited
createCommanderDirectory, so a turn could spawn before its CLAUDE.md
existed — the exact ordering that redesign was for — and the cwd it
returned was a Promise serialising as {}.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
This commit is contained in:
2026-08-24 13:40:42 +00:00
co-authored by Claude Opus 5
parent 247291eeb9
commit e29a4ee380
17 changed files with 631 additions and 190 deletions
+98
View File
@@ -0,0 +1,98 @@
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { createApiKey, revokeApiKeysByName } from 'officerdb';
import { mintApiKey } from '@@/auth-token';
import { PERMISSION_BY_KEY } from '@@/permissions/registry';
import { PORT, OFFICER_API_URL } from '../../officer-url.mjs';
import { getCommanderDir } from '../../data-path';
/*
A commander's own credential.
── Why it has one at all ──
A commander is an agent working while nobody watches, and it has to reach the platform to do anything
worth doing. Until now it could not: the only credential in the tree sits in the MCP tool server's
environment, which the agent's own shell cannot see. So the first commander built here did the
reasonable thing from where it was standing and curled the whisper container directly on localhost —
correct answer, wrong door, and a door the platform does not control.
── Why it is narrowed ──
The owner bypasses every permission check, so a credential carrying the owner's identity is unbounded.
That is fine for a browser session somebody is sitting in front of and wrong for a process that runs
for months unattended. `api_keys.permissions` is the only thing that can bound a Super Admin — see
`permissions/authorize.ts` → `decideApiRequest`, which applies it BEFORE the owner short-circuit.
── Why the default is "everything except admin" ──
A commander that can reach nothing is useless on the day it is created, and a default nobody can work
with gets widened in a hurry rather than thought about. So the default removes the class that is never
part of a watcher's job — installing plugins, managing users and roles, changing server settings — and
leaves the rest.
It is a DEFAULT, not a policy: the list is stored on the key row and can be narrowed per commander.
And for a member it narrows itself, because the check is an intersection with what their role holds.
*/
/** Permission keys a commander gets unless told otherwise: everything the platform does that is not administration. */
export function defaultCommanderPermissions(): string[] {
return [...PERMISSION_BY_KEY.values()].filter((p) => p.kind !== 'admin').map((p) => p.key);
}
/** The env file's path, and the name the key is stored under — both derived, so revocation cannot miss one. */
export const commanderKeyName = (dirName: string) => `commander:${dirName}`;
export const commanderEnvPath = (email: string, dirName: string) =>
join(getCommanderDir(email, dirName), 'officer.env');
/**
* Mint a commander's key and write it into its directory.
*
* The secret is written to a FILE rather than injected into the agent's environment because the agent is
* not the only thing that needs it: a commander arms a detached loop, and that loop is spawned by the
* agent itself and inherits nothing the platform chose. A file both can read is the only shape that
* covers the interactive turn and the unattended loop with one credential.
*
* 0600, and `createCommanderDirectory` chowns the whole directory to the account afterwards — which is
* why this must run BEFORE that chown, not after.
*/
export async function writeCommanderCredential(params: {
userId: number;
email: string;
dirName: string;
permissions?: string[];
}): Promise<{ path: string; permissions: string[] }> {
const permissions = params.permissions ?? defaultCommanderPermissions();
const { secret, keyHash, prefix } = mintApiKey();
// Revoke first. A commander recreated under a directory name that has been used before would otherwise
// leave a live key nothing points at any more.
await revokeApiKeysByName(params.userId, commanderKeyName(params.dirName)).catch(() => {});
await createApiKey({
userId: params.userId,
name: commanderKeyName(params.dirName),
keyHash,
prefix,
permissions,
});
const path = commanderEnvPath(params.email, params.dirName);
mkdirSync(join(path, '..'), { recursive: true });
writeFileSync(
path,
[
"# This commander's own credential. Source it before calling Officer:",
'# set -a; . ./officer.env; set +a',
'#',
'# It is narrowed — see `permissions` on its api_keys row — and it is revoked when this commander is',
'# deleted. Do not copy it anywhere else; anything that needs one gets its own.',
`OFFICER_API_URL=${OFFICER_API_URL}`,
`OFFICER_API_HOST=${process.env.PUBLIC_URL ? new URL(process.env.PUBLIC_URL).host : `127.0.0.1:${PORT}`}`,
`OFFICER_API_KEY=${secret}`,
'',
].join('\n'),
{ mode: 0o600 },
);
return { path, permissions };
}