@dudousxd/nestjs-authz-drizzle 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/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # @dudousxd/nestjs-authz-drizzle
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#55](https://github.com/DavideCarvalho/nestjs-authz/pull/55) [`7b040d8`](https://github.com/DavideCarvalho/nestjs-authz/commit/7b040d8bf187d630726b16031ff7c6fa14d95f5b) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - New package: `@dudousxd/nestjs-authz-drizzle` — the Drizzle ORM (Postgres) sibling of the typeorm/mikro-orm/prisma adapters.
8
+
9
+ - `compileScope(constraint, tableOrColumns)` / `applyScope(gate, Entity, table)` compile `gate.scope()` into a Drizzle `SQL` WHERE (fields resolved against the table's columns or an explicit allowlist map; values always bound; `allow-all` → `undefined`, `deny-all` → `1 = 0`).
10
+ - `DrizzleAuthzStore` — the same store surface as the TypeORM adapter (idempotent role/permission upserts, tenant-scoped role assignments, direct user permissions, `getUserAuthz`), over the canonical `authz_*` tables, plus `withDb(tx)` for caller transactions.
11
+ - `createAuthzTables({ tableNames, schema })` returns the tables as `pgTable`s to spread into your drizzle-kit schema; `ensureSchema()` / `authzSchemaDdl()` for non-drizzle-kit setups.
12
+ - `AuthzRbacModule` registers the `PERMISSION_PROVIDER` (with wildcard `getPermissions`) and `ROLE_PROVIDER` seams, tenant-aware via nestjs-context.
13
+
14
+ - [#58](https://github.com/DavideCarvalho/nestjs-authz/pull/58) [`8b65088`](https://github.com/DavideCarvalho/nestjs-authz/commit/8b6508804216d46384ec3a734a55b9c0ac1e48b6) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Per-source role assignments (manual vs SSO/SCIM/…).
15
+
16
+ Each role assignment now records a `source`, default `'manual'`. Every store adapter gains:
17
+
18
+ - `setUserRoles(user, roleNames, { source?, tenantId? })` replaces only that source's assignments, so an SSO sync never removes a role that was granted by hand. It creates missing roles and runs in a transaction.
19
+ - `assignRole(user, role, { source })` and `removeRole(user, role, { source })`. Without `source`, `removeRole` removes the role from every source.
20
+ - `getRoleAssignments(user, scope?)` returns `{ role, source, tenantId }[]`.
21
+ - `getRolesForUser` and the Gate seams still return distinct role names.
22
+
23
+ Core's `store-kit` exports `DEFAULT_ROLE_SOURCE` and `RoleAssignment`. The adapters now require `@dudousxd/nestjs-authz >= 0.7.0`.
24
+
25
+ **Migration**
26
+
27
+ - **TypeORM:** `ensureAuthzSchema` / `autoCreateSchema` adds `source varchar(64) NOT NULL DEFAULT 'manual'` to `authz_user_role`, so existing rows become manual assignments. It never rewrites an existing primary key. Until you widen the key, a role can come from only one source per user, and a second-source insert is silently ignored. Widen it once:
28
+
29
+ - PostgreSQL: `ALTER TABLE authz_user_role DROP CONSTRAINT <pk_name>, ADD PRIMARY KEY ("userType","userId","roleId","tenantId","source");`
30
+ - MySQL (utf8mb4 needs the shorter key columns): `ALTER TABLE authz_user_role MODIFY roleId varchar(64) NOT NULL, MODIFY source varchar(64) NOT NULL DEFAULT 'manual', DROP PRIMARY KEY, ADD PRIMARY KEY (userType, userId, roleId, tenantId, source);`
31
+ - SQLite: rebuild the table.
32
+
33
+ New tables are created with the 5-column key, and `roleId` is now `varchar(64)` so the key fits MySQL's 3072-byte limit.
34
+
35
+ - **MikroORM:** the column self-heals the same way. The PK does not. See the adapter README for the SQL.
36
+ - **Prisma:** opt-in with `roleSources: true` after adding `source String @default("manual")` to `UserRole` and including it in `@@id`. See the adapter README. Without the option the adapter behaves exactly as before.
37
+ - **Drizzle:** `createAuthzTables()` now includes the column and the widened key, so regenerate with drizzle-kit. `ensureSchema()` adds the column. See the README for the key SQL.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Davi Carvalho
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,173 @@
1
+ # @dudousxd/nestjs-authz-drizzle
2
+
3
+ [Drizzle ORM](https://orm.drizzle.team) adapter for
4
+ [`@dudousxd/nestjs-authz`](https://github.com/DavideCarvalho/nestjs-authz) (Postgres):
5
+
6
+ - **Query scopes** — compile `gate.scope(Entity)` into a Drizzle `WHERE` (`compileScope` /
7
+ `applyScope`), so list endpoints filter at the database instead of over-fetching.
8
+ - **RBAC persistence** — roles, permissions, tenant-scoped role assignments and direct user
9
+ permissions, plus the `AuthzRbacModule` Gate seam. Your app owns the Drizzle database; this
10
+ package never opens a connection.
11
+
12
+ It's the Drizzle version of `@dudousxd/nestjs-authz-typeorm`. The store surface and
13
+ `AuthzRbacModule` are the same, and so are the physical tables and columns, so switching
14
+ between adapters leaves your data where it is.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pnpm add @dudousxd/nestjs-authz-drizzle @dudousxd/nestjs-authz drizzle-orm
20
+ ```
21
+
22
+ `drizzle-orm` is a peer (`>=0.40.0 <1.0.0`). Any Drizzle Postgres driver works:
23
+ `node-postgres`, `postgres-js`, PGlite, Neon, and so on.
24
+
25
+ ## Query scopes
26
+
27
+ Write a policy `scope` with the ORM-neutral builders from the core:
28
+
29
+ ```ts
30
+ import { Policy, eq, or, type ScopeConstraint } from '@dudousxd/nestjs-authz';
31
+
32
+ @Policy(Post)
33
+ export class PostPolicy {
34
+ scope(user: User): ScopeConstraint {
35
+ return or(eq('authorId', user.id), eq('published', true));
36
+ }
37
+ }
38
+ ```
39
+
40
+ Then compile it against your Drizzle table:
41
+
42
+ ```ts
43
+ import { applyScope, compileScope } from '@dudousxd/nestjs-authz-drizzle';
44
+ import { and, eq } from 'drizzle-orm';
45
+ import { posts } from './db/schema';
46
+
47
+ const scope = await applyScope(gate, Post, posts); // = compileScope(await gate.scope(Post), posts)
48
+ const rows = await db.select().from(posts).where(and(scope, eq(posts.archived, false)));
49
+ ```
50
+
51
+ - A scope `field` resolves to the table's **property key** (`authorId`) first, then to the
52
+ physical column name (`author_id`). A field that matches neither throws, so it never reaches
53
+ the SQL.
54
+ - To allowlist columns explicitly, or to scope over a JOIN, pass a column map instead of a
55
+ table: `compileScope(constraint, { authorId: posts.authorId, orgId: orgs.id })`.
56
+ - `allow-all` (super-admin, `before` grant, permission-provider grant) returns `undefined`.
57
+ Both `.where()` and `and()` ignore it, so no predicate is added. `deny-all` becomes `1 = 0`.
58
+ - Values always go through Drizzle's operators. They're bound as parameters and mapped by the
59
+ column (for example, a `Date` becomes a timestamp).
60
+
61
+ ## RBAC store
62
+
63
+ ```ts
64
+ import { AuthzRbacModule, DrizzleAuthzStore } from '@dudousxd/nestjs-authz-drizzle';
65
+
66
+ @Module({
67
+ imports: [
68
+ AuthzRbacModule.forRootAsync({
69
+ inject: [DB], // your Drizzle database token
70
+ useFactory: (db: Db) => ({ store: new DrizzleAuthzStore(db) }),
71
+ }),
72
+ ],
73
+ })
74
+ export class AppModule {}
75
+ ```
76
+
77
+ ```ts
78
+ await store.givePermissionToRole('editor', 'posts.publish');
79
+ await store.assignRole({ type: 'user', id: 7 }, 'editor'); // global
80
+ await store.assignRole({ type: 'user', id: 7 }, 'admin', { tenantId: 'acme' }); // tenant-scoped
81
+ await store.giveUserPermission(7, 'reports.export'); // direct grant
82
+
83
+ gate.forUser(user).allows('posts.publish'); // true (PERMISSION_PROVIDER seam, wildcards supported)
84
+ gate.forUser(user).hasRole('editor'); // true (ROLE_PROVIDER seam)
85
+ ```
86
+
87
+ With `@dudousxd/nestjs-context` installed, the module reads the current tenant from the context
88
+ accessor. A tenant-scoped role then grants only inside its own tenant. Global roles and direct
89
+ grants apply everywhere.
90
+
91
+ To run the store inside your own transaction, use `store.withDb(tx)`.
92
+
93
+ ## Schema
94
+
95
+ The five tables are plain Drizzle `pgTable`s built by `createAuthzTables`. Re-export them from
96
+ the schema file that `drizzle.config.ts` points at, and drizzle-kit will generate the migration:
97
+
98
+ ```ts
99
+ // db/schema.ts
100
+ import { createAuthzTables } from '@dudousxd/nestjs-authz-drizzle';
101
+
102
+ export const authz = createAuthzTables(); // or { tableNames: { roles: 'app_roles' }, schema: 'rbac' }
103
+ export const {
104
+ roles: authzRoles,
105
+ permissions: authzPermissions,
106
+ rolePermission: authzRolePermission,
107
+ userRole: authzUserRole,
108
+ userPermission: authzUserPermission,
109
+ } = authz;
110
+ ```
111
+
112
+ Give the store the **same** object with `new DrizzleAuthzStore(db, { tables: authz })`. The
113
+ queries and the migration then come from one definition and can't drift apart.
114
+
115
+ If you don't use drizzle-kit, set `autoCreateSchema: true` on the module, or call
116
+ `store.ensureSchema()` yourself. Both run `CREATE TABLE/INDEX IF NOT EXISTS` and never alter or
117
+ drop anything. `authzSchemaDdl(tables)` gives you the same DDL as strings for a hand-written
118
+ migration. `autoCreateSchema` defaults to `false`, because with Drizzle the schema usually
119
+ belongs to drizzle-kit.
120
+
121
+ | Table (default name) | Columns |
122
+ | ----------------------- | ------------------------------------------------------------ |
123
+ | `authz_roles` | `id`, `name` (unique), `guard`, `createdAt` |
124
+ | `authz_permissions` | `id`, `name` (unique), `guard`, `createdAt` |
125
+ | `authz_role_permission` | `roleId`, `permissionId` (PK) |
126
+ | `authz_user_role` | `userType`, `userId`, `roleId`, `tenantId` (`''` = global) (PK) |
127
+ | `authz_user_permission` | `userType`, `userId`, `permissionId` (PK) |
128
+
129
+ Users are referenced **by id only**. This package never owns a users table.
130
+
131
+ ## Role sources (manual vs SSO/SCIM)
132
+
133
+ Every role assignment records a `source`. It defaults to `'manual'`, so existing calls and existing
134
+ rows keep their meaning. A sync replaces only its own source:
135
+
136
+ ```ts
137
+ // On each SSO login: exactly these roles come from SSO. Manual grants are untouched.
138
+ await store.setUserRoles(user, rolesFromIdpGroups, { source: 'sso', tenantId: 'acme' });
139
+
140
+ await store.assignRole(user, 'editor'); // source 'manual'
141
+ await store.assignRole(user, 'editor', { source: 'scim' }); // a second assignment of the same role
142
+ await store.removeRole(user, 'editor', { source: 'scim' }); // still an editor (manual)
143
+ await store.removeRole(user, 'editor'); // no source: removed from every source
144
+ await store.getRoleAssignments(user); // [{ role, source, tenantId }]
145
+ ```
146
+
147
+ `getRolesForUser` and the Gate seams see the distinct role names from all sources.
148
+
149
+ ### Migrating an existing database
150
+
151
+ `authz_user_role` gains a `"source"` column (`NOT NULL DEFAULT 'manual'`), and the primary key
152
+ becomes `("userType","userId","roleId","tenantId","source")`.
153
+
154
+ - **drizzle-kit:** regenerate the migration from `createAuthzTables()`.
155
+ - **`ensureSchema()`:** it adds the column (`ADD COLUMN IF NOT EXISTS`, so existing rows become
156
+ manual assignments) but doesn't touch the key. Widen the key once, so that one role can come
157
+ from two sources:
158
+
159
+ ```sql
160
+ ALTER TABLE "authz_user_role"
161
+ DROP CONSTRAINT "authz_user_role_pkey",
162
+ ADD CONSTRAINT "authz_user_role_pkey" PRIMARY KEY ("userType","userId","roleId","tenantId","source");
163
+ ```
164
+
165
+ ## Testing
166
+
167
+ `pnpm test` runs every spec against an in-process Postgres (PGlite), so it needs no Docker.
168
+ `pnpm test:db:pg` runs the integration specs against a real Postgres container. If
169
+ `AUTHZ_TEST_PG_HOST`/`AUTHZ_TEST_PG_PORT` are already set, it uses that server instead.
170
+
171
+ ## License
172
+
173
+ MIT
@@ -0,0 +1,47 @@
1
+ import type { UserRef } from '@dudousxd/nestjs-authz/store-kit';
2
+ import { type DynamicModule } from '@nestjs/common';
3
+ import type { DrizzleAuthzStore } from './drizzle-authz.store.js';
4
+ /** Injection token holding the {@link DrizzleAuthzStore} the RBAC module manages. */
5
+ export declare const AUTHZ_RBAC_STORE: unique symbol;
6
+ /** Injection token holding the resolved {@link AuthzRbacModuleOptions}. */
7
+ export declare const AUTHZ_RBAC_OPTIONS: unique symbol;
8
+ /**
9
+ * Map the Gate's current user (whatever the app's auth layer produced) to a
10
+ * {@link UserRef} the store can key on. Defaults to reading `{ type, id }` / `{ id }`.
11
+ */
12
+ export type UserRefMapper = (user: unknown) => UserRef | undefined;
13
+ export interface AuthzRbacModuleOptions {
14
+ /** The Drizzle RBAC store (built with the app-provided Drizzle database). */
15
+ store: DrizzleAuthzStore;
16
+ /**
17
+ * Run the store's `ensureSchema` (`CREATE ... IF NOT EXISTS`, non-destructive) on bootstrap.
18
+ * Default `false`: with Drizzle the schema is normally owned by drizzle-kit — spread the
19
+ * `createAuthzTables()` result into your schema and let it generate the migration.
20
+ */
21
+ autoCreateSchema?: boolean;
22
+ /**
23
+ * Derive a {@link UserRef} from the Gate's current user. Defaults to
24
+ * {@link defaultUserRefMapper} (`{ type, id }` or `{ id }`).
25
+ */
26
+ userRefFrom?: UserRefMapper;
27
+ }
28
+ export interface AuthzRbacModuleAsyncOptions {
29
+ imports?: unknown[];
30
+ inject?: unknown[];
31
+ useFactory: (...args: unknown[]) => Promise<AuthzRbacModuleOptions> | AuthzRbacModuleOptions;
32
+ }
33
+ /** Default mapping: accept a `{ type, id }` ref, a `{ id }` object, or a bare id. */
34
+ export declare function defaultUserRefMapper(user: unknown): UserRef | undefined;
35
+ /**
36
+ * Wires persisted RBAC into the core authz Gate. The app provides the Drizzle `db`
37
+ * (via `inject`/`useFactory`) and constructs the {@link DrizzleAuthzStore} — this module
38
+ * NEVER hardcodes a connection token. On init it registers the RBAC permission check into
39
+ * the Gate via the {@link PERMISSION_PROVIDER} seam, so `gate.allows('some.permission')`
40
+ * consults persisted permissions, and (with `autoCreateSchema: true`) ensures the schema exists.
41
+ */
42
+ export declare class AuthzRbacModule {
43
+ static forRoot(options: AuthzRbacModuleOptions): DynamicModule;
44
+ static forRootAsync(options: AuthzRbacModuleAsyncOptions): DynamicModule;
45
+ private static commonProviders;
46
+ }
47
+ //# sourceMappingURL=authz-rbac.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authz-rbac.module.d.ts","sourceRoot":"","sources":["../src/authz-rbac.module.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EACL,KAAK,aAAa,EAQnB,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,qFAAqF;AACrF,eAAO,MAAM,gBAAgB,eAAqD,CAAC;AACnF,2EAA2E;AAC3E,eAAO,MAAM,kBAAkB,eAAuD,CAAC;AAEvF;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,GAAG,SAAS,CAAC;AAEnE,MAAM,WAAW,sBAAsB;IACrC,6EAA6E;IAC7E,KAAK,EAAE,iBAAiB,CAAC;IACzB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;OAGG;IACH,WAAW,CAAC,EAAE,aAAa,CAAC;CAC7B;AAED,MAAM,WAAW,2BAA2B;IAC1C,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;IACnB,UAAU,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,sBAAsB,CAAC,GAAG,sBAAsB,CAAC;CAC9F;AAgDD,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,SAAS,CAOvE;AA+FD;;;;;;GAMG;AACH,qBACa,eAAe;IAC1B,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,sBAAsB,GAAG,aAAa;IAa9D,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,aAAa;IAsBxE,OAAO,CAAC,MAAM,CAAC,eAAe;CAS/B"}
@@ -0,0 +1,236 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var AuthzRbacModule_1;
14
+ import { CONTEXT_ACCESSOR, PERMISSION_PROVIDER, ROLE_PROVIDER, } from '@dudousxd/nestjs-authz';
15
+ import { Inject, Injectable, Module, Optional, } from '@nestjs/common';
16
+ import { ModuleRef } from '@nestjs/core';
17
+ /** Injection token holding the {@link DrizzleAuthzStore} the RBAC module manages. */
18
+ export const AUTHZ_RBAC_STORE = Symbol.for('@dudousxd/nestjs-authz-drizzle:store');
19
+ /** Injection token holding the resolved {@link AuthzRbacModuleOptions}. */
20
+ export const AUTHZ_RBAC_OPTIONS = Symbol.for('@dudousxd/nestjs-authz-drizzle:options');
21
+ /** Read the current tenant from the (optional) context accessor, defensively. */
22
+ function tenantScopeFrom(context) {
23
+ if (!context || typeof context.tenantId !== 'function')
24
+ return {};
25
+ let tenantId;
26
+ try {
27
+ tenantId = context.tenantId();
28
+ }
29
+ catch {
30
+ tenantId = undefined;
31
+ }
32
+ return tenantId == null ? {} : { tenantId };
33
+ }
34
+ /**
35
+ * Locate the context accessor for tenant scoping. Prefers a value injected into
36
+ * this module; falls back to a non-strict {@link ModuleRef} lookup so an accessor
37
+ * provided by ANY module (the app root, a global ContextModule) is still found —
38
+ * the RBAC module is global and its providers don't import the app's modules, so a
39
+ * plain `@Inject` would miss a root-provided accessor. Mirrors the Gate's seam.
40
+ */
41
+ function resolveTenantContext(injected, moduleRef, cache) {
42
+ if (injected)
43
+ return injected;
44
+ if (cache.resolved)
45
+ return cache.value;
46
+ cache.resolved = true;
47
+ if (moduleRef) {
48
+ try {
49
+ cache.value = moduleRef.get(CONTEXT_ACCESSOR, { strict: false });
50
+ }
51
+ catch {
52
+ cache.value = undefined;
53
+ }
54
+ }
55
+ return cache.value;
56
+ }
57
+ /** Default mapping: accept a `{ type, id }` ref, a `{ id }` object, or a bare id. */
58
+ export function defaultUserRefMapper(user) {
59
+ if (user == null)
60
+ return undefined;
61
+ if (typeof user === 'string' || typeof user === 'number')
62
+ return user;
63
+ const u = user;
64
+ if (u.id == null)
65
+ return undefined;
66
+ const id = u.id;
67
+ return typeof u.type === 'string' ? { type: u.type, id } : { id };
68
+ }
69
+ /**
70
+ * The RBAC {@link PermissionProvider} the Gate consults (via the shared
71
+ * {@link PERMISSION_PROVIDER} token). Grants a named ability when the current user holds
72
+ * the matching persisted permission — the Laravel/spatie `Gate::before` grant.
73
+ */
74
+ let RbacPermissionProvider = class RbacPermissionProvider {
75
+ options;
76
+ context;
77
+ moduleRef;
78
+ contextCache = {
79
+ resolved: false,
80
+ value: undefined,
81
+ };
82
+ constructor(options, context, moduleRef) {
83
+ this.options = options;
84
+ this.context = context;
85
+ this.moduleRef = moduleRef;
86
+ }
87
+ scope() {
88
+ return tenantScopeFrom(resolveTenantContext(this.context, this.moduleRef, this.contextCache));
89
+ }
90
+ // The core `PermissionProvider` interface passes an optional `resource` (3rd
91
+ // arg); it is intentionally ignored here. RBAC grants are model-less,
92
+ // named-ability grants (the Laravel/spatie `Gate::before` grant), so the
93
+ // verdict never depends on a specific resource instance. Permissions are scoped
94
+ // by the current tenant (from nestjs-context, when present) — a tenant-scoped
95
+ // role only grants within its tenant; direct user grants always apply.
96
+ async hasPermission(user, permission) {
97
+ const map = this.options.userRefFrom ?? defaultUserRefMapper;
98
+ const ref = map(user);
99
+ if (ref === undefined)
100
+ return undefined;
101
+ return this.options.store.userHasPermission(ref, permission, this.scope());
102
+ }
103
+ // Expose the user's full granted permission set so the core can apply
104
+ // Laravel/spatie-style wildcard matching (a granted `posts.*` satisfies a check
105
+ // for `posts.update`, `*` satisfies anything). The matching itself lives in core,
106
+ // so every adapter that lists grants gets wildcard semantics for free.
107
+ async getPermissions(user) {
108
+ const map = this.options.userRefFrom ?? defaultUserRefMapper;
109
+ const ref = map(user);
110
+ if (ref === undefined)
111
+ return undefined;
112
+ return this.options.store.getPermissionsForUser(ref, this.scope());
113
+ }
114
+ };
115
+ RbacPermissionProvider = __decorate([
116
+ Injectable(),
117
+ __param(0, Inject(AUTHZ_RBAC_OPTIONS)),
118
+ __param(1, Optional()),
119
+ __param(1, Inject(CONTEXT_ACCESSOR)),
120
+ __param(2, Optional()),
121
+ __metadata("design:paramtypes", [Object, Object, ModuleRef])
122
+ ], RbacPermissionProvider);
123
+ /**
124
+ * The RBAC {@link RoleProvider} the Gate consults (via the shared {@link ROLE_PROVIDER}
125
+ * token) for coarse role-checks (`gate.hasRole('teacher')`, `@Roles('admin')`). Returns
126
+ * the role names the current user holds in the persisted store. Core unions these with
127
+ * any roles read off the user object by the default `RoleResolver`.
128
+ */
129
+ let RbacRoleProvider = class RbacRoleProvider {
130
+ options;
131
+ context;
132
+ moduleRef;
133
+ contextCache = {
134
+ resolved: false,
135
+ value: undefined,
136
+ };
137
+ constructor(options, context, moduleRef) {
138
+ this.options = options;
139
+ this.context = context;
140
+ this.moduleRef = moduleRef;
141
+ }
142
+ async getRoles(user) {
143
+ const map = this.options.userRefFrom ?? defaultUserRefMapper;
144
+ const ref = map(user);
145
+ if (ref === undefined)
146
+ return undefined;
147
+ // Scope roles by the current tenant (when nestjs-context is present): a
148
+ // tenant-scoped role only counts within its tenant; global roles always count.
149
+ const scope = tenantScopeFrom(resolveTenantContext(this.context, this.moduleRef, this.contextCache));
150
+ return this.options.store.getRolesForUser(ref, scope);
151
+ }
152
+ };
153
+ RbacRoleProvider = __decorate([
154
+ Injectable(),
155
+ __param(0, Inject(AUTHZ_RBAC_OPTIONS)),
156
+ __param(1, Optional()),
157
+ __param(1, Inject(CONTEXT_ACCESSOR)),
158
+ __param(2, Optional()),
159
+ __metadata("design:paramtypes", [Object, Object, ModuleRef])
160
+ ], RbacRoleProvider);
161
+ /** Runs the store's `ensureSchema` on bootstrap when `autoCreateSchema` is enabled. */
162
+ let AuthzRbacBootstrap = class AuthzRbacBootstrap {
163
+ options;
164
+ constructor(options) {
165
+ this.options = options;
166
+ }
167
+ async onModuleInit() {
168
+ if (!this.options)
169
+ return;
170
+ if (this.options.autoCreateSchema !== true)
171
+ return;
172
+ await this.options.store.ensureSchema();
173
+ }
174
+ };
175
+ AuthzRbacBootstrap = __decorate([
176
+ Injectable(),
177
+ __param(0, Optional()),
178
+ __param(0, Inject(AUTHZ_RBAC_OPTIONS)),
179
+ __metadata("design:paramtypes", [Object])
180
+ ], AuthzRbacBootstrap);
181
+ /**
182
+ * Wires persisted RBAC into the core authz Gate. The app provides the Drizzle `db`
183
+ * (via `inject`/`useFactory`) and constructs the {@link DrizzleAuthzStore} — this module
184
+ * NEVER hardcodes a connection token. On init it registers the RBAC permission check into
185
+ * the Gate via the {@link PERMISSION_PROVIDER} seam, so `gate.allows('some.permission')`
186
+ * consults persisted permissions, and (with `autoCreateSchema: true`) ensures the schema exists.
187
+ */
188
+ let AuthzRbacModule = AuthzRbacModule_1 = class AuthzRbacModule {
189
+ static forRoot(options) {
190
+ return {
191
+ module: AuthzRbacModule_1,
192
+ global: true,
193
+ providers: [
194
+ { provide: AUTHZ_RBAC_OPTIONS, useValue: options },
195
+ { provide: AUTHZ_RBAC_STORE, useValue: options.store },
196
+ ...AuthzRbacModule_1.commonProviders(),
197
+ ],
198
+ exports: [AUTHZ_RBAC_STORE, PERMISSION_PROVIDER, ROLE_PROVIDER],
199
+ };
200
+ }
201
+ static forRootAsync(options) {
202
+ return {
203
+ module: AuthzRbacModule_1,
204
+ global: true,
205
+ imports: (options.imports ?? []),
206
+ providers: [
207
+ {
208
+ provide: AUTHZ_RBAC_OPTIONS,
209
+ useFactory: options.useFactory,
210
+ inject: (options.inject ?? []),
211
+ },
212
+ {
213
+ provide: AUTHZ_RBAC_STORE,
214
+ useFactory: (opts) => opts.store,
215
+ inject: [AUTHZ_RBAC_OPTIONS],
216
+ },
217
+ ...AuthzRbacModule_1.commonProviders(),
218
+ ],
219
+ exports: [AUTHZ_RBAC_STORE, PERMISSION_PROVIDER, ROLE_PROVIDER],
220
+ };
221
+ }
222
+ static commonProviders() {
223
+ return [
224
+ RbacPermissionProvider,
225
+ { provide: PERMISSION_PROVIDER, useExisting: RbacPermissionProvider },
226
+ RbacRoleProvider,
227
+ { provide: ROLE_PROVIDER, useExisting: RbacRoleProvider },
228
+ AuthzRbacBootstrap,
229
+ ];
230
+ }
231
+ };
232
+ AuthzRbacModule = AuthzRbacModule_1 = __decorate([
233
+ Module({})
234
+ ], AuthzRbacModule);
235
+ export { AuthzRbacModule };
236
+ //# sourceMappingURL=authz-rbac.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authz-rbac.module.js","sourceRoot":"","sources":["../src/authz-rbac.module.ts"],"names":[],"mappings":";;;;;;;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,EAAE,WAAW,EAAE,gBAAgB,EAAE;YACzD,kBAAkB;SACnB,CAAC;IACJ,CAAC;CACF,CAAA;AA7CY,eAAe;IAD3B,MAAM,CAAC,EAAE,CAAC;GACE,eAAe,CA6C3B"}
@@ -0,0 +1,99 @@
1
+ import { type RoleAssignment, type UserAuthz, type UserRef } from '@dudousxd/nestjs-authz/store-kit';
2
+ import { type AuthzTables } from './schema.js';
3
+ import type { AuthzStoreOptions, DrizzlePgDatabase, RoleAssignmentScope, TenantScope } from './types.js';
4
+ export type { RoleAssignment, UserAuthz };
5
+ /**
6
+ * Drizzle-backed RBAC store (Postgres). A plain POJO that receives the app's Drizzle database in
7
+ * its constructor — NOT `@Injectable`, no internal connection token (the app owns the connection
8
+ * and plugs it via DI; see the persistence contract). Same method surface as the TypeORM adapter:
9
+ * idempotent role/permission upserts, tenant-scoped role assignments, direct user permissions.
10
+ *
11
+ * Every statement goes through the Drizzle query builder, so values are always bound and the
12
+ * table identifiers come from the (validated) Drizzle table config. Pass a transaction (`tx`) as
13
+ * `db` to run the store inside the caller's unit of work.
14
+ */
15
+ export declare class DrizzleAuthzStore {
16
+ private readonly db;
17
+ /** The Drizzle tables this store reads/writes (spread them into your drizzle-kit schema). */
18
+ readonly tables: AuthzTables;
19
+ constructor(db: DrizzlePgDatabase, opts?: AuthzStoreOptions);
20
+ /** A store bound to another database/transaction, sharing this store's tables. */
21
+ withDb(db: DrizzlePgDatabase): DrizzleAuthzStore;
22
+ /**
23
+ * Create the RBAC tables if they don't exist (`CREATE ... IF NOT EXISTS`, never destructive).
24
+ * Skip this when drizzle-kit owns your migrations — spread {@link AuthzStoreOptions.tables}
25
+ * into your schema instead.
26
+ */
27
+ ensureSchema(): Promise<void>;
28
+ /**
29
+ * Create the role if absent; returns its id. Idempotent and race-tolerant: the INSERT is
30
+ * `ON CONFLICT DO NOTHING` on the unique `name`, and the id is re-read afterwards so two
31
+ * concurrent creators converge on the same row.
32
+ */
33
+ createRole(name: string): Promise<string>;
34
+ /** Create the permission if absent; returns its id. Idempotent and race-tolerant. */
35
+ createPermission(name: string): Promise<string>;
36
+ private findRoleId;
37
+ private findPermissionId;
38
+ /** Grant a permission to a role (creating both by name if needed). Idempotent. */
39
+ givePermissionToRole(roleName: string, permissionName: string): Promise<void>;
40
+ /** Revoke a permission from a role. No-op if either is absent or not linked. */
41
+ revokePermissionFromRole(roleName: string, permissionName: string): Promise<void>;
42
+ /**
43
+ * Assign a role to a user (creating the role by name if needed). Idempotent.
44
+ *
45
+ * Pass `{ tenantId }` to scope the assignment to a tenant — it then applies ONLY within that
46
+ * tenant. Omitting it makes a GLOBAL assignment that applies in every tenant (and in an
47
+ * unscoped check). The same `(user, role)` can be assigned in multiple tenants independently.
48
+ */
49
+ assignRole(user: UserRef, roleName: string, scope?: RoleAssignmentScope): Promise<void>;
50
+ /**
51
+ * REPLACE the user's role assignments of ONE source (default `'manual'`) in one tenant scope
52
+ * with exactly `roleNames` — e.g. an SSO/SCIM sync calls `setUserRoles(user, mappedRoles,
53
+ * { source: 'sso' })` on every login. Other sources' assignments are untouched, so a role held
54
+ * both manually and via SSO survives an SSO sync that drops it. Roles are created by name when
55
+ * missing. Runs in a transaction (or inside the caller's, when the store was built with `tx`).
56
+ */
57
+ setUserRoles(user: UserRef, roleNames: readonly string[], scope?: RoleAssignmentScope): Promise<void>;
58
+ /**
59
+ * Remove a role from a user. No-op if the role or assignment is absent. With `{ tenantId }`
60
+ * only the assignment in THAT tenant is removed; omitting it removes the GLOBAL assignment.
61
+ * With `{ source }` only that source's assignment goes; without it, every source's.
62
+ */
63
+ removeRole(user: UserRef, roleName: string, scope?: RoleAssignmentScope): Promise<void>;
64
+ /** Grant a permission DIRECTLY to a user (spatie's `$user->givePermissionTo`). Idempotent. */
65
+ giveUserPermission(user: UserRef, permissionName: string): Promise<void>;
66
+ /**
67
+ * Revoke a DIRECT user permission. No-op if absent. Only the direct grant is removed — a
68
+ * permission the user ALSO has via a role survives.
69
+ */
70
+ revokeUserPermission(user: UserRef, permissionName: string): Promise<void>;
71
+ /**
72
+ * Role assignments visible for a tenant scope: a GLOBAL assignment always applies; a
73
+ * tenant-scoped one only when its tenant matches. With no tenant, only global assignments are
74
+ * visible (a tenant-scoped role never leaks into an unscoped check).
75
+ */
76
+ private tenantFilter;
77
+ private userRoleWhere;
78
+ /** The role names a user holds, optionally restricted to a tenant scope (see {@link assignRole}). */
79
+ getRolesForUser(user: UserRef, scope?: TenantScope): Promise<string[]>;
80
+ /**
81
+ * Every role assignment visible in a tenant scope, one entry per `(role, source, tenant)` —
82
+ * e.g. to show which roles came from SSO and which were granted by hand.
83
+ */
84
+ getRoleAssignments(user: UserRef, scope?: TenantScope): Promise<RoleAssignment[]>;
85
+ /**
86
+ * The flattened, distinct permission names a user has — the UNION of role-derived permissions
87
+ * (honoring the tenant scope) and DIRECT user permissions (not tenant-scoped). Includes
88
+ * wildcard grants (`posts.*`) verbatim; the core matcher expands them.
89
+ */
90
+ getPermissionsForUser(user: UserRef, scope?: TenantScope): Promise<string[]>;
91
+ /** A user's roles + effective permissions in one shot (tenant-aware). */
92
+ getUserAuthz(user: UserRef, scope?: TenantScope): Promise<UserAuthz>;
93
+ /**
94
+ * True when the user holds `permission` (exact name) — via a (tenant-scoped) role OR a direct
95
+ * grant. With no scope, only global role assignments count toward the role path.
96
+ */
97
+ userHasPermission(user: UserRef, permission: string, scope?: TenantScope): Promise<boolean>;
98
+ }
99
+ //# sourceMappingURL=drizzle-authz.store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-authz.store.d.ts","sourceRoot":"","sources":["../src/drizzle-authz.store.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,OAAO,EAEb,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,KAAK,WAAW,EAAoD,MAAM,aAAa,CAAC;AACjG,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,WA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