@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/dist/scope.js ADDED
@@ -0,0 +1,95 @@
1
+ import { Table, and, eq, getTableColumns, gt, gte, inArray, is, isNotNull, isNull, lt, lte, ne, notInArray, or, sql, } from 'drizzle-orm';
2
+ /** Always-true / always-false predicates (portable across Postgres/MySQL/SQLite). */
3
+ const ALWAYS_TRUE = () => sql `1 = 1`;
4
+ const ALWAYS_FALSE = () => sql `1 = 0`;
5
+ function columnMap(columns) {
6
+ return is(columns, Table) ? getTableColumns(columns) : columns;
7
+ }
8
+ function resolveColumn(map, field) {
9
+ if (Object.hasOwn(map, field))
10
+ return map[field];
11
+ // Fall back to the physical column name (`author_id` for a property `authorId`).
12
+ for (const column of Object.values(map)) {
13
+ if (column.name === field)
14
+ return column;
15
+ }
16
+ throw new Error(`Unknown scope field "${field}": it is not a column of the scoped table / column map.`);
17
+ }
18
+ /**
19
+ * Compile an ORM-neutral {@link ScopeConstraint} (`gate.scope(Entity)`) into a Drizzle `WHERE`.
20
+ *
21
+ * Returns:
22
+ * - `undefined` for `allow-all` — pass it straight to `.where(...)` / `and(...)`, which both
23
+ * ignore `undefined`, so NO predicate is added (every row is visible);
24
+ * - `1 = 0` for `deny-all` — an always-false predicate;
25
+ * - otherwise the compiled condition tree.
26
+ *
27
+ * Empty semantics match the core AST and the sibling adapters: empty `in` → no rows, empty `nin`
28
+ * → all rows, empty `and` → all rows, empty `or` → no rows.
29
+ *
30
+ * SAFE: fields are resolved against the table's columns (or your explicit map) — an unknown field
31
+ * throws instead of reaching SQL — and values go through Drizzle's operators, so they are always
32
+ * bound parameters (and mapped by the column's driver mapping, e.g. `Date` → timestamp).
33
+ */
34
+ export function compileScope(constraint, columns) {
35
+ if (constraint.kind === 'all')
36
+ return undefined;
37
+ if (constraint.kind === 'none')
38
+ return ALWAYS_FALSE();
39
+ const map = columnMap(columns);
40
+ const compileCondition = (c) => {
41
+ const column = resolveColumn(map, c.field);
42
+ const v = c.value;
43
+ switch (c.op) {
44
+ case 'eq':
45
+ return eq(column, v);
46
+ case 'ne':
47
+ return ne(column, v);
48
+ case 'gt':
49
+ return gt(column, v);
50
+ case 'gte':
51
+ return gte(column, v);
52
+ case 'lt':
53
+ return lt(column, v);
54
+ case 'lte':
55
+ return lte(column, v);
56
+ case 'in':
57
+ case 'nin': {
58
+ const values = Array.isArray(v) ? v : [v];
59
+ // An empty `IN ()` is invalid SQL and matches nothing; an empty `NOT IN ()` matches all.
60
+ if (values.length === 0)
61
+ return c.op === 'in' ? ALWAYS_FALSE() : ALWAYS_TRUE();
62
+ return c.op === 'in' ? inArray(column, values) : notInArray(column, values);
63
+ }
64
+ case 'isNull':
65
+ return isNull(column);
66
+ case 'isNotNull':
67
+ return isNotNull(column);
68
+ default:
69
+ throw new Error(`Unsupported scope operator: ${String(c.op)}`);
70
+ }
71
+ };
72
+ const compileNode = (node) => {
73
+ if (node.kind === 'condition')
74
+ return compileCondition(node);
75
+ // An empty AND is the identity (true); an empty OR is the zero (false).
76
+ if (node.nodes.length === 0)
77
+ return node.kind === 'and' ? ALWAYS_TRUE() : ALWAYS_FALSE();
78
+ const children = node.nodes.map(compileNode);
79
+ return (node.kind === 'and' ? and(...children) : or(...children));
80
+ };
81
+ return compileNode(constraint);
82
+ }
83
+ /**
84
+ * Ergonomic entry point: resolve the query scope for the current (context) user via the Gate and
85
+ * compile it against `columns`. Equivalent to `compileScope(await gate.scope(entity, ability), columns)`.
86
+ *
87
+ * ```ts
88
+ * const scope = await applyScope(gate, Post, posts); // posts = your pgTable
89
+ * const rows = await db.select().from(posts).where(and(scope, eq(posts.published, true)));
90
+ * ```
91
+ */
92
+ export async function applyScope(gate, entity, columns, ability = 'viewAny') {
93
+ return compileScope(await gate.scope(entity, ability), columns);
94
+ }
95
+ //# sourceMappingURL=scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.js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CAAC,CAAC;YACxB,KAAK,WAAW;gBACd,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC;YAC3B;gBACE,MAAM,IAAI,KAAK,CAAC,+BAA+B,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QACnE,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,WAAW,GAAG,CAAC,IAAe,EAAO,EAAE;QAC3C,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW;YAAE,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAC7D,wEAAwE;QACxE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC;QACzF,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAC7C,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAQ,CAAC;IAC3E,CAAC,CAAC;IAEF,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC;AACjC,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,IAAmB,EACnB,MAAqB,EACrB,OAAqB,EACrB,OAAO,GAAG,SAAS;IAEnB,OAAO,YAAY,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,46 @@
1
+ import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
2
+ import type { AuthzTables } from './schema.js';
3
+ /** BYO table names. Any omitted name falls back to {@link DEFAULT_TABLE_NAMES}. */
4
+ export interface TableNames {
5
+ roles?: string;
6
+ permissions?: string;
7
+ rolePermission?: string;
8
+ userRole?: string;
9
+ /** Direct user→permission pivot. Defaults to `authz_user_permission`. */
10
+ userPermission?: string;
11
+ }
12
+ /** Optional tenant scope for a user-role assignment / role-or-permission query. */
13
+ export interface TenantScope {
14
+ /**
15
+ * Restrict a role assignment (or a query) to this tenant. Omitted/undefined → the GLOBAL
16
+ * scope (an assignment applies in every tenant; a query sees global assignments only — a
17
+ * tenant-scoped role does NOT leak into an unscoped check).
18
+ */
19
+ tenantId?: string;
20
+ }
21
+ /**
22
+ * Tenant scope + assignment source for role mutations. `source` (default `'manual'`) records where
23
+ * an assignment came from (`'sso'`, `'scim'`, …) so a sync can replace just its own rows — see
24
+ * `setUserRoles`.
25
+ */
26
+ export interface RoleAssignmentScope extends TenantScope {
27
+ source?: string;
28
+ }
29
+ export interface AuthzStoreOptions {
30
+ /**
31
+ * The Drizzle tables to query — pass the SAME object you spread into your drizzle-kit schema
32
+ * (built with {@link createAuthzTables}). When omitted, the store builds them from
33
+ * `tableNames` / `schema`.
34
+ */
35
+ tables?: AuthzTables;
36
+ /** BYO table names; each defaults to the matching {@link DEFAULT_TABLE_NAMES} entry. Ignored with `tables`. */
37
+ tableNames?: TableNames;
38
+ /** Optional Postgres schema (NOT a connection). Ignored with `tables`. */
39
+ schema?: string;
40
+ }
41
+ /**
42
+ * Any Drizzle Postgres database or transaction (`drizzle(pool)`, `drizzle(pglite)`, `tx` inside
43
+ * `db.transaction(...)`, ...). The app owns the connection; the store never opens one.
44
+ */
45
+ export type DrizzlePgDatabase = PgDatabase<PgQueryResultHKT, any, any>;
46
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,mFAAmF;AACnF,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,+GAA+G;IAC/G,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AAEH,MAAM,MAAM,iBAAiB,GAAG,UAAU,CAAC,gBAAgB,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@dudousxd/nestjs-authz-drizzle",
3
+ "version": "0.1.0",
4
+ "description": "Drizzle ORM RBAC persistence + query-scope compiler for @dudousxd/nestjs-authz — roles, permissions, a Gate seam, and gate.scope() → Drizzle WHERE (zero connection ownership).",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/DavideCarvalho/nestjs-authz.git",
9
+ "directory": "packages/drizzle"
10
+ },
11
+ "homepage": "https://davidecarvalho.github.io/aviary/docs/authz",
12
+ "bugs": {
13
+ "url": "https://github.com/DavideCarvalho/nestjs-authz/issues"
14
+ },
15
+ "keywords": [
16
+ "nestjs",
17
+ "authorization",
18
+ "authz",
19
+ "rbac",
20
+ "roles",
21
+ "permissions",
22
+ "drizzle",
23
+ "drizzle-orm"
24
+ ],
25
+ "author": "Davi Carvalho <davi@goflip.ai>",
26
+ "type": "module",
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist/",
38
+ "README.md",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "peerDependencies": {
42
+ "@dudousxd/nestjs-authz": ">=0.7.0",
43
+ "@nestjs/common": ">=10.0.0",
44
+ "@nestjs/core": ">=10.0.0",
45
+ "drizzle-orm": ">=0.40.0 <1.0.0",
46
+ "reflect-metadata": ">=0.1.13"
47
+ },
48
+ "devDependencies": {
49
+ "@electric-sql/pglite": "0.4.6",
50
+ "@nestjs/common": "12.0.1",
51
+ "@nestjs/core": "12.0.1",
52
+ "@nestjs/testing": "12.0.1",
53
+ "@testcontainers/postgresql": "12.1.0",
54
+ "@types/node": "20.19.43",
55
+ "@types/pg": "8.23.1",
56
+ "drizzle-orm": "0.45.2",
57
+ "pg": "8.23.0",
58
+ "reflect-metadata": "0.2.2",
59
+ "rxjs": "7.8.2",
60
+ "typescript": "5.9.3",
61
+ "vitest": "3.2.7",
62
+ "@dudousxd/nestjs-authz": "^0.7.0"
63
+ },
64
+ "engines": {
65
+ "node": ">=20"
66
+ },
67
+ "scripts": {
68
+ "build": "tsc -p tsconfig.json",
69
+ "test": "vitest run --passWithNoTests",
70
+ "test:db:pg": "AUTHZ_TEST_DIALECT=postgres vitest run --config vitest.db.config.ts",
71
+ "test:watch": "vitest",
72
+ "typecheck": "tsc -p tsconfig.json --noEmit"
73
+ }
74
+ }