step 1/4: the permission engine is called permissions, not capabilities
The word meant four different things in this repo, not the three the offscale
doc records:
1. the permission registry → RENAMED here
2. $OFFICER_ROOT/capabilities/ items → kept; this is what capabilities are
3. sidecar routing keys → step 3, becoming `handles`
4. Lightning wallet features → kept; a domain term, and on the wire
to the mobile apps
The fourth was not in the doc and a global find-and-replace would have broken
the mobile wallet, which reads `{ kind, capabilities: Capability[] }` from the
wallet sidecar. So this renamed against an explicit file allowlist rather than
by sweeping the tree, and `CapabilityPage.tsx` — the UI for the item store, and
correctly named already — was left alone.
Moved: servers/capabilities/ → servers/permissions/, capability-gate.ts →
permission-gate.ts, users/capabilities-routes.ts → permissions-routes.ts,
hooks/useCapabilities.ts → usePermissions.ts. Identifiers follow.
Three breaks the typechecker could not see, all found by exercising it live.
The route paths moved with the prose sweep, so the server served
/user/permissions while the frontend still called /user/capabilities. A 404 on
every page load, and tsgo clean throughout.
The response FIELD moved too. `client.get<SelfPermissions>()` is an unchecked
cast, so `data.capabilities` became `undefined` at runtime with no compile
error — `can()` would have answered "no" to everything and the dock would have
emptied itself.
And the grants list was passed straight out of the database, so it arrived as
`{ role, capability, level }` while the screen read `grant.permission`. Every
role would have rendered as holding nothing. It is now mapped in the route:
the wire says `permission`, the column still says `capability`, and step 2
therefore changes nothing any client can see.
The stale react-query keys were the quiet one: two files still invalidated
['self-capabilities'] after the hook moved to ['self-permissions'], so
installing a plugin would have silently stopped refreshing the dock.
The database is untouched — `role_capabilities` and its `capability` column are
step 2, and the two call sites that cross that boundary say so in a comment.
Round-tripped the 9 live grants through the admin endpoint to prove the PUT
contract survived: 9 before, 9 after, Member's three intact.
Also reverted prettier churn on five landing-page files that a broad --write
picked up. Second time today; the lesson is not sticking.
tsgo clean. 797 tests, 787 pass, same 7 pre-existing failures — two of which
now read "path → permission" rather than "path → capability".
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
import { getUserById, getRoleGrants } from 'officerdb';
|
||||
import type { UserRole } from 'officerdb';
|
||||
import {
|
||||
PERMISSION_BY_KEY,
|
||||
CORE_CAPABILITIES,
|
||||
permissionForApiPath,
|
||||
permissionForWsProvider,
|
||||
isRequestAllowedAtLevel,
|
||||
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.
|
||||
*/
|
||||
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() };
|
||||
|
||||
const grants = new Map<string, PermissionLevel>();
|
||||
for (const permission of CORE_CAPABILITIES) 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 await grantsForRole(user.role)) {
|
||||
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 };
|
||||
} 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,
|
||||
): Promise<{ allowed: boolean; reason?: string }> {
|
||||
const { isOwner, grants } = await getEffectivePermissions(userId);
|
||||
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' };
|
||||
|
||||
// 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): Promise<boolean> {
|
||||
const { isOwner, grants } = await getEffectivePermissions(userId);
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { Permission } from './registry';
|
||||
import {
|
||||
PERMISSIONS,
|
||||
PERMISSION_BY_KEY,
|
||||
GRANTABLE_PERMISSIONS,
|
||||
permissionForApiPath,
|
||||
permissionForWsProvider,
|
||||
isRequestAllowedAtLevel,
|
||||
isSelfServiceRoute,
|
||||
} from './registry';
|
||||
import { assertPermissionTotality, isExemptApiPath } from './totality';
|
||||
|
||||
// The database-backed half (authorize.ts) is exercised against the live schema; this file covers the pure
|
||||
// half, which is where the rules actually live. Everything here runs without a database.
|
||||
|
||||
// Mirrors the `handlers` map in server.tsx by hand, which is itself the drift this file keeps catching.
|
||||
// `cliamp` and `cliamp-audio` left on 2026-08-15 with `plugins/music/cliamp/` — see below.
|
||||
const REAL_WS = ['terminal', 'chat', 'task-runner', 'pipeline', 'desktop', 'vault', 'sidecar'];
|
||||
const realApi = () => [...new Set(PERMISSIONS.flatMap((c) => c.api))];
|
||||
const surface = () => ({
|
||||
apiPrefixes: [...realApi(), '/auth', '/landing-page-data', '/waitlist', '/vault', '/sidecar'],
|
||||
wsProviders: REAL_WS,
|
||||
});
|
||||
|
||||
describe('totality', () => {
|
||||
test('the registry covers its own declared surface', () => {
|
||||
expect(() => assertPermissionTotality(surface())).not.toThrow();
|
||||
});
|
||||
|
||||
// The four ways this is allowed to fail. Each one is a real bug it exists to catch, and a check that
|
||||
// only ever passes is worth nothing — so assert that it refuses, not merely that it runs.
|
||||
test('refuses a mounted router no permission claims', () => {
|
||||
const s = surface();
|
||||
s.apiPrefixes.push('/newthing');
|
||||
expect(() => assertPermissionTotality(s)).toThrow(/\/api\/newthing is mounted but no permission claims it/);
|
||||
});
|
||||
|
||||
test('refuses a served socket no permission claims — the 2026-08-06 hole', () => {
|
||||
const s = surface();
|
||||
s.wsProviders = [...REAL_WS, 'newsocket'];
|
||||
expect(() => assertPermissionTotality(s)).toThrow(/websocket provider 'newsocket' is served/);
|
||||
});
|
||||
|
||||
test('refuses a claim on a router that no longer exists', () => {
|
||||
const s = surface();
|
||||
s.apiPrefixes = s.apiPrefixes.filter((p) => p !== '/gitea');
|
||||
expect(() => assertPermissionTotality(s)).toThrow(/claims \/api\/gitea, which nothing mounts/);
|
||||
});
|
||||
|
||||
test('refuses a claim on a socket that is not served', () => {
|
||||
const s = surface();
|
||||
s.wsProviders = REAL_WS.filter((p) => p !== 'terminal');
|
||||
expect(() => assertPermissionTotality(s)).toThrow(/claims websocket 'terminal', which is not served/);
|
||||
});
|
||||
|
||||
test('no two permissions claim the same prefix', () => {
|
||||
const seen = new Map<string, string>();
|
||||
for (const permission of PERMISSIONS) {
|
||||
for (const prefix of permission.api) {
|
||||
expect(seen.has(prefix)).toBe(false);
|
||||
seen.set(prefix, permission.key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('signin is exempt and gitea is not', () => {
|
||||
expect(isExemptApiPath('/api/auth/signin')).toBe(true);
|
||||
expect(isExemptApiPath('/api/gitea')).toBe(false);
|
||||
expect(isExemptApiPath('/api/dashboards/4')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('path → permission', () => {
|
||||
test('resolves a prefix and its descendants', () => {
|
||||
expect(permissionForApiPath('/api/gitea')?.key).toBe('gitea');
|
||||
expect(permissionForApiPath('/api/gitea/repos/a/b')?.key).toBe('gitea');
|
||||
});
|
||||
|
||||
test('does not match a prefix that is merely a string prefix', () => {
|
||||
// '/api/username' must not resolve to the 'account' permission, which claims '/user'. A naive
|
||||
// startsWith would. (This was '/api/musicbrainz' against 'music' until music became a plugin.)
|
||||
expect(permissionForApiPath('/api/username')).toBeNull();
|
||||
});
|
||||
|
||||
test('longest prefix wins, so /dav and /caldav do not fight', () => {
|
||||
expect(permissionForApiPath('/api/caldav/x')?.key).toBe('calendar');
|
||||
expect(permissionForApiPath('/api/dav/x')?.key).toBe('calendar');
|
||||
});
|
||||
|
||||
test('an unclaimed path resolves to nothing rather than to something permissive', () => {
|
||||
expect(permissionForApiPath('/api/not-a-thing')).toBeNull();
|
||||
});
|
||||
|
||||
test('sockets resolve to their permission', () => {
|
||||
expect(permissionForWsProvider('terminal')?.key).toBe('terminal');
|
||||
expect(permissionForWsProvider('chat')?.key).toBe('chat');
|
||||
expect(permissionForWsProvider('nope')).toBeNull();
|
||||
});
|
||||
|
||||
// This pinned a real hole for one day: `/api/cliamp/ws` and `/api/cliamp/audio/ws` were SERVED in
|
||||
// server.tsx's route table while no permission claimed them and their `handlers` entries were commented
|
||||
// out — so connecting crashed on a non-null assertion, and the boot check could not see any of it
|
||||
// because it reads `Object.keys(handlers)` rather than the route table.
|
||||
//
|
||||
// Closed on 2026-08-15 by cliamp leaving for `plugins/music/cliamp/`: the routes, the relay and the
|
||||
// provider names all went with it, and the two lists agree again. Kept as an assertion rather than
|
||||
// deleted, because "the route table serves nothing the handlers map lacks" is the invariant the
|
||||
// original incident was about, and this is the cheapest place to notice it breaking again.
|
||||
test('no cliamp socket is served or claimed — the route table and handlers agree', () => {
|
||||
expect(permissionForWsProvider('cliamp')).toBeNull();
|
||||
expect(permissionForWsProvider('cliamp-audio')).toBeNull();
|
||||
expect(REAL_WS).not.toContain('cliamp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('levels', () => {
|
||||
// A FIXTURE, not a registry entry.
|
||||
//
|
||||
// These tests ran against the real `music` permission until 2026-08-15, when music left with
|
||||
// `plugins/music/`. Re-anchoring them on whichever entry happens to have a `personal` list today only
|
||||
// moves the problem to the next extraction — and it had already half-broken before that, because the
|
||||
// moment music's `api` was commented out (2026-08-13) every path below stopped matching and three of
|
||||
// these four tests passed for the wrong reason: everything is refused when nothing is claimed.
|
||||
//
|
||||
// `isRequestAllowedAtLevel` is a pure function of a Permission. Handing it one states what is actually
|
||||
// under test — the RULE — rather than borrowing a feature that can leave.
|
||||
const fixture: Permission = {
|
||||
key: 'fixture',
|
||||
label: 'Fixture',
|
||||
description: 'Not in the registry — a shape to exercise the level rules against',
|
||||
kind: 'app',
|
||||
api: ['/fixture'],
|
||||
personal: ['/favorites', '/now-playing'],
|
||||
};
|
||||
|
||||
test('write permits anything within the permission', () => {
|
||||
expect(isRequestAllowedAtLevel(fixture, 'write', 'DELETE', '/api/fixture/track/9')).toBe(true);
|
||||
});
|
||||
|
||||
test('read permits safe methods', () => {
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'GET', '/api/fixture/albums')).toBe(true);
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'HEAD', '/api/fixture/albums')).toBe(true);
|
||||
});
|
||||
|
||||
test('read permits mutations only under personal sub-paths', () => {
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/favorites/7')).toBe(true);
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'PUT', '/api/fixture/now-playing')).toBe(true);
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/scan')).toBe(false);
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'DELETE', '/api/fixture/track/9')).toBe(false);
|
||||
});
|
||||
|
||||
test('a personal entry does not leak across a name boundary', () => {
|
||||
// '/favorites-export' must not be covered by the '/favorites' personal entry.
|
||||
expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/favorites-export')).toBe(false);
|
||||
});
|
||||
|
||||
test('a plugin gets the same rule through readOnlyWrites', () => {
|
||||
// The two lists are concatenated, so a plugin declaring per-caller paths on the one field its
|
||||
// manifest has behaves identically to a core permission declaring `personal`. This is what music
|
||||
// relies on now that it ships as one.
|
||||
const plugin: Permission = { ...fixture, personal: undefined, readOnlyWrites: ['/favorites', '/now-playing'] };
|
||||
expect(isRequestAllowedAtLevel(plugin, 'read', 'POST', '/api/fixture/favorites/7')).toBe(true);
|
||||
expect(isRequestAllowedAtLevel(plugin, 'read', 'POST', '/api/fixture/scan')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('self-service routes', () => {
|
||||
const userAdmin = PERMISSION_BY_KEY.get('user-admin')!;
|
||||
|
||||
test('PUT /api/users is self-profile update and stays reachable', () => {
|
||||
expect(isSelfServiceRoute(userAdmin, 'PUT', '/api/users')).toBe(true);
|
||||
expect(isSelfServiceRoute(userAdmin, 'put', '/api/users')).toBe(true);
|
||||
});
|
||||
|
||||
test('it does not open the rest of the router', () => {
|
||||
expect(isSelfServiceRoute(userAdmin, 'GET', '/api/users')).toBe(false);
|
||||
expect(isSelfServiceRoute(userAdmin, 'DELETE', '/api/users/5')).toBe(false);
|
||||
expect(isSelfServiceRoute(userAdmin, 'PATCH', '/api/users/5/role')).toBe(false);
|
||||
// The exact-match rule: a descendant of a self-service path is not self-service.
|
||||
expect(isSelfServiceRoute(userAdmin, 'PUT', '/api/users/5')).toBe(false);
|
||||
});
|
||||
|
||||
test('permissions without the field are unaffected', () => {
|
||||
expect(isSelfServiceRoute(PERMISSION_BY_KEY.get('wallet')!, 'PUT', '/api/wallet')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('kinds', () => {
|
||||
test('execution permissions are never grantable', () => {
|
||||
const grantable = new Set(GRANTABLE_PERMISSIONS.map((c) => c.key));
|
||||
// `files` left this list on 2026-08-11, then `terminal` and `chat` the same day — see the tests below and
|
||||
// docs/per-user-linux-accounts.md. Everything still here runs as the OWNER in the owner's home with no
|
||||
// per-caller resolution at all.
|
||||
for (const key of ['tasks', 'desktop', 'browser', 'items']) {
|
||||
expect(PERMISSION_BY_KEY.get(key)?.kind).toBe('execution');
|
||||
expect(grantable.has(key)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
// A confined permission is grantable, but the grant is inert without a Linux account — enforced in
|
||||
// authorize.ts, which is where the rule can cover routes, sockets and the dock at once.
|
||||
test('confined permissions are grantable', () => {
|
||||
const grantable = new Set(GRANTABLE_PERMISSIONS.map((c) => c.key));
|
||||
for (const key of ['files', 'terminal', 'chat']) {
|
||||
expect(PERMISSION_BY_KEY.get(key)?.kind).toBe('confined');
|
||||
expect(grantable.has(key)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
// The claim `confined` makes is that every path it reaches resolves its directory from the CALLER. That
|
||||
// cannot be asserted from the registry, so this pins the inverse: nothing becomes confined without a
|
||||
// deliberate edit here, and the list stays short enough to audit by eye.
|
||||
//
|
||||
// `chat` was on this list ahead of its implementation for a day, with `api/chat/chat.ts` and the chat socket
|
||||
// both refusing non-owners because a turn still spawned the agent as the owner. Both refusals were removed
|
||||
// on 2026-08-12, together, once the turn ran under `runAs` with the member's own home, credential,
|
||||
// transcripts and session ownership. `chat` is now confined in fact and not only in the registry.
|
||||
test('confined is a short, deliberate list', () => {
|
||||
expect(PERMISSIONS.filter((c) => c.kind === 'confined').map((c) => c.key)).toEqual(['terminal', 'chat', 'files']);
|
||||
});
|
||||
|
||||
test('admin permissions are never grantable', () => {
|
||||
const grantable = new Set(GRANTABLE_PERMISSIONS.map((c) => c.key));
|
||||
// `headscale` was here until 2026-08-15, when it left with offscale. A plugin's permissions are
|
||||
// registered at install from its manifest, so they are not in this compile-time list by design.
|
||||
for (const key of ['user-admin', 'server-admin', 'wallet']) {
|
||||
expect(PERMISSION_BY_KEY.get(key)?.kind).toBe('admin');
|
||||
expect(grantable.has(key)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('gitea is grantable — the case this was built for', () => {
|
||||
expect(GRANTABLE_PERMISSIONS.some((c) => c.key === 'gitea')).toBe(true);
|
||||
});
|
||||
|
||||
test('every permission declares at least one api prefix', () => {
|
||||
for (const permission of PERMISSIONS) expect(permission.api.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,567 @@
|
||||
// The permission registry: the single enumeration of what this platform can do, and the unit the owner
|
||||
// grants to a role.
|
||||
//
|
||||
// ── Why permissions and not routes ──
|
||||
//
|
||||
// The obvious model is "list the routes a role may call". It does not survive contact with this codebase.
|
||||
// A sweep of all 100 mutating platform routes on 2026-08-06 found reads permanently stuck on POST for two
|
||||
// reasons that are not going away: bodies GET cannot carry (`/stt` multipart audio, `/tts`, `/ocr`,
|
||||
// `/transcribe`), and credentials that must not sit in a query string where access logs, shell history and
|
||||
// Referer headers capture them (`/tts/voices` apiKey, the four `/test` endpoints, `/local-providers/probe`).
|
||||
// Five genuinely free conversions were done in e54d71d; the rest are staying. So the METHOD alone cannot
|
||||
// carry the read/write distinction — hence `readOnlyWrites` below, declared per permission.
|
||||
//
|
||||
// The deeper reason is that a route list is not what the owner is deciding. The owner decides "this person
|
||||
// gets Gitea". A permission is that decision; the prefixes, sockets and screens it expands to are an
|
||||
// implementation detail that belongs next to the decision rather than in the granting UI.
|
||||
//
|
||||
// ── The four kinds, and why `execution` can never be granted ──
|
||||
//
|
||||
// core every authenticated account, always. Not grantable because not deniable — signing in
|
||||
// without them means a broken app, not a restricted one.
|
||||
// app the grantable surface. This is what the owner hands out per role.
|
||||
// confined execution-shaped, but the KERNEL enforces the boundary per account. Grantable, and only
|
||||
// to an account that has a Linux user — see below.
|
||||
// execution NEVER grantable. Owner only, structurally.
|
||||
// admin owner only: the platform administering itself, and the owner's own money and network.
|
||||
//
|
||||
// ── `confined`, and why it is not just `app` ──
|
||||
//
|
||||
// Added 2026-08-11 with per-user Linux accounts (docs/per-user-linux-accounts.md). A confined permission
|
||||
// touches the filesystem or runs a process, so calling it an `app` would be a lie — but it is no longer
|
||||
// the OWNER'S filesystem, because the account has its own Linux user, its own home, and the kernel refusing
|
||||
// everything above it.
|
||||
//
|
||||
// The distinction earns its keep in one place: a grant on a confined permission means NOTHING unless the
|
||||
// account actually has that Linux user. `authorize.ts` drops confined grants for an account with no
|
||||
// `osUser`, so "granted but unconfined" resolves to no access rather than to the owner's home. That rule
|
||||
// lives there, once, instead of in each router that would otherwise have to remember it.
|
||||
//
|
||||
// Moving a permission from `execution` to `confined` is therefore a claim with a test attached: every path
|
||||
// it reaches must resolve its directory from the CALLER, not from HOME_DIR.
|
||||
//
|
||||
// `execution` is the important one. Everything under it runs as the OWNER'S OS user in the owner's home
|
||||
// directory: the terminal is a real shell, chat spawns `claude` with --dangerously-skip-permissions, tasks
|
||||
// run arbitrary scripts, the file browser and code editor read and write the owner's disk, the desktop is
|
||||
// the owner's physical screen. Granting any of them is not a feature flag, it is co-ownership of the
|
||||
// machine. There is no level of "read" that makes a shell safe, which is why these have no level at all.
|
||||
// Revisit only if per-user home confinement is ever solved — and that is a project, not a checkbox.
|
||||
//
|
||||
// ── Read by default ──
|
||||
//
|
||||
// A grant carries a level, `read` or `write`. `read` permits safe methods (GET/HEAD/OPTIONS) anywhere in
|
||||
// the permission, plus mutations under `personal` — sub-paths that hold the CALLER'S own data and nothing
|
||||
// else. `dashboards` is the worked example: a dashboard belongs to the account that made it, so the whole
|
||||
// surface is personal and a read grant is really "your own, fully". So "may a member write here" is a
|
||||
// property of the endpoint, not a policy knob someone has to remember to set.
|
||||
//
|
||||
// Music was this note's example until 2026-08-15, when it left with `plugins/music/`. A plugin declares
|
||||
// the same thing through its manifest's `readOnlyWrites` — `isRequestAllowedAtLevel` merges the two lists,
|
||||
// so they are one mechanism under two names.
|
||||
|
||||
export type PermissionKind = 'core' | 'app' | 'confined' | 'execution' | 'admin';
|
||||
|
||||
export type Permission = {
|
||||
/** Stable identifier. Stored in the database as the grant's subject — renaming one is a data change. */
|
||||
key: string;
|
||||
label: string;
|
||||
description: string;
|
||||
kind: PermissionKind;
|
||||
/**
|
||||
* Path prefixes under `/api`, written exactly as they are mounted on protectedRouter in hono.ts —
|
||||
* leading slash, no `/api`. The totality check pairs these against the real mount table, so a prefix
|
||||
* here that nothing mounts is as much an error as a mount nothing claims.
|
||||
*/
|
||||
api: string[];
|
||||
/** WebSocket providers, named as in server.tsx's `handlers` map. */
|
||||
ws?: string[];
|
||||
/** Frontend route prefixes. Filters the dock and the app registry; never a security boundary. */
|
||||
routes?: string[];
|
||||
/**
|
||||
* Sub-paths, relative to each `api` prefix, that a READ grant may still mutate because they hold only
|
||||
* the caller's own data. Matched as a prefix after the permission's own: `/devices` on the `notify`
|
||||
* permission permits `POST /api/notify/devices/123`.
|
||||
*/
|
||||
personal?: string[];
|
||||
/**
|
||||
* Reads that must stay POST — see the note at the top. A read grant permits these paths at any method.
|
||||
* Written relative to the permission's `api` prefix, like `personal`.
|
||||
*/
|
||||
readOnlyWrites?: string[];
|
||||
/**
|
||||
* Routes any authenticated account may call even holding NO grant on this permission, because they act
|
||||
* on the caller themselves. `METHOD /exact/path`, relative to the permission's prefix — exact, not a
|
||||
* prefix, so this cannot widen by accident.
|
||||
*
|
||||
* One entry exists and it should stay that way. `PUT /api/users` is self-profile update (useAuth.ts
|
||||
* calls it to change your own name and avatar) and has always lived on the same router as the owner-only
|
||||
* account administration beside it. Moving it to `/api/user` would be tidier and would break every
|
||||
* shipped mobile client, so the honest fix is to say out loud that this one route is not what the
|
||||
* permission around it is.
|
||||
*/
|
||||
selfService?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The PLATFORM's own permissions. A plugin's are added on top at runtime — see `setPluginPermissions`.
|
||||
*
|
||||
* Kept separate from the live `PERMISSIONS` below so two invariants hold by construction rather than by
|
||||
* anyone remembering them: a plugin can never become `core` (granted to everyone, undeniable), and a
|
||||
* plugin is never in the fresh-install baseline.
|
||||
*/
|
||||
const CORE_REGISTRY: Permission[] = [
|
||||
// ── core ────────────────────────────────────────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'account',
|
||||
label: 'Account',
|
||||
description: 'Sign in, your own profile, password, preferences and API keys',
|
||||
kind: 'core',
|
||||
// `/api-keys` is core rather than app or admin because a key is not new authority — it is a second way
|
||||
// to present the authority the account already has, so denying it would only force the holder to keep
|
||||
// using a password in places a password should not go. What a key can then DO is decided by the same
|
||||
// permission checks as any other request from that user; nothing here widens them.
|
||||
api: ['/user', '/dock', '/api-keys'],
|
||||
routes: ['/settings/profile'],
|
||||
},
|
||||
{
|
||||
key: 'bug-report',
|
||||
label: 'Report a problem',
|
||||
description: 'Send the server owner a bug report',
|
||||
kind: 'core',
|
||||
api: ['/bug-report'],
|
||||
},
|
||||
|
||||
// ── app: the grantable surface ──────────────────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'gitea',
|
||||
label: 'Gitea',
|
||||
description: 'Repositories, issues, pull requests and notifications from your own Gitea account',
|
||||
kind: 'app',
|
||||
// api: ['/gitea'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/gitea'],
|
||||
// Every Gitea call is already scoped to the caller's own personal access token — the sidecar resolves
|
||||
// the token from the caller's row and the instance from the owner's, so a member holding `read` still
|
||||
// acts only as themselves upstream. Gitea's own permissions are the second gate and the real one:
|
||||
// a token cannot reach a repository its account cannot reach, whatever this platform thinks.
|
||||
//
|
||||
// Which is why the whole permission is `personal` rather than a list of sub-paths. Nothing under
|
||||
// /api/gitea can affect another Officer user, so withholding write here would only stop someone
|
||||
// commenting on their own issues — security theatre with a real cost and no benefit.
|
||||
personal: ['/'],
|
||||
},
|
||||
{
|
||||
key: 'photos',
|
||||
label: 'Photos',
|
||||
description: 'Browse the photo library',
|
||||
kind: 'app',
|
||||
// api: ['/photos'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/photos'],
|
||||
},
|
||||
{
|
||||
key: 'jellyfin',
|
||||
label: 'Video',
|
||||
description: 'Browse and play the Jellyfin library',
|
||||
kind: 'app',
|
||||
// api: ['/jellyfin'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/jellyfin'],
|
||||
},
|
||||
{
|
||||
key: 'memos',
|
||||
label: 'Memos',
|
||||
description: 'Notes',
|
||||
kind: 'app',
|
||||
// api: ['/memos'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/memos'],
|
||||
},
|
||||
{
|
||||
key: 'calendar',
|
||||
label: 'Calendar and contacts',
|
||||
description: 'Calendars, contacts, and the app passwords that sync them to a phone',
|
||||
kind: 'app',
|
||||
// api: ['/caldav', '/dav'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/calendar', '/contacts'],
|
||||
// App passwords are minted for and revoked by their own owner; `/dav` holds nothing shared.
|
||||
personal: ['/'],
|
||||
},
|
||||
{
|
||||
key: 'email',
|
||||
label: 'Email',
|
||||
description: 'Mail accounts and messages',
|
||||
kind: 'app',
|
||||
// api: ['/email'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/email'],
|
||||
},
|
||||
{
|
||||
key: 'notify',
|
||||
label: 'Notifications',
|
||||
description: 'Push notifications to your devices',
|
||||
kind: 'app',
|
||||
// api: ['/notify'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
// Device registration is the caller's own — a phone subscribing to its own push channel.
|
||||
personal: ['/devices', '/subscriptions'],
|
||||
},
|
||||
{
|
||||
key: 'transmission',
|
||||
label: 'Transmission',
|
||||
description: 'Torrent downloads',
|
||||
kind: 'app',
|
||||
// api: ['/transmission'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/transmission'],
|
||||
},
|
||||
{
|
||||
key: 'soulseek',
|
||||
label: 'Soulseek',
|
||||
description: 'Search and download from the Soulseek network',
|
||||
kind: 'app',
|
||||
// api: ['/slskd'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/soulseek'],
|
||||
},
|
||||
{
|
||||
key: 'invoices',
|
||||
label: 'Invoices',
|
||||
description: 'InvoiceShelf books',
|
||||
kind: 'app',
|
||||
// api: ['/invoiceshelf'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/invoices'],
|
||||
},
|
||||
// `vpn` (POST /api/vpn/enroll) was here until 2026-08-14 — the one member-grantable piece of headscale,
|
||||
// minting a pre-auth key bound to the caller. Deleted because it had no caller anywhere: the standalone
|
||||
// OffScale app gates it on `embedded`, which it never sets, and it never will — the app is permanently
|
||||
// independent of the platform, since the thing that gets you to the platform cannot itself need it.
|
||||
//
|
||||
// Device enrolment did not go away, it moved out. A phone claims an invite from the Companion at
|
||||
// `${invite.base}/api/v1/enroll/claim`, which is a different component entirely and does not involve
|
||||
// Officer. Confirmed against the mobile monorepo and the companion repo before removal.
|
||||
//
|
||||
// What this does cost: `headscale` is `admin`, so with `vpn` gone no member-grantable headscale surface
|
||||
// remains. Reintroduce one here if members ever need to enrol their own devices through Officer.
|
||||
// Core, not app — and this was a real defect, not a preference. `/api/dashboards` is not a feature, it is
|
||||
// the per-user key-value store where EVERY workspace screen keeps its layout (`screens/files`,
|
||||
// `ws-layout-*`, panel config). `WorkspaceView` renders nothing until that store has loaded, so gating it
|
||||
// meant a member with `files` granted got a completely blank Files screen and no request to
|
||||
// /api/file-browser at all — the panel never mounted. Same for Terminal, Chat and every other screen.
|
||||
//
|
||||
// It is entirely `personal` and always was: every row is keyed to the caller. There is nothing here to
|
||||
// withhold, and withholding it does not restrict an account, it breaks it — which is exactly the
|
||||
// definition of `core` at the top of this file.
|
||||
{
|
||||
key: 'dashboards',
|
||||
label: 'Screen layouts and dashboards',
|
||||
description: 'Where your own screen layouts and dashboards are saved',
|
||||
kind: 'core',
|
||||
api: ['/dashboards'],
|
||||
routes: ['/dashboards'],
|
||||
personal: ['/'],
|
||||
},
|
||||
|
||||
// ── execution: never grantable ──────────────────────────────────────────────────────────────────
|
||||
// Confined since 2026-08-11. A member's shell is spawned by the pty sidecar through `sudo setpriv` as their
|
||||
// own Linux account, in their own home, with the platform's environment cleared — so it is their shell, and
|
||||
// the kernel decides what it can reach. The sidecar also records whose each session is, so `list` and `kill`
|
||||
// scope to the caller instead of every shell on the box.
|
||||
//
|
||||
// What this is NOT is a jail. A member with a shell can `cd /` and read whatever the system leaves
|
||||
// world-readable, like any account on any machine. It isolates members from each other and from the owner's
|
||||
// files, which is the promise `confined` makes.
|
||||
{
|
||||
key: 'terminal',
|
||||
label: 'Terminal',
|
||||
description: 'A shell on this machine, as your own user',
|
||||
kind: 'confined',
|
||||
api: ['/terminal'],
|
||||
ws: ['terminal'],
|
||||
routes: ['/terminal'],
|
||||
},
|
||||
// Confined, and true since 2026-08-12: a member's turn spawns their own `claude` as their own Linux account
|
||||
// through `sudo setpriv`, with their own `~/.claude` credential, their own transcripts and sessions that
|
||||
// record whose they are. The two owner-only refusals that held this open — `api/chat/chat.ts` and the socket
|
||||
// in `server.tsx` — were removed together once each of those was in place.
|
||||
{
|
||||
key: 'chat',
|
||||
label: 'Chat',
|
||||
description: 'The agent',
|
||||
kind: 'confined',
|
||||
// `/agent-status` is on this grant but deliberately NOT on `chatRouter`, because that router refuses
|
||||
// non-owners wholesale — so an endpoint there could not be read by the accounts that need it. It reports
|
||||
// two booleans about the caller's own home and nothing about anyone else, which is what lets a member be
|
||||
// told "run `claude` once to sign in" instead of being shown a tile that 403s.
|
||||
api: ['/chat', '/agent-status'],
|
||||
ws: ['chat'],
|
||||
routes: ['/chat'],
|
||||
},
|
||||
// Confined rather than execution since 2026-08-11. Every path under `/file-browser` resolves its root
|
||||
// through `resolveHomeDir(userId)` in a middleware that refuses the request outright when the account has
|
||||
// no Linux user — so a member sees their own home and `resolveUserPath`'s containment check stops them
|
||||
// walking out of it. `/upload` was already per-caller: it writes only under
|
||||
// `DATA_PATH/<email>/attachments`, never into a home.
|
||||
{
|
||||
key: 'files',
|
||||
label: 'Files',
|
||||
description: 'Your own home directory on this machine, and the code editor over it',
|
||||
kind: 'confined',
|
||||
api: ['/file-browser', '/upload'],
|
||||
routes: ['/files', '/code-editor'],
|
||||
},
|
||||
{
|
||||
key: 'tasks',
|
||||
label: 'Tasks and jobs',
|
||||
description: 'Running permissions, pipelines and background jobs',
|
||||
kind: 'execution',
|
||||
api: ['/tasks', '/jobs', '/pipeline-jobs', '/queue'],
|
||||
ws: ['task-runner', 'pipeline'],
|
||||
routes: ['/jobs'],
|
||||
},
|
||||
{
|
||||
key: 'items',
|
||||
label: 'Permission authoring',
|
||||
description: 'Skills, tools, agents and processes on disk',
|
||||
kind: 'execution',
|
||||
api: ['/skills', '/tools', '/agents', '/processes', '/rescan'],
|
||||
},
|
||||
{
|
||||
key: 'desktop',
|
||||
label: 'Desktop',
|
||||
description: "The server owner's physical screen",
|
||||
kind: 'execution',
|
||||
// api: ['/desktop'], // plugin — switched off 2026-08-13
|
||||
// ws: ['desktop'],
|
||||
api: [],
|
||||
routes: ['/desktop'],
|
||||
},
|
||||
// `/browser` — the Chrome-extension relay — is unmounted as of 2026-08-13 and dropped from this claim,
|
||||
// because check 2 of assertPermissionTotality refuses to boot on a permission claiming a prefix nothing
|
||||
// serves. Put both back together or neither.
|
||||
//
|
||||
// `/scrape` is untouched and is what this permission still covers. It shares nothing with the relay: it
|
||||
// launches its own headless chromium through playwright and never speaks to the extension.
|
||||
{
|
||||
key: 'browser',
|
||||
label: 'Browser',
|
||||
description: 'Drives a real browser on the host',
|
||||
kind: 'execution',
|
||||
api: ['/scrape'],
|
||||
routes: ['/browser'],
|
||||
},
|
||||
|
||||
// ── admin: the platform administering itself ────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'app-store',
|
||||
label: 'App store',
|
||||
description: 'Install, enable and remove the sidecars this server runs',
|
||||
// Admin, not app. Installing a sidecar starts a process on the machine and provisioning one starts
|
||||
// containers — that is process control, not a feature a member can be granted a read of. The router
|
||||
// gates on the owner in its own right as well; this entry is what makes the boot check pass and what
|
||||
// keeps the surface visible in one enumeration.
|
||||
kind: 'admin',
|
||||
api: ['/app-store'],
|
||||
routes: ['/app-store'],
|
||||
},
|
||||
{
|
||||
key: 'plugins',
|
||||
label: 'Plugins',
|
||||
description: 'Install, enable and remove the plugins this server runs',
|
||||
// Admin for the same reason as the app store above: installing a plugin mounts routes and starts a
|
||||
// process, which is process control rather than a feature to grant a read of.
|
||||
//
|
||||
// Note this permission guards the MANAGEMENT surface, not the plugins themselves. A plugin declares
|
||||
// its own permissions in its manifest, and those are what gate its routes — so a member can hold
|
||||
// `offscale` at read without being able to install or remove anything.
|
||||
kind: 'admin',
|
||||
api: ['/plugins'],
|
||||
routes: ['/plugins'],
|
||||
},
|
||||
{
|
||||
key: 'server-admin',
|
||||
label: 'Server settings',
|
||||
description: 'Server configuration, integrations and the activity log',
|
||||
kind: 'admin',
|
||||
api: ['/server-settings', '/integrations', '/activity', '/system-monitor'],
|
||||
routes: ['/settings/server', '/settings/system', '/activity', '/system-monitor'],
|
||||
},
|
||||
{
|
||||
key: 'user-admin',
|
||||
label: 'User management',
|
||||
description: 'Accounts, roles and what each role may reach',
|
||||
kind: 'admin',
|
||||
api: ['/users'],
|
||||
routes: ['/settings/user-management'],
|
||||
// Changing your own name, username and avatar. Owner-only account administration is every other route
|
||||
// on this router and stays owner-only — see ownerGate in users-router.ts, which is the second lock.
|
||||
selfService: ['PUT /'],
|
||||
},
|
||||
// `headscale` lived here until 2026-08-15, when it left with the rest of offscale. A plugin declares
|
||||
// its own permissions in its manifest and they are registered at install — see plugins/mount.ts. The
|
||||
// platform no longer knows this permission exists, which is the entire point.
|
||||
{
|
||||
key: 'wallet',
|
||||
label: 'Wallet',
|
||||
description: "The server owner's bitcoin",
|
||||
kind: 'admin',
|
||||
// api: ['/wallet'], // plugin — switched off 2026-08-13
|
||||
api: [],
|
||||
routes: ['/wallet'],
|
||||
},
|
||||
];
|
||||
|
||||
// ── Derived lookups ───────────────────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// `let`, not `const`, because installing a plugin adds permissions and uninstalling removes them. ESM
|
||||
// exports are live bindings, so an importer holding `PERMISSION_BY_KEY` sees the reassignment — every
|
||||
// consumer reads these inside a function, never at module scope, which is what makes that safe.
|
||||
//
|
||||
// Nothing mutates the arrays in place. `setPluginPermissions` replaces them, for the same reason
|
||||
// `buildHonoApp` replaces the app rather than adding routes to it: a half-updated lookup is worse than a
|
||||
// stale one, and replacement has no half.
|
||||
|
||||
/** Core plus every installed plugin's. The list `permissionForApiPath` and the totality check read. */
|
||||
export let PERMISSIONS: Permission[] = CORE_REGISTRY;
|
||||
|
||||
export let PERMISSION_BY_KEY = new Map(PERMISSIONS.map((c) => [c.key, c]));
|
||||
|
||||
/**
|
||||
* The keys an owner may actually hand to a role. `core` is automatic; `execution` and `admin` are owner-only.
|
||||
*
|
||||
* `confined` is offered here, but a grant on one is inert for an account without a Linux user — that is
|
||||
* enforced in `authorize.ts`, not by withholding it from this list. Withholding it would mean the owner
|
||||
* could not pre-grant a role before provisioning the people in it, which is the normal order of operations.
|
||||
*/
|
||||
export let GRANTABLE_PERMISSIONS = PERMISSIONS.filter((c) => c.kind === 'app' || c.kind === 'confined');
|
||||
|
||||
/**
|
||||
* What every role starts with on a fresh install: the three confined permissions, at `write`.
|
||||
*
|
||||
* These are the baseline the platform is FOR — a terminal, a file browser and chat. An account that can sign
|
||||
* in and reach none of them is not a restricted account, it is a useless one, and making the owner grant them
|
||||
* by hand before anyone can do anything is a step with no decision in it.
|
||||
*
|
||||
* Seeded as real rows rather than implied by absence, which keeps the table's one rule intact: a missing row
|
||||
* means no access, always, with no exceptions to remember. So revoking one of these works exactly like
|
||||
* revoking anything else — the row goes, and nothing puts it back.
|
||||
*
|
||||
* `app` permissions are deliberately NOT here. Those reach data the owner may not intend to share, and each
|
||||
* needs a sidecar installed before it means anything anyway.
|
||||
*/
|
||||
// From CORE_REGISTRY, never from PERMISSIONS: a plugin must not be able to put itself in the baseline
|
||||
// every new role starts with.
|
||||
export const DEFAULT_ROLE_PERMISSIONS: string[] = CORE_REGISTRY.filter((c) => c.kind === 'confined').map((c) => c.key);
|
||||
|
||||
/**
|
||||
* Available to every signed-in account without a grant.
|
||||
*
|
||||
* From CORE_REGISTRY, so a plugin declaring `kind: 'core'` — which its manifest cannot express, but which
|
||||
* a future bug could smuggle in — still could not grant itself to everyone undeniably.
|
||||
*/
|
||||
export const CORE_CAPABILITIES = CORE_REGISTRY.filter((c) => c.kind === 'core');
|
||||
|
||||
/**
|
||||
* Replace the plugin half of the registry. Called after every install, uninstall, enable and disable.
|
||||
*
|
||||
* Plugin permissions are dropped and re-added wholesale rather than diffed: the source of truth is the
|
||||
* set of installed plugins, and computing a delta against it would be a second answer to the same
|
||||
* question. A key colliding with a core one is REFUSED here rather than silently overriding — a plugin
|
||||
* that could redefine `chat` or `terminal` could widen it.
|
||||
*/
|
||||
export function setPluginPermissions(pluginPermissions: Permission[]): { rejected: string[] } {
|
||||
const coreKeys = new Set(CORE_REGISTRY.map((c) => c.key));
|
||||
const seen = new Set<string>();
|
||||
const accepted: Permission[] = [];
|
||||
const rejected: string[] = [];
|
||||
|
||||
for (const permission of pluginPermissions) {
|
||||
if (coreKeys.has(permission.key) || seen.has(permission.key)) {
|
||||
rejected.push(permission.key);
|
||||
continue;
|
||||
}
|
||||
seen.add(permission.key);
|
||||
accepted.push(permission);
|
||||
}
|
||||
|
||||
PERMISSIONS = [...CORE_REGISTRY, ...accepted];
|
||||
PERMISSION_BY_KEY = new Map(PERMISSIONS.map((c) => [c.key, c]));
|
||||
GRANTABLE_PERMISSIONS = PERMISSIONS.filter((c) => c.kind === 'app' || c.kind === 'confined');
|
||||
return { rejected };
|
||||
}
|
||||
|
||||
export type PermissionLevel = 'read' | 'write';
|
||||
|
||||
const isPrefixOf = (prefix: string, path: string): boolean =>
|
||||
prefix === '/' || path === prefix || path.startsWith(`${prefix}/`);
|
||||
|
||||
/**
|
||||
* Which permission owns this path? `path` is the full request path (`/api/gitea/...`).
|
||||
*
|
||||
* Longest prefix wins, so a permission may claim `/dav` while another claims `/dav/something` without the
|
||||
* order of the array mattering. Returns null for a path no permission claims — which the totality check
|
||||
* below is there to make impossible for anything mounted on protectedRouter.
|
||||
*/
|
||||
export function permissionForApiPath(path: string): Permission | null {
|
||||
const rest = path.startsWith('/api') ? path.slice('/api'.length) : path;
|
||||
let best: Permission | null = null;
|
||||
let bestLength = -1;
|
||||
for (const permission of PERMISSIONS) {
|
||||
for (const prefix of permission.api) {
|
||||
if (isPrefixOf(prefix, rest) && prefix.length > bestLength) {
|
||||
best = permission;
|
||||
bestLength = prefix.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function permissionForWsProvider(provider: string): Permission | null {
|
||||
return PERMISSIONS.find((c) => c.ws?.includes(provider)) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this an exact self-service route — one any authenticated account may call without holding the
|
||||
* permission at all? Matched exactly on method AND path, never as a prefix.
|
||||
*/
|
||||
export function isSelfServiceRoute(permission: Permission, method: string, path: string): boolean {
|
||||
if (!permission.selfService?.length) return false;
|
||||
const rest = path.startsWith('/api') ? path.slice('/api'.length) : path;
|
||||
const upper = method.toUpperCase();
|
||||
return permission.api.some((prefix) => {
|
||||
if (!isPrefixOf(prefix, rest)) return false;
|
||||
const sub = rest.slice(prefix.length) || '/';
|
||||
return permission.selfService!.includes(`${upper} ${sub}`);
|
||||
});
|
||||
}
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
/**
|
||||
* May a caller holding `level` on `permission` make this request?
|
||||
*
|
||||
* `write` is unconditional within the permission. `read` permits safe methods, anything the permission
|
||||
* declares as a `readOnlyWrites` read-in-POST-clothing, and mutations confined to `personal` sub-paths.
|
||||
*/
|
||||
export function isRequestAllowedAtLevel(
|
||||
permission: Permission,
|
||||
level: PermissionLevel,
|
||||
method: string,
|
||||
path: string,
|
||||
): boolean {
|
||||
if (level === 'write') return true;
|
||||
if (SAFE_METHODS.has(method.toUpperCase())) return true;
|
||||
|
||||
const rest = path.startsWith('/api') ? path.slice('/api'.length) : path;
|
||||
// Strip whichever of the permission's own prefixes matched, so `personal` entries are written relative
|
||||
// to the permission rather than repeated per prefix.
|
||||
const withinPermission = permission.api
|
||||
.filter((prefix) => isPrefixOf(prefix, rest))
|
||||
.map((prefix) => rest.slice(prefix.length) || '/');
|
||||
|
||||
const allowed = [...(permission.personal ?? []), ...(permission.readOnlyWrites ?? [])];
|
||||
return withinPermission.some((sub) => allowed.some((entry) => isPrefixOf(entry, sub)));
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { PERMISSIONS, permissionForApiPath, permissionForWsProvider } from './registry';
|
||||
|
||||
// The part that actually matters.
|
||||
//
|
||||
// On 2026-08-06 a Member token that was 403'd on `GET /api/tasks` opened `/api/tasks/pipeline/ws` and got
|
||||
// a 101 in the same minute — a shell, the agent with --dangerously-skip-permissions, arbitrary script
|
||||
// execution and the owner's screen, all reachable. The cause was not a bad rule. It was that WebSocket
|
||||
// upgrades never reach Hono's middleware at all: Bun's route table in server.tsx matches
|
||||
// `/api/terminal/ws` before the `/api/*` catch-all, so the authorisation gate was simply not on that code
|
||||
// path. Nobody had written a rule that was wrong; a door had been added and the rule had not been told.
|
||||
//
|
||||
// It was fixed in 2873948 by adding the check to the socket door too. That fix is a patch, and patches of
|
||||
// that shape do not survive the next door. What survives is refusing to boot: every mounted API prefix and
|
||||
// every user-facing WebSocket provider must map to exactly one permission, or the server does not start.
|
||||
// Add a router and forget the registry and you find out during `pm2 restart`, not during an incident.
|
||||
//
|
||||
// The exemptions below are the honest cost of that: a short list of surfaces that genuinely are not
|
||||
// user-permission-gated, each of which has to say why. A list that grows silently is the failure mode, so
|
||||
// keep it short and keep the reasons real.
|
||||
|
||||
/**
|
||||
* Mounted under `honoServer` directly rather than `protectedRouter`, and gated by something other than a
|
||||
* platform permission. Each entry is a claim that has to stay true.
|
||||
*/
|
||||
const EXEMPT_API_PREFIXES: Record<string, string> = {
|
||||
// Unauthenticated by necessity — this is where a caller goes to BECOME authenticated.
|
||||
'/auth': 'signin, bootstrap and token refresh; runs before any account exists to check',
|
||||
// Public marketing surfaces, served to anonymous visitors.
|
||||
'/landing-page-data': 'public landing page content, no account involved',
|
||||
'/waitlist': 'public signup form, no account involved',
|
||||
// The Bitwarden clients carry their own bearer token, not a platform JWT, so userMiddleware would 401
|
||||
// them and a permission lookup has no account to resolve. Gated by origin scoping and Vaultwarden itself.
|
||||
'/vault': 'Bitwarden protocol clients authenticate to Vaultwarden, not to Officer',
|
||||
// Registration socket for sidecars. Process-to-process on loopback; there is no user on this path.
|
||||
'/sidecar': 'sidecar registration, loopback process-to-process',
|
||||
// The caller is a Claude session running curl, not a browser: it has no platform JWT to present, so
|
||||
// userMiddleware would 401 it and a permission lookup would have no account to resolve. What it does
|
||||
// present is a per-panel token minted by the platform, which identifies exactly one agent panel and
|
||||
// authorises exactly one action — deliver a prompt to a NAMED PEER ON THAT PANEL'S OWN DASHBOARD.
|
||||
// It reads nothing else, writes nothing else, and cannot name a raw session key. The narrowness is
|
||||
// the whole justification: this is not a general API door with a second credential, it is one verb.
|
||||
'/agent-handoff': 'agent-to-agent handoff; a per-panel bearer token authorising one verb, not a platform JWT',
|
||||
};
|
||||
|
||||
/**
|
||||
* WebSocket providers that do not go through `upgradeWs` and therefore never carry a platform account.
|
||||
*/
|
||||
const EXEMPT_WS_PROVIDERS: Record<string, string> = {
|
||||
sidecar: 'sidecar registration, loopback process-to-process, no user',
|
||||
vault: 'Vaultwarden notifications hub; upgraded by upgradeVaultWs with a Bitwarden token',
|
||||
};
|
||||
|
||||
/**
|
||||
* Is this path served above the account gate?
|
||||
*
|
||||
* Read by the permission backstop, so that signin — which by definition has no account to check — is not
|
||||
* asked to prove a permission. Deliberately shares EXEMPT_API_PREFIXES with the boot check: an exemption
|
||||
* granted at boot and an exemption honoured at request time must be the same list, or one of them is a
|
||||
* hole.
|
||||
*/
|
||||
export function isExemptApiPath(path: string): boolean {
|
||||
const rest = path.startsWith('/api') ? path.slice('/api'.length) : path;
|
||||
return Object.keys(EXEMPT_API_PREFIXES).some((prefix) => rest === prefix || rest.startsWith(`${prefix}/`));
|
||||
}
|
||||
|
||||
export type PermissionSurface = {
|
||||
/** Every prefix mounted on protectedRouter, as written in hono.ts. */
|
||||
apiPrefixes: string[];
|
||||
/** Every key of the `handlers` map in server.tsx. */
|
||||
wsProviders: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Refuses to return if the registry and the real surface disagree. Called from the boot path.
|
||||
*
|
||||
* Four ways to fail, and all four are real bugs rather than pedantry:
|
||||
* - a mounted prefix no permission claims → reachable by a rule nobody wrote
|
||||
* - a prefix two permissions claim → which grant applies is undefined
|
||||
* - a declared prefix nothing mounts → the registry is describing a router that no longer exists
|
||||
* - a socket provider no permission claims → exactly the 2026-08-06 hole, structurally
|
||||
*/
|
||||
export function assertPermissionTotality(surface: PermissionSurface): void {
|
||||
const problems: string[] = [];
|
||||
|
||||
// 1. Every mount is claimed, and claimed once.
|
||||
for (const prefix of surface.apiPrefixes) {
|
||||
if (prefix in EXEMPT_API_PREFIXES) continue;
|
||||
const claimants = PERMISSIONS.filter((c) => c.api.includes(prefix));
|
||||
if (claimants.length === 0) {
|
||||
problems.push(`/api${prefix} is mounted but no permission claims it — add it to the registry`);
|
||||
} else if (claimants.length > 1) {
|
||||
problems.push(`/api${prefix} is claimed by ${claimants.map((c) => c.key).join(', ')} — it must be exactly one`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Every claim corresponds to something real. Catches a router that was deleted or renamed while the
|
||||
// registry kept describing it — which would leave a grant that silently means nothing.
|
||||
const mounted = new Set(surface.apiPrefixes);
|
||||
for (const permission of PERMISSIONS) {
|
||||
for (const prefix of permission.api) {
|
||||
if (!mounted.has(prefix)) {
|
||||
problems.push(`permission '${permission.key}' claims /api${prefix}, which nothing mounts`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Every socket door is claimed. This is the one the incident was about.
|
||||
for (const provider of surface.wsProviders) {
|
||||
if (provider in EXEMPT_WS_PROVIDERS) continue;
|
||||
if (!permissionForWsProvider(provider)) {
|
||||
problems.push(`websocket provider '${provider}' is served but no permission claims it`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. And no permission claims a socket that does not exist.
|
||||
const providers = new Set(surface.wsProviders);
|
||||
for (const permission of PERMISSIONS) {
|
||||
for (const provider of permission.ws ?? []) {
|
||||
if (!providers.has(provider)) {
|
||||
problems.push(`permission '${permission.key}' claims websocket '${provider}', which is not served`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Keys are unique — a duplicate would make grants ambiguous in the database.
|
||||
const seen = new Set<string>();
|
||||
for (const permission of PERMISSIONS) {
|
||||
if (seen.has(permission.key)) problems.push(`duplicate permission key '${permission.key}'`);
|
||||
seen.add(permission.key);
|
||||
}
|
||||
|
||||
if (problems.length > 0) {
|
||||
throw new Error(
|
||||
[
|
||||
'Permission registry does not cover the served surface. The server will not start.',
|
||||
'',
|
||||
...problems.map((p) => ` • ${p}`),
|
||||
'',
|
||||
'Fix src/servers/permissions/registry.ts. If a surface genuinely is not permission-gated, add it',
|
||||
'to the exemption list in totality.ts WITH a reason — an unexplained exemption is how the',
|
||||
'websocket hole happened.',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Exposed for the settings UI, so an owner can see what a permission actually covers. */
|
||||
export function describePermissionSurface(): {
|
||||
exemptApi: typeof EXEMPT_API_PREFIXES;
|
||||
exemptWs: typeof EXEMPT_WS_PROVIDERS;
|
||||
} {
|
||||
return { exemptApi: EXEMPT_API_PREFIXES, exemptWs: EXEMPT_WS_PROVIDERS };
|
||||
}
|
||||
|
||||
export { permissionForApiPath };
|
||||
Reference in New Issue
Block a user