Rôles et permissions sur @core/auth : jokers, droits sur ses propres données, attributions sans escalade
Installer
genpm add @core/rbacCe que vous obtenez
- Source dans src/lib/rbac/, 10 fichiers. (20,1 ko)
- Règles IA dans src/lib/rbac/AGENTS.md, plus les fichiers de règles de l’IDE.
- Résout @core/auth, @core/contracts, @core/db pour vous.
README
Ce paquet n’a pas de README.
Voici exactement ce que lit votre IA quand elle travaille dans src/lib/rbac. Rien d’autre n’est ajouté à son contexte.
@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.
L’arborescence exacte qui sera injectée, après .genpmignore. Épinglée à
// Adaptador Next.js (App Router), sin importar `next`.
// Server Component / Server Action: `const user = await getUser(await cookies()); await requirePermission(user, 'posts:publish');`
// Route handler: `const denied = await permissionResponse(user, 'orders:refund'); if (denied) return denied;`
import { can, type Grants, getGrants, type PermissionContext, RbacError } from '../index.ts';
type MaybeUser = { id: string } | null | undefined;
/** Lanza `RbacError` (`forbidden`) si no hay usuario o le falta el permiso; devuelve sus `Grants`. */
export async function requirePermission(user: MaybeUser, permission: string, ctx?: PermissionContext): Promise<Grants> {
if (!user) throw new RbacError('forbidden', 'not signed in');
const g = await getGrants(user.id);
if (!(await can(g, permission, ctx))) throw new RbacError('forbidden', `missing permission ${permission}`);
return g;
}
/** Para route handlers: `Response` 401/403 si no se puede, o `null` si se puede. */
export async function permissionResponse(
user: MaybeUser,
permission: string,
ctx?: PermissionContext,
): Promise<Response | null> {
if (!user) return Response.json({ error: 'unauthorized' }, { status: 401 });
return (await can(user.id, permission, ctx)) ? null : Response.json({ error: 'forbidden' }, { status: 403 });
}
Ce paquet ne déclare aucun serveur MCP.
| Version | Commit | Publié | Analyse |
|---|---|---|---|
| 1.0.1 | decbadd | il y a 7 heures | analyse réussie |
- npm
- aucun
- proposé
- GenPM propose la commande npm et ne l’exécute que si vous acceptez.
- Utilisé par (1)
- @core/admin ^1.0.0
- analyse
- analyse réussie · 0 problème
- commit
- v1.0.1 → decbadd748476defda5138e5dc02cd5b7086463b · vérifié après téléchargement
- scripts
- Aucun. GenPM n’exécute jamais le code des paquets.
- licence
- MIT
- Qualité
- 100/100
- Licence reconnuevalidé
- AGENTS.md explique son objectifvalidé
- AGENTS.md donne les étapes d’intégrationvalidé
- AGENTS.md liste conventions ou interditsvalidé
- Contient des testsvalidé
- Analyse de sécurité réussievalidé
- Publié au cours des 6 derniers moisvalidé
- Éditeur vérifiévalidé
- Résumé et mots-clésvalidé
- signalement
- Vous avez repéré un problème ?