@willyim/rbac 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,190 +1,27 @@
1
- # @willyim/rbac
1
+ # @willyim/rbac (deprecated)
2
2
 
3
- Typed RBAC where permissions are the primitive and roles are named permission bags.
3
+ **Deprecated.** Permissions are part of [`@willyim/kit`](https://github.com/wovalle/willy.im/tree/main/packages/kit#readme) now. This
4
+ package's last release only re-exports kit, so existing imports keep working.
4
5
 
5
- Define your permissions once, get fully typed checkers for your server loaders and a hook factory for your React components.
6
+ ## Move to kit
6
7
 
7
- ## Install
8
-
9
- ```bash
10
- npm install @willyim/rbac
11
- ```
12
-
13
- ## Define permissions
14
-
15
- ```ts
16
- import { definePermissions } from "@willyim/rbac"
17
-
18
- export const auth = definePermissions({
19
- permissions: [
20
- "contacts:read",
21
- "contacts:import",
22
- "reports:read",
23
- "calendar:read",
24
- "calendar:read-all",
25
- "settings:read",
26
- "settings:manage",
27
- ] as const,
28
- roles: {
29
- admin: [
30
- "contacts:read",
31
- "contacts:import",
32
- "reports:read",
33
- "calendar:read",
34
- "calendar:read-all",
35
- "settings:read",
36
- "settings:manage",
37
- ],
38
- agent: ["contacts:read", "calendar:read", "settings:read"],
39
- },
40
- })
41
-
42
- // Derive types from your config
43
- export type Permission = (typeof auth.permissions)[number]
44
- export type Role = keyof typeof auth.roles
8
+ ```sh
9
+ npm uninstall @willyim/rbac
10
+ npm install @willyim/kit zod
45
11
  ```
46
12
 
47
- Permissions and roles are inferred from your config — typos in role arrays are caught at compile time.
48
-
49
- ## Check permissions (server)
50
-
51
- `createChecker` returns a `PermissionChecker` scoped to a role. Use it in loaders, middleware, or anywhere on the server.
52
-
53
- ```ts
54
- const checker = auth.createChecker("agent")
55
-
56
- checker.has("contacts:read") // true
57
- checker.has("reports:read") // false
58
-
59
- // Throws a 403 Response if the permission is not granted
60
- checker.require("reports:read") // throws Response("Forbidden", { status: 403 })
61
- ```
62
-
63
- ### Superadmin
64
-
65
- Pass `{ superadmin: true }` to grant all permissions regardless of role. The library handles the semantics; your app decides who is a superadmin.
66
-
67
- ```ts
68
- const checker = auth.createChecker("agent", { superadmin: isSuperAdmin(user.email) })
69
-
70
- checker.has("reports:read") // true — superadmin bypasses role restrictions
71
- checker.isSuperadmin // true
72
- checker.granted // all permissions in the system
73
- ```
74
-
75
- Add superadmin-only features as permissions that no role lists. Only superadmins (via the flag) will ever have them:
76
-
77
- ```ts
78
- // permissions.ts
79
- export const auth = definePermissions({
80
- permissions: ["contacts:read", /* ... */, "jobs:manage"] as const,
81
- roles: {
82
- admin: ["contacts:read", /* ... */], // jobs:manage not listed — only superadmins get it
83
- },
84
- })
85
-
86
- // route loader
87
- if (!permissions.has("jobs:manage")) throw new Response("Not Found", { status: 404 })
88
- ```
89
-
90
- ### React Router loader example
91
-
92
- ```ts
93
- // app/lib/session.ts
94
- import { auth } from "./permissions"
95
-
96
- export async function getSessionContext() {
97
- const role = await getRoleFromSession()
98
- const permissions = auth.createChecker(role, { superadmin: isSuperAdmin(user.email) })
99
- return { permissions, /* ... */ }
100
- }
101
-
102
- // app/routes/reports.tsx
103
- export async function loader({ context }: Route.LoaderArgs) {
104
- const { permissions } = await context.getSessionContext()
105
- permissions.require("reports:read")
106
- return { /* ... */ }
107
- }
108
- ```
109
-
110
- ## Check permissions (React)
111
-
112
- The `@willyim/rbac/react` entry point exports `createPermissionsHook`, a factory that builds a typed `usePermissions` hook from any data source.
113
-
114
- ```ts
115
- // app/hooks/use-permissions.ts
116
- import { createPermissionsHook } from "@willyim/rbac/react"
117
- import { useRouteLoaderData } from "react-router"
118
- import type { Permission } from "../lib/permissions"
119
-
120
- export const usePermissions = createPermissionsHook<Permission>(() => {
121
- const data = useRouteLoaderData("routes/_dashboard_layout")
122
- return {
123
- granted: data?.permissions.granted ?? [],
124
- isSuperadmin: data?.permissions.isSuperadmin ?? false,
125
- }
126
- })
127
- ```
128
-
129
- Then use it in components:
130
-
131
- ```tsx
132
- function Nav() {
133
- const { has } = usePermissions()
134
-
135
- return (
136
- <nav>
137
- <Link to="/">Home</Link>
138
- {has("reports:read") && <Link to="/reports">Reports</Link>}
139
- {has("settings:manage") && <Link to="/settings">Settings</Link>}
140
- </nav>
141
- )
142
- }
143
- ```
144
-
145
- ## API
146
-
147
- ### `definePermissions(config)`
148
-
149
- | Parameter | Type | Description |
150
- |-----------|------|-------------|
151
- | `config.permissions` | `readonly string[]` | All permissions in the system (use `as const`) |
152
- | `config.roles` | `Record<string, readonly Permission[]>` | Each role maps to a subset of permissions |
153
-
154
- Returns an object with:
155
-
156
- - `createChecker(role, opts?)` — returns a `PermissionChecker` for the given role
157
- - `permissions` — the original permissions array
158
- - `roles` — the original roles config
159
-
160
- ### `PermissionChecker<P>`
161
-
162
- | Member | Description |
163
- |--------|-------------|
164
- | `has(permission)` | Returns `true` if the permission is granted (always `true` for superadmin) |
165
- | `require(permission)` | Throws `Response("Forbidden", { status: 403 })` if not granted (never throws for superadmin) |
166
- | `granted` | Array of all granted permissions (all permissions for superadmin) |
167
- | `isSuperadmin` | `true` when the checker was created with `{ superadmin: true }` |
168
-
169
- ### `CheckerOptions`
170
-
171
- | Option | Type | Default | Description |
172
- |--------|------|---------|-------------|
173
- | `superadmin` | `boolean` | `false` | When `true`, all `has()` checks pass and `granted` returns every permission |
174
-
175
- ### `createPermissionsHook(useData)`
13
+ | Before | After |
14
+ |---|---|
15
+ | `import { definePermissions } from "@willyim/rbac"` | `import { definePermissions } from "@willyim/kit"` |
16
+ | `import { createPermissionsHook } from "@willyim/rbac/react"` | `import { createPermissionsHook } from "@willyim/kit/react"` |
176
17
 
177
- | Parameter | Type | Description |
178
- |-----------|------|-------------|
179
- | `useData` | `() => { granted: P[], isSuperadmin?: boolean }` | A React hook that returns permissions data from your loader |
18
+ The API is the same, with two additions in `checkerFor(grants)`:
180
19
 
181
- Returns a `usePermissions` hook with:
20
+ - `"*"` is a superadmin: `has` is always true and `isSuperadmin` is true. It used to be dropped.
21
+ - `definePermissions({ ..., resources: ["thread"] })` accepts instance grants such as
22
+ `"thread:abc"`, and `"thread:*"` for every instance.
182
23
 
183
- | Property | Description |
184
- |----------|-------------|
185
- | `has(permission)` | Returns `true` if the permission is granted |
186
- | `granted` | Array of all granted permissions |
187
- | `isSuperadmin` | `true` when the data source explicitly sets it (not inferred) |
24
+ See kit's README, section "Grants".
188
25
 
189
26
  ## License
190
27
 
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** @deprecated `@willyim/rbac` is part of `@willyim/kit` now: import from "@willyim/kit". */
2
+ export {
3
+ definePermissions,
4
+ type CheckerOptions,
5
+ type DefinePermissionsConfig,
6
+ type PermissionChecker,
7
+ type PermissionsResult,
8
+ } from "@willyim/kit"
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ /** @deprecated `@willyim/rbac` is part of `@willyim/kit` now: import from "@willyim/kit". */
2
+ export { definePermissions } from "@willyim/kit"
package/package.json CHANGED
@@ -1,22 +1,26 @@
1
1
  {
2
2
  "name": "@willyim/rbac",
3
- "version": "0.2.1",
4
- "description": "Typed RBAC where permissions are the primitive and roles are named permission bags",
3
+ "version": "0.4.0",
4
+ "description": "Deprecated: use @willyim/kit, which includes these permissions",
5
+ "deprecated": "@willyim/rbac is part of @willyim/kit now. Install @willyim/kit and import definePermissions from \"@willyim/kit\" (the hook from \"@willyim/kit/react\").",
5
6
  "type": "module",
6
- "main": "./dist/src/define-permissions.js",
7
- "types": "./dist/src/define-permissions.d.ts",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
8
9
  "exports": {
9
10
  ".": {
10
- "types": "./dist/src/define-permissions.d.ts",
11
- "default": "./dist/src/define-permissions.js"
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
12
13
  },
13
14
  "./react": {
14
- "types": "./dist/src/create-permissions-hook.d.ts",
15
- "default": "./dist/src/create-permissions-hook.js"
15
+ "types": "./react.d.ts",
16
+ "default": "./react.js"
16
17
  }
17
18
  },
18
19
  "files": [
19
- "dist",
20
+ "index.js",
21
+ "index.d.ts",
22
+ "react.js",
23
+ "react.d.ts",
20
24
  "README.md",
21
25
  "LICENSE"
22
26
  ],
@@ -24,12 +28,6 @@
24
28
  "engines": {
25
29
  "node": ">=20"
26
30
  },
27
- "scripts": {
28
- "build": "tsc -p tsconfig.json",
29
- "prepare": "npm run build",
30
- "typecheck": "tsc --noEmit",
31
- "test": "npm run build && node --test ./dist/test/**/*.test.js"
32
- },
33
31
  "keywords": [
34
32
  "rbac",
35
33
  "permissions",
@@ -42,9 +40,13 @@
42
40
  "license": "MIT",
43
41
  "repository": {
44
42
  "type": "git",
45
- "url": "https://github.com/wovalle/willy.im",
43
+ "url": "git+https://github.com/wovalle/willy.im.git",
46
44
  "directory": "packages/rbac"
47
45
  },
46
+ "dependencies": {
47
+ "@willyim/kit": "^0.1.0",
48
+ "zod": "^4.1.11"
49
+ },
48
50
  "peerDependencies": {
49
51
  "react": ">=18"
50
52
  },
@@ -53,10 +55,6 @@
53
55
  "optional": true
54
56
  }
55
57
  },
56
- "devDependencies": {
57
- "@types/node": "^22.19.7",
58
- "typescript": "^5.9.3"
59
- },
60
58
  "publishConfig": {
61
59
  "access": "public"
62
60
  }
package/react.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** @deprecated `@willyim/rbac/react` is `@willyim/kit/react` now. */
2
+ export {
3
+ createPermissionsHook,
4
+ type PermissionsData,
5
+ type UsePermissionsReturn,
6
+ } from "@willyim/kit/react"
package/react.js ADDED
@@ -0,0 +1,2 @@
1
+ /** @deprecated `@willyim/rbac/react` is `@willyim/kit/react` now. */
2
+ export { createPermissionsHook } from "@willyim/kit/react"
@@ -1,11 +0,0 @@
1
- export type UsePermissionsReturn<P extends string> = {
2
- has(permission: P): boolean;
3
- granted: P[];
4
- isSuperadmin: boolean;
5
- };
6
- export type PermissionsData<P extends string> = {
7
- granted: P[];
8
- isSuperadmin?: boolean;
9
- };
10
- export declare function createPermissionsHook<P extends string>(useData: () => PermissionsData<P>): () => UsePermissionsReturn<P>;
11
- //# sourceMappingURL=create-permissions-hook.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"create-permissions-hook.d.ts","sourceRoot":"","sources":["../../src/create-permissions-hook.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,CAAC,CAAC,SAAS,MAAM,IAAI;IACnD,GAAG,CAAC,UAAU,EAAE,CAAC,GAAG,OAAO,CAAA;IAC3B,OAAO,EAAE,CAAC,EAAE,CAAA;IACZ,YAAY,EAAE,OAAO,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IAAI;IAC9C,OAAO,EAAE,CAAC,EAAE,CAAA;IACZ,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA;AAED,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,EACpD,OAAO,EAAE,MAAM,eAAe,CAAC,CAAC,CAAC,GAChC,MAAM,oBAAoB,CAAC,CAAC,CAAC,CAW/B"}
@@ -1,11 +0,0 @@
1
- export function createPermissionsHook(useData) {
2
- return function usePermissions() {
3
- const { granted, isSuperadmin = false } = useData();
4
- const set = new Set(granted);
5
- return {
6
- has: (permission) => set.has(permission),
7
- granted,
8
- isSuperadmin,
9
- };
10
- };
11
- }
@@ -1,20 +0,0 @@
1
- export type PermissionChecker<P extends string> = {
2
- has(permission: P): boolean;
3
- require(permission: P): void;
4
- granted: P[];
5
- isSuperadmin: boolean;
6
- };
7
- export type CheckerOptions = {
8
- superadmin?: boolean;
9
- };
10
- export type DefinePermissionsConfig<P extends readonly string[], R extends Record<string, readonly NoInfer<P[number]>[]>> = {
11
- permissions: P;
12
- roles: R;
13
- };
14
- export type PermissionsResult<P extends readonly string[], R extends Record<string, readonly P[number][]>> = {
15
- createChecker(role: keyof R & string, opts?: CheckerOptions): PermissionChecker<P[number]>;
16
- permissions: P;
17
- roles: R;
18
- };
19
- export declare function definePermissions<const P extends readonly string[], const R extends Record<string, readonly NoInfer<P[number]>[]>>(config: DefinePermissionsConfig<P, R>): PermissionsResult<P, R>;
20
- //# sourceMappingURL=define-permissions.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"define-permissions.d.ts","sourceRoot":"","sources":["../../src/define-permissions.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,MAAM,IAAI;IAChD,GAAG,CAAC,UAAU,EAAE,CAAC,GAAG,OAAO,CAAA;IAC3B,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,IAAI,CAAA;IAC5B,OAAO,EAAE,CAAC,EAAE,CAAA;IACZ,YAAY,EAAE,OAAO,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,uBAAuB,CACjC,CAAC,SAAS,SAAS,MAAM,EAAE,EAC3B,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,IACrD;IAAE,WAAW,EAAE,CAAC,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAA;AAEhC,MAAM,MAAM,iBAAiB,CAC3B,CAAC,SAAS,SAAS,MAAM,EAAE,EAC3B,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,IAC5C;IACF,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,cAAc,GAAG,iBAAiB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;IAC1F,WAAW,EAAE,CAAC,CAAA;IACd,KAAK,EAAE,CAAC,CAAA;CACT,CAAA;AAED,wBAAgB,iBAAiB,CAC/B,KAAK,CAAC,CAAC,SAAS,SAAS,MAAM,EAAE,EACjC,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAC7D,MAAM,EAAE,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,CA0BhE"}
@@ -1,22 +0,0 @@
1
- export function definePermissions(config) {
2
- function createChecker(role, opts) {
3
- const superadmin = opts?.superadmin ?? false;
4
- const rolePerms = config.roles[role];
5
- const grantedSet = new Set(rolePerms);
6
- return {
7
- has: (p) => superadmin || grantedSet.has(p),
8
- require: (p) => {
9
- if (!superadmin && !grantedSet.has(p)) {
10
- throw new Response("Forbidden", { status: 403 });
11
- }
12
- },
13
- granted: superadmin ? [...config.permissions] : [...rolePerms],
14
- isSuperadmin: superadmin,
15
- };
16
- }
17
- return {
18
- createChecker,
19
- permissions: config.permissions,
20
- roles: config.roles,
21
- };
22
- }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=define-permissions.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"define-permissions.test.d.ts","sourceRoot":"","sources":["../../test/define-permissions.test.ts"],"names":[],"mappings":""}
@@ -1,127 +0,0 @@
1
- import { describe, it } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { definePermissions } from "../src/define-permissions.js";
4
- const auth = definePermissions({
5
- permissions: [
6
- "posts:read",
7
- "posts:write",
8
- "posts:delete",
9
- "users:read",
10
- "users:manage",
11
- ],
12
- roles: {
13
- admin: ["posts:read", "posts:write", "posts:delete", "users:read", "users:manage"],
14
- editor: ["posts:read", "posts:write", "users:read"],
15
- viewer: ["posts:read", "users:read"],
16
- },
17
- });
18
- describe("definePermissions", () => {
19
- it("exposes the original permissions and roles", () => {
20
- assert.deepEqual(auth.permissions, [
21
- "posts:read",
22
- "posts:write",
23
- "posts:delete",
24
- "users:read",
25
- "users:manage",
26
- ]);
27
- assert.deepEqual(Object.keys(auth.roles), ["admin", "editor", "viewer"]);
28
- });
29
- });
30
- describe("createChecker", () => {
31
- it("has() returns true for granted permissions", () => {
32
- const checker = auth.createChecker("editor");
33
- assert.equal(checker.has("posts:read"), true);
34
- assert.equal(checker.has("posts:write"), true);
35
- assert.equal(checker.has("users:read"), true);
36
- });
37
- it("has() returns false for denied permissions", () => {
38
- const checker = auth.createChecker("editor");
39
- assert.equal(checker.has("posts:delete"), false);
40
- assert.equal(checker.has("users:manage"), false);
41
- });
42
- it("granted contains exactly the role permissions", () => {
43
- const checker = auth.createChecker("viewer");
44
- assert.deepEqual(checker.granted, ["posts:read", "users:read"]);
45
- });
46
- it("admin has all permissions", () => {
47
- const checker = auth.createChecker("admin");
48
- for (const p of auth.permissions) {
49
- assert.equal(checker.has(p), true, `admin should have ${p}`);
50
- }
51
- });
52
- it("require() does not throw for granted permissions", () => {
53
- const checker = auth.createChecker("editor");
54
- assert.doesNotThrow(() => checker.require("posts:read"));
55
- assert.doesNotThrow(() => checker.require("posts:write"));
56
- });
57
- it("require() throws a 403 Response for denied permissions", () => {
58
- const checker = auth.createChecker("viewer");
59
- try {
60
- checker.require("posts:delete");
61
- assert.fail("should have thrown");
62
- }
63
- catch (err) {
64
- assert.ok(err instanceof Response);
65
- assert.equal(err.status, 403);
66
- }
67
- });
68
- it("different roles are isolated from each other", () => {
69
- const admin = auth.createChecker("admin");
70
- const viewer = auth.createChecker("viewer");
71
- assert.equal(admin.has("posts:delete"), true);
72
- assert.equal(viewer.has("posts:delete"), false);
73
- assert.equal(admin.has("users:manage"), true);
74
- assert.equal(viewer.has("users:manage"), false);
75
- });
76
- });
77
- describe("superadmin", () => {
78
- it("has() returns true for all permissions", () => {
79
- const checker = auth.createChecker("viewer", { superadmin: true });
80
- for (const p of auth.permissions) {
81
- assert.equal(checker.has(p), true, `superadmin should have ${p}`);
82
- }
83
- });
84
- it("require() never throws", () => {
85
- const checker = auth.createChecker("viewer", { superadmin: true });
86
- for (const p of auth.permissions) {
87
- assert.doesNotThrow(() => checker.require(p));
88
- }
89
- });
90
- it("granted returns all permissions", () => {
91
- const checker = auth.createChecker("viewer", { superadmin: true });
92
- assert.deepEqual(checker.granted, [...auth.permissions]);
93
- });
94
- it("isSuperadmin is true when flag is set", () => {
95
- const checker = auth.createChecker("viewer", { superadmin: true });
96
- assert.equal(checker.isSuperadmin, true);
97
- });
98
- it("isSuperadmin is false by default", () => {
99
- const checker = auth.createChecker("admin");
100
- assert.equal(checker.isSuperadmin, false);
101
- });
102
- it("isSuperadmin is false when flag is explicitly false", () => {
103
- const checker = auth.createChecker("admin", { superadmin: false });
104
- assert.equal(checker.isSuperadmin, false);
105
- });
106
- });
107
- describe("edge cases", () => {
108
- it("works with a role that has no permissions", () => {
109
- const empty = definePermissions({
110
- permissions: ["a", "b"],
111
- roles: { none: [] },
112
- });
113
- const checker = empty.createChecker("none");
114
- assert.equal(checker.has("a"), false);
115
- assert.equal(checker.has("b"), false);
116
- assert.deepEqual(checker.granted, []);
117
- });
118
- it("works with a single permission and single role", () => {
119
- const minimal = definePermissions({
120
- permissions: ["only"],
121
- roles: { sole: ["only"] },
122
- });
123
- const checker = minimal.createChecker("sole");
124
- assert.equal(checker.has("only"), true);
125
- assert.deepEqual(checker.granted, ["only"]);
126
- });
127
- });