@willyim/rbac 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Willy Ovalle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # @willyim/rbac
2
+
3
+ Typed RBAC where permissions are the primitive and roles are named permission bags.
4
+
5
+ Define your permissions once, get fully typed checkers for your server loaders and a hook factory for your React components.
6
+
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
45
+ ```
46
+
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
+ ### React Router loader example
64
+
65
+ ```ts
66
+ // app/lib/session.ts
67
+ import { auth } from "./permissions"
68
+
69
+ export async function getSessionContext() {
70
+ const role = await getRoleFromSession()
71
+ const permissions = auth.createChecker(role)
72
+ return { permissions, /* ... */ }
73
+ }
74
+
75
+ // app/routes/reports.tsx
76
+ export async function loader({ context }: Route.LoaderArgs) {
77
+ const { permissions } = await context.getSessionContext()
78
+ permissions.require("reports:read")
79
+ return { /* ... */ }
80
+ }
81
+ ```
82
+
83
+ ## Check permissions (React)
84
+
85
+ The `@willyim/rbac/react` entry point exports `createPermissionsHook`, a factory that builds a typed `usePermissions` hook from any data source.
86
+
87
+ ```ts
88
+ // app/hooks/use-permissions.ts
89
+ import { createPermissionsHook } from "@willyim/rbac/react"
90
+ import { useRouteLoaderData } from "react-router"
91
+ import type { Permission } from "../lib/permissions"
92
+
93
+ export const usePermissions = createPermissionsHook<Permission>(() => {
94
+ const data = useRouteLoaderData("routes/_dashboard_layout")
95
+ return data?.permissions ?? []
96
+ })
97
+ ```
98
+
99
+ Then use it in components:
100
+
101
+ ```tsx
102
+ function Nav() {
103
+ const { has } = usePermissions()
104
+
105
+ return (
106
+ <nav>
107
+ <Link to="/">Home</Link>
108
+ {has("reports:read") && <Link to="/reports">Reports</Link>}
109
+ {has("settings:manage") && <Link to="/settings">Settings</Link>}
110
+ </nav>
111
+ )
112
+ }
113
+ ```
114
+
115
+ ## API
116
+
117
+ ### `definePermissions(config)`
118
+
119
+ | Parameter | Type | Description |
120
+ |-----------|------|-------------|
121
+ | `config.permissions` | `readonly string[]` | All permissions in the system (use `as const`) |
122
+ | `config.roles` | `Record<string, readonly Permission[]>` | Each role maps to a subset of permissions |
123
+
124
+ Returns an object with:
125
+
126
+ - `createChecker(role)` — returns a `PermissionChecker` for the given role
127
+ - `permissions` — the original permissions array
128
+ - `roles` — the original roles config
129
+
130
+ ### `PermissionChecker<P>`
131
+
132
+ | Method | Description |
133
+ |--------|-------------|
134
+ | `has(permission)` | Returns `true` if the permission is granted |
135
+ | `require(permission)` | Throws `Response("Forbidden", { status: 403 })` if not granted |
136
+ | `granted` | Array of all granted permissions |
137
+
138
+ ### `createPermissionsHook(useGranted)`
139
+
140
+ | Parameter | Type | Description |
141
+ |-----------|------|-------------|
142
+ | `useGranted` | `() => P[]` | A React hook or function that returns the granted permissions |
143
+
144
+ Returns a `usePermissions` hook with:
145
+
146
+ | Property | Description |
147
+ |----------|-------------|
148
+ | `has(permission)` | Returns `true` if the permission is granted |
149
+ | `granted` | Array of all granted permissions |
150
+
151
+ ## License
152
+
153
+ MIT
@@ -0,0 +1,6 @@
1
+ export type UsePermissionsReturn<P extends string> = {
2
+ has(permission: P): boolean;
3
+ granted: P[];
4
+ };
5
+ export declare function createPermissionsHook<P extends string>(useGranted: () => P[]): () => UsePermissionsReturn<P>;
6
+ //# sourceMappingURL=create-permissions-hook.d.ts.map
@@ -0,0 +1 @@
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;CACb,CAAA;AAED,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,EACpD,UAAU,EAAE,MAAM,CAAC,EAAE,GACpB,MAAM,oBAAoB,CAAC,CAAC,CAAC,CAU/B"}
@@ -0,0 +1,10 @@
1
+ export function createPermissionsHook(useGranted) {
2
+ return function usePermissions() {
3
+ const granted = useGranted();
4
+ const set = new Set(granted);
5
+ return {
6
+ has: (permission) => set.has(permission),
7
+ granted,
8
+ };
9
+ };
10
+ }
@@ -0,0 +1,16 @@
1
+ export type PermissionChecker<P extends string> = {
2
+ has(permission: P): boolean;
3
+ require(permission: P): void;
4
+ granted: P[];
5
+ };
6
+ export type DefinePermissionsConfig<P extends readonly string[], R extends Record<string, readonly NoInfer<P[number]>[]>> = {
7
+ permissions: P;
8
+ roles: R;
9
+ };
10
+ export type PermissionsResult<P extends readonly string[], R extends Record<string, readonly P[number][]>> = {
11
+ createChecker(role: keyof R & string): PermissionChecker<P[number]>;
12
+ permissions: P;
13
+ roles: R;
14
+ };
15
+ 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>;
16
+ //# sourceMappingURL=define-permissions.d.ts.map
@@ -0,0 +1 @@
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;CACb,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,GAAG,iBAAiB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;IACnE,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,CAwBhE"}
@@ -0,0 +1,20 @@
1
+ export function definePermissions(config) {
2
+ function createChecker(role) {
3
+ const rolePerms = config.roles[role];
4
+ const grantedSet = new Set(rolePerms);
5
+ return {
6
+ has: (p) => grantedSet.has(p),
7
+ require: (p) => {
8
+ if (!grantedSet.has(p)) {
9
+ throw new Response("Forbidden", { status: 403 });
10
+ }
11
+ },
12
+ granted: [...rolePerms],
13
+ };
14
+ }
15
+ return {
16
+ createChecker,
17
+ permissions: config.permissions,
18
+ roles: config.roles,
19
+ };
20
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=define-permissions.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-permissions.test.d.ts","sourceRoot":"","sources":["../../test/define-permissions.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,97 @@
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("edge cases", () => {
78
+ it("works with a role that has no permissions", () => {
79
+ const empty = definePermissions({
80
+ permissions: ["a", "b"],
81
+ roles: { none: [] },
82
+ });
83
+ const checker = empty.createChecker("none");
84
+ assert.equal(checker.has("a"), false);
85
+ assert.equal(checker.has("b"), false);
86
+ assert.deepEqual(checker.granted, []);
87
+ });
88
+ it("works with a single permission and single role", () => {
89
+ const minimal = definePermissions({
90
+ permissions: ["only"],
91
+ roles: { sole: ["only"] },
92
+ });
93
+ const checker = minimal.createChecker("sole");
94
+ assert.equal(checker.has("only"), true);
95
+ assert.deepEqual(checker.granted, ["only"]);
96
+ });
97
+ });
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@willyim/rbac",
3
+ "version": "0.1.0",
4
+ "description": "Typed RBAC where permissions are the primitive and roles are named permission bags",
5
+ "type": "module",
6
+ "main": "./dist/src/define-permissions.js",
7
+ "types": "./dist/src/define-permissions.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/src/define-permissions.d.ts",
11
+ "default": "./dist/src/define-permissions.js"
12
+ },
13
+ "./react": {
14
+ "types": "./dist/src/create-permissions-hook.d.ts",
15
+ "default": "./dist/src/create-permissions-hook.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "npm run build && node --test ./dist/test/**/*.test.js"
31
+ },
32
+ "keywords": [
33
+ "rbac",
34
+ "permissions",
35
+ "roles",
36
+ "authorization",
37
+ "typed",
38
+ "react",
39
+ "react-router"
40
+ ],
41
+ "license": "MIT",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/wovalle/willy.im",
45
+ "directory": "packages/rbac"
46
+ },
47
+ "peerDependencies": {
48
+ "react": ">=18"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "react": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.19.7",
57
+ "typescript": "^5.9.3"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }