Other machines have to make the same database change, and pasted SQL is the
wrong way to ship it. `scripts/rename-capabilities-to-permissions.ts` renames
the table, its column, both indexes and its three CHECK constraints in one
transaction, and refuses to guess:
neither table nothing to do; db:push will create it
already renamed no-op, prints the grant count
BOTH tables present stops and says a human must decide
old table only migrates, counts before and after, prints every grant
Testing it found a bug that reading it had not. The existence checks were
inside the transaction but ran on the pool rather than on `tx`, so they could
not see the uncommitted rename: `columnExists('role_permissions','capability')`
answered false because that table did not exist yet on that connection, and the
COLUMN rename was silently skipped. The result was a `role_permissions` table
with a `capability` column — half migrated, and only failing on the next query.
That was found by building a scratch database in edge-pertento's exact shape
and running the script against it, rather than by review. Every check now
happens before the transaction, against the old names.
Verified end to end on that scratch: 6 grants migrated intact, a second run
correctly no-ops, and `db:push` afterwards leaves role_permissions and its rows
alone while creating the rest of the schema. Indexes come out as
role_permissions_pkey and uq_role_permissions_role_permission.
Also swept the last all-caps survivors the case-sensitive passes missed:
CORE_CAPABILITIES → CORE_PERMISSIONS, and a react-query key still spelling
['ROLE_CAPABILITIES']. The only CAPABILITIES left in src/ is the wallet's, which
is Lightning and stays.
175 lines
8.4 KiB
TypeScript
175 lines
8.4 KiB
TypeScript
import { getUserById, getRoleGrants } from 'officerdb';
|
|
import type { UserRole } from 'officerdb';
|
|
import {
|
|
PERMISSION_BY_KEY,
|
|
CORE_PERMISSIONS,
|
|
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_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 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);
|
|
}
|