Rollen und Rechte auf @core/auth: Platzhalter, Eigentümer-Regeln und Vergabe ohne Rechteausweitung
Installieren
genpm add @core/rbacWas du bekommst
- Quellcode in src/lib/rbac/, 10 Dateien. (20,1 kB)
- KI-Regeln in src/lib/rbac/AGENTS.md, dazu Regeldateien für die IDE.
- Löst @core/auth, @core/contracts, @core/db für dich auf.
README
Dieses Paket hat keine README.
Genau das liest deine KI, wenn sie in src/lib/rbac arbeitet. Sonst wird ihrem Kontext nichts hinzugefügt.
@core/rbac — rules for AI agents
Purpose
Authorization on top of @core/auth users: roles stored in the database, permissions resource:action with wildcards
(posts:*, *) and own-only grants (posts:update:own), and a role hierarchy (rank) that prevents privilege
escalation. Default roles: owner, admin, editor, support, author. Not authentication, not multi-tenancy.
Map
index.ts— public API:can,assertCan,getGrants,grantRole,revokeRole,bootstrapOwner,defineRole,ensureDefaultRoles.permissions.ts— pure matchergrants()(no DB).defaults.ts— default roles and their permissions.schema.ts— tablesroles,user_roles. Depends on../dband../auth.adapters/hono.ts—requirePermission(perm)middleware.adapters/next.ts—requirePermission(user, perm),permissionResponse(user, perm).admin.ts—usersAdminResourcefor @core/admin (users with roles; grant/revoke actions withusers:manage).
Integration
- Generate and apply migrations (see
src/lib/db/AGENTS.md). - At startup or in a setup script:
await ensureDefaultRoles(). - Make the first user owner once, e.g. in the
onLoginhook of @core/auth:onLogin: async ({ user, isNewUser }) => { if (isNewUser) await bootstrapOwner(user.id); }(only the first call wins). - Hono:
app.use(sessionMiddleware); app.post('/api/posts/:id/publish', requirePermission('posts:publish'), handler). Next.js:const user = await getUser(await cookies()); await requirePermission(user, 'posts:publish'); - Own-only checks:
await assertCan(user.id, 'posts:update', { ownerId: post.authorId }). - Verify: a user without roles gets 403; the owner gets 200.
Conventions
- Permission names: lowercase
resource:action(orders:refund). Actions in use: read, create, update, delete, publish, manage. - Check permissions on the server for every write and every private read; hiding UI is not authorization.
- Load
getGrants(userId)once per request and pass it tocan()when checking several permissions. - Change roles only through
grantRole/revokeRole(they enforce the hierarchy and keep at least one owner).
Don't
- Don't insert into
user_rolesdirectly, and don't add an env flag or "god mode" that bypassescan(). - Don't expose
defineRoleto users without checkingusers:manageand that the new rank is below the actor's. - Don't trust a role or permission sent by the client.
# @core/rbac — rules for AI agents
## Purpose
Authorization on top of @core/auth users: roles stored in the database, permissions `resource:action` with wildcards
(`posts:*`, `*`) and own-only grants (`posts:update:own`), and a role hierarchy (`rank`) that prevents privilege
escalation. Default roles: owner, admin, editor, support, author. Not authentication, not multi-tenancy.
## Map
- `index.ts` — public API: `can`, `assertCan`, `getGrants`, `grantRole`, `revokeRole`, `bootstrapOwner`, `defineRole`, `ensureDefaultRoles`.
- `permissions.ts` — pure matcher `grants()` (no DB).
- `defaults.ts` — default roles and their permissions.
- `schema.ts` — tables `roles`, `user_roles`. Depends on `../db` and `../auth`.
- `adapters/hono.ts` — `requirePermission(perm)` middleware. `adapters/next.ts` — `requirePermission(user, perm)`, `permissionResponse(user, perm)`.
- `admin.ts` — `usersAdminResource` for @core/admin (users with roles; grant/revoke actions with `users:manage`).
## Integration
1. Generate and apply migrations (see `src/lib/db/AGENTS.md`).
2. At startup or in a setup script: `await ensureDefaultRoles()`.
3. Make the first user owner once, e.g. in the `onLogin` hook of @core/auth:
`onLogin: async ({ user, isNewUser }) => { if (isNewUser) await bootstrapOwner(user.id); }` (only the first call wins).
4. Hono: `app.use(sessionMiddleware); app.post('/api/posts/:id/publish', requirePermission('posts:publish'), handler)`.
Next.js: `const user = await getUser(await cookies()); await requirePermission(user, 'posts:publish');`
5. Own-only checks: `await assertCan(user.id, 'posts:update', { ownerId: post.authorId })`.
6. Verify: a user without roles gets 403; the owner gets 200.
## Conventions
- Permission names: lowercase `resource:action` (`orders:refund`). Actions in use: read, create, update, delete, publish, manage.
- Check permissions on the server for every write and every private read; hiding UI is not authorization.
- Load `getGrants(userId)` once per request and pass it to `can()` when checking several permissions.
- Change roles only through `grantRole`/`revokeRole` (they enforce the hierarchy and keep at least one owner).
## Don't
- Don't insert into `user_roles` directly, and don't add an env flag or "god mode" that bypasses `can()`.
- Don't expose `defineRole` to users without checking `users:manage` and that the new rank is below the actor's.
- Don't trust a role or permission sent by the client.
Der genaue Baum, der nach .genpmignore eingebunden wird. Gepinnt an
// Comprobación pura de permisos (sin BD): comodines y sufijo `:own`.
export type PermissionContext = {
/** Dueño del registro sobre el que se actúa; activa los permisos `…:own`. */
ownerId?: string | null;
};
// Recurso con `_` permitido: colecciones como `site_settings` (@core/site).
const PERMISSION_RE = /^(\*|[a-z][a-z0-9_-]*(:([a-z][a-z0-9-]*|\*))?(:own)?)$/;
export function isValidPermission(p: string): boolean {
return PERMISSION_RE.test(p);
}
/**
* ¿Concede `granted` el permiso `required` (`recurso:acción`)? `*` concede todo; `posts:*` toda acción sobre posts;
* `posts:update:own` solo si `ctx.ownerId` es el propio usuario.
*/
export function grants(
granted: readonly string[],
required: string,
userId: string,
ctx: PermissionContext = {},
): boolean {
const [resource, action] = required.split(':');
if (!resource || !action || required.endsWith(':own')) throw new Error(`invalid permission check: ${required}`);
const own = ctx.ownerId != null && ctx.ownerId === userId;
return granted.some(
(g) =>
g === '*' ||
g === required ||
g === `${resource}:*` ||
(own && (g === `${required}:own` || g === `${resource}:*:own`)),
);
}
Dieses Paket deklariert keine MCP-Server.
| Version | Commit | Veröffentlicht | Prüfung |
|---|---|---|---|
| 1.0.1 | decbadd | vor 4 Stunden | Prüfung bestanden |
- npm
- keine
- vorgeschlagen
- GenPM schlägt den npm-Befehl vor und führt ihn nur aus, wenn du zustimmst.
- Verwendet von (1)
- @core/admin ^1.0.0
- Prüfung
- Prüfung bestanden · 0 Befunde
- Commit
- v1.0.1 → decbadd748476defda5138e5dc02cd5b7086463b · nach dem Abruf verifiziert
- Skripte
- Keine. GenPM führt niemals Paketcode aus.
- Lizenz
- MIT
- Qualität
- 100/100
- Anerkannte Lizenzerfüllt
- AGENTS.md erklärt den Zweckerfüllt
- AGENTS.md enthält Integrationsschritteerfüllt
- AGENTS.md nennt Konventionen oder Verboteerfüllt
- Enthält Testserfüllt
- Sicherheitsscan bestandenerfüllt
- In den letzten 6 Monaten veröffentlichterfüllt
- Verifizierter Herausgebererfüllt
- Zusammenfassung und Schlagwörtererfüllt
- Meldung
- Stimmt etwas nicht?