the allow list shipped an hour ago was a snapshot. plugin permissions
register at mount, so a plugin installed after a commander was created was
missing from its list and failed as a bare 403 with nothing saying why —
and every future thing a commander is meant to do is exactly that shape:
notify a device, send mail, spawn a sub-agent, hand a transcription to an
idle one, reach a plugin that does not exist yet.
so a credential now narrows two ways, and both only subtract:
permissions an ALLOW list. exact, a snapshot. right for a credential
with one job.
excludedKinds kinds it may never reach, resolved against the LIVE
registry on every request. right for a credential whose
job is open-ended.
a commander gets the second: every kind except admin. bounded away from
installing plugins, managing users and roles and changing server settings,
forever — and open to everything the platform learns to do, with nothing
to re-issue. still intersected with the account, so for a member it
narrows itself against their role.
verified against the running server with a commander-shaped key: tasks,
notify, file-browser and the transcribe PLUGIN all reach their routes;
/api/users, /api/plugins and /api/roles are 403. the plugin case is the
one an allow list could not have passed — it was mounted long after any
key was minted.
the commander's CLAUDE.md says what it cannot do in the rule's own terms,
and that a 403 is an answer rather than a problem to route around.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
275 lines
13 KiB
TypeScript
275 lines
13 KiB
TypeScript
import { getUserById, getRoleGrants } from 'officerdb';
|
|
import type { CredentialScope } from '../auth-token';
|
|
import type { UserRole } from 'officerdb';
|
|
import {
|
|
PERMISSION_BY_KEY,
|
|
CORE_PERMISSIONS,
|
|
permissionForApiPath,
|
|
permissionForWsProvider,
|
|
isRequestAllowedAtLevel,
|
|
isOwnerOnlyRoute,
|
|
isSelfServiceRoute,
|
|
type PermissionLevel,
|
|
} from './registry';
|
|
|
|
// Resolving "may this account do this". Every deny path in the platform ends up here.
|
|
//
|
|
// Two rules run the whole file:
|
|
//
|
|
// 1. The owner bypasses everything. isSuperAdmin is the single question asked first, and a Super Admin
|
|
// never consults the grants table — which is why the schema refuses to store a row for that role.
|
|
// 2. Everyone else gets core permissions plus whatever their ROLE has been granted, and nothing else.
|
|
// An unrecognised permission, a missing row, a database error, a user who no longer exists: all deny.
|
|
//
|
|
// Fail-closed is not decoration here. This function is what stands between a Member and a shell, and the
|
|
// failure mode of a permissive default is not a bug report — it is someone else's session. Every catch in
|
|
// this file returns "no", and none of them log-and-continue.
|
|
|
|
export type EffectivePermissions = {
|
|
isOwner: boolean;
|
|
/** Permission key → level. Empty for an account with nothing granted; the owner's is never consulted. */
|
|
grants: Map<string, PermissionLevel>;
|
|
};
|
|
|
|
// ── Grant cache ───────────────────────────────────────────────────────────────────────────────────
|
|
//
|
|
// Keyed on ROLE, not user, so it holds at most one entry per role and a new account needs no warm-up.
|
|
//
|
|
// super-admin.ts deliberately does NOT cache, and says why: a cache with no invalidation contract is a
|
|
// staleness bug waiting for whoever builds the role UI. This one has a contract — the only writer is the
|
|
// grants API in api/users, which calls invalidateRoleGrants on every mutation, in this same process. That
|
|
// is the entire set of writers; if a second one ever appears it has to call this too, which is why the
|
|
// cache and its invalidator live in the same file as the reader that depends on them.
|
|
const grantCache = new Map<UserRole, Map<string, PermissionLevel>>();
|
|
|
|
/** Called by every path that writes a grant. Clears one role, or all of them. */
|
|
export function invalidateRoleGrants(role?: UserRole): void {
|
|
if (role) grantCache.delete(role);
|
|
else grantCache.clear();
|
|
}
|
|
|
|
async function grantsForRole(role: UserRole): Promise<Map<string, PermissionLevel>> {
|
|
const cached = grantCache.get(role);
|
|
if (cached) return cached;
|
|
const grants = (await getRoleGrants(role)) as Map<string, PermissionLevel>;
|
|
grantCache.set(role, grants);
|
|
return grants;
|
|
}
|
|
|
|
/**
|
|
* What this account may reach, resolved from its role.
|
|
*
|
|
* Core permissions come in at `write` unconditionally: they are the caller's own profile, dock and bug
|
|
* reports, and a read-only version of "change your own password" is not a coherent thing to offer.
|
|
*
|
|
* `execution` and `admin` permissions are dropped even if a row somehow grants them. The API refuses to
|
|
* write such a row, but this is the layer that has to hold if one ever exists — a constraint the database
|
|
* does not enforce is a constraint the reader must.
|
|
*/
|
|
/**
|
|
* The resolution itself, with no database in it.
|
|
*
|
|
* Split out on 2026-08-22 so it can be tested. `authorize.ts` is described in its own header as the file
|
|
* standing between a Member and a shell, and it had no automated tests at all — because every path through
|
|
* it needed two database calls, and the only file in this repository that mocks `officerdb` has a stub that
|
|
* leaks into whatever runs after it. Pulling the decision away from the fetching removes the need for a
|
|
* mock rather than working around one: everything below this line is a pure function of two arguments.
|
|
*
|
|
* The async wrapper keeps the caching, the error handling and the single-question shape callers rely on.
|
|
*/
|
|
export function resolveEffectivePermissions(
|
|
user: { role: UserRole; osUser: string | null },
|
|
roleGrants: Map<string, PermissionLevel>,
|
|
): EffectivePermissions {
|
|
if (user.role === 'Super Admin') return { isOwner: true, grants: new Map() };
|
|
|
|
const grants = new Map<string, PermissionLevel>();
|
|
for (const permission of CORE_PERMISSIONS) grants.set(permission.key, 'write');
|
|
|
|
// Whether the kernel can enforce a boundary for this account. `confined` permissions are dropped
|
|
// without it — see below.
|
|
const hasOsAccount = !!user.osUser;
|
|
|
|
for (const [key, level] of roleGrants) {
|
|
const permission = PERMISSION_BY_KEY.get(key);
|
|
// Unknown key: a permission that was renamed or removed while a grant survived. Ignore it — the
|
|
// alternative is honouring a name nothing defines.
|
|
if (!permission) continue;
|
|
|
|
// A confined permission touches the filesystem or runs a process, and is safe only because the
|
|
// account has its own Linux user to be confined to. Without one there is no boundary, so the grant
|
|
// resolves to nothing rather than to the owner's home — which is what it WOULD resolve to, since
|
|
// `getOwnerHomeDir` ignores the email it is passed, always.
|
|
//
|
|
// Dropped here rather than refused per-router so that one rule covers the HTTP routes, the
|
|
// websocket doors and the dock all at once. A member with `files` granted but no OS account sees no
|
|
// Files icon, gets a 403 from /api/file-browser, and cannot open the terminal socket — from this.
|
|
if (permission.kind === 'confined') {
|
|
if (!hasOsAccount) continue;
|
|
grants.set(key, level);
|
|
continue;
|
|
}
|
|
|
|
if (permission.kind !== 'app') continue;
|
|
grants.set(key, level);
|
|
}
|
|
|
|
return { isOwner: false, grants };
|
|
}
|
|
|
|
export async function getEffectivePermissions(userId: number | undefined): Promise<EffectivePermissions> {
|
|
const empty: EffectivePermissions = { isOwner: false, grants: new Map() };
|
|
if (!userId) return empty;
|
|
|
|
try {
|
|
const user = await getUserById(userId);
|
|
if (!user) return empty;
|
|
if (user.role === 'Super Admin') return { isOwner: true, grants: new Map() };
|
|
return resolveEffectivePermissions(user, await grantsForRole(user.role));
|
|
} catch {
|
|
// A transient database error must never grant anything. Deny, and let the next request retry.
|
|
return empty;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* May this account make this HTTP request?
|
|
*
|
|
* `path` is the full request path. Paths outside `/api` are not this function's business — the DAV sync
|
|
* door authenticates with its own app password and never carries a platform account.
|
|
*/
|
|
export async function isApiRequestAllowed(
|
|
userId: number | undefined,
|
|
method: string,
|
|
path: string,
|
|
scope?: CredentialScope | null,
|
|
): Promise<{ allowed: boolean; reason?: string }> {
|
|
return decideApiRequest(await getEffectivePermissions(userId), method, path, scope);
|
|
}
|
|
|
|
/**
|
|
* Does this credential's own narrowing admit this permission?
|
|
*
|
|
* Two rules, both subtractive, and an absent one admits everything:
|
|
*
|
|
* - `excludeKinds` is resolved against the LIVE registry, so it keeps meaning what it meant as the
|
|
* platform grows. That is what makes it right for a commander: excluded from administration forever,
|
|
* and able to reach a plugin installed long after it was minted. An allow list cannot express that —
|
|
* it names what existed on the day it was written, so next year's plugin is simply missing from it.
|
|
* - `allow` is an exact list, for a credential with one job.
|
|
*
|
|
* An unresolvable permission is refused rather than admitted: a path nothing serves must not become
|
|
* reachable by failing to resolve, which is the same rule the unnarrowed path already applies below.
|
|
*/
|
|
function credentialAdmits(
|
|
scope: CredentialScope,
|
|
permission: { key: string; kind: string } | null | undefined,
|
|
): boolean {
|
|
if (!permission) return false;
|
|
if (scope.excludeKinds?.includes(permission.kind)) return false;
|
|
if (Array.isArray(scope.allow) && !scope.allow.includes(permission.key)) return false;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* The decision, given an already-resolved account. Pure, and where every rule below actually lives.
|
|
*
|
|
* `scope` is the narrowing carried by an API key, or null/undefined for one that carries its holder's
|
|
* full authority (which is every key a human has minted and every session JWT). It is an intersection,
|
|
* never a union: a key cannot reach what its account could not, and its account cannot reach, through
|
|
* this key, what the key excludes.
|
|
*
|
|
* **It is checked before the owner bypass, and that is the whole point.** A Super Admin consults no
|
|
* grants table, so a credential carrying the owner's identity is unbounded by construction — which is
|
|
* fine for a browser session the owner is sitting in front of, and not fine for an agent holding one
|
|
* unattended for months. This line is the only thing in the platform that can bound them.
|
|
*/
|
|
export function decideApiRequest(
|
|
effective: EffectivePermissions,
|
|
method: string,
|
|
path: string,
|
|
scope?: CredentialScope | null,
|
|
): { allowed: boolean; reason?: string } {
|
|
const { isOwner, grants } = effective;
|
|
|
|
// Same deny-the-unmapped rule as below, one step earlier: a path this cannot resolve must not become
|
|
// reachable by failing to resolve.
|
|
if (scope && !credentialAdmits(scope, permissionForApiPath(path))) {
|
|
return { allowed: false, reason: 'this credential is not permitted to use that' };
|
|
}
|
|
|
|
if (isOwner) return { allowed: true };
|
|
|
|
const permission = permissionForApiPath(path);
|
|
// Totality guarantees every mounted, non-exempt prefix maps to a permission, so reaching this branch
|
|
// means either an exempt prefix (which the caller checks before us) or a path nothing serves. Deny:
|
|
// a 403 on a route that does not exist is not a leak, and a permissive default here would be.
|
|
if (!permission) return { allowed: false, reason: 'no permission covers this path' };
|
|
|
|
// BEFORE self-service, and before kind. A permission can be fully granted and still have an
|
|
// administrative corner — a plugin's settings, holding the credential the rest of it runs on. The owner
|
|
// already returned above, so reaching here at all means this is not them.
|
|
if (isOwnerOnlyRoute(permission, path)) {
|
|
return { allowed: false, reason: `that part of ${permission.label} is restricted to the server owner` };
|
|
}
|
|
|
|
// Checked before kind, because a self-service route acts on the caller and is therefore not the thing
|
|
// the permission around it restricts. Exact method and path only — see the field's comment.
|
|
if (isSelfServiceRoute(permission, method, path)) return { allowed: true };
|
|
|
|
if (permission.kind === 'execution') {
|
|
return { allowed: false, reason: `${permission.label} runs as the server owner and cannot be shared` };
|
|
}
|
|
if (permission.kind === 'admin') {
|
|
return { allowed: false, reason: `${permission.label} is restricted to the server owner` };
|
|
}
|
|
|
|
const level = grants.get(permission.key);
|
|
if (!level) return { allowed: false, reason: `your role does not have access to ${permission.label}` };
|
|
|
|
if (!isRequestAllowedAtLevel(permission, level, method, path)) {
|
|
return { allowed: false, reason: `you have read-only access to ${permission.label}` };
|
|
}
|
|
return { allowed: true };
|
|
}
|
|
|
|
/**
|
|
* May this account open this WebSocket provider?
|
|
*
|
|
* There is no method to reason about, so a socket needs the permission at any level.
|
|
*
|
|
* That rule was written for cliamp and cliamp-audio — the music app's playback transport, and the only
|
|
* grantable sockets there have ever been. Both left on 2026-08-15 with `plugins/music/cliamp/`, so every
|
|
* provider reaching here today belongs to an `execution` permission and is refused above, structurally,
|
|
* rather than by being left off a list. The rule stays because the first plugin to own a socket needs it.
|
|
*/
|
|
export async function isWsProviderAllowed(
|
|
userId: number | undefined,
|
|
provider: string,
|
|
scope?: CredentialScope | null,
|
|
): Promise<boolean> {
|
|
return decideWsProvider(await getEffectivePermissions(userId), provider, scope);
|
|
}
|
|
|
|
/** The decision, given an already-resolved account. See `isWsProviderAllowed` for why level is not read. */
|
|
export function decideWsProvider(
|
|
effective: EffectivePermissions,
|
|
provider: string,
|
|
scope?: CredentialScope | null,
|
|
): boolean {
|
|
const { isOwner, grants } = effective;
|
|
|
|
// Before the owner bypass, for the reason given in `decideApiRequest`. A socket is the one door a
|
|
// narrowed credential must not walk through just because it authenticated.
|
|
if (scope && !credentialAdmits(scope, permissionForWsProvider(provider))) return false;
|
|
|
|
if (isOwner) return true;
|
|
|
|
const permission = permissionForWsProvider(provider);
|
|
// `confined` is admissible here as well as `app`: getEffectivePermissions has already dropped confined
|
|
// grants for an account with no Linux user, so reaching this line with one in `grants` means the boundary
|
|
// exists. Anything still `execution` is refused structurally, by not being in the map at all.
|
|
if (!permission || (permission.kind !== 'app' && permission.kind !== 'confined')) return false;
|
|
return grants.has(permission.key);
|
|
}
|