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:
2026-08-15 16:03:22 +00:00
parent b0fcd8b81b
commit 2e8ec845c8
59 changed files with 454 additions and 442 deletions
+240
View File
@@ -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);
});
});