@dudousxd/nestjs-authz-typeorm 0.6.0 → 0.8.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 CHANGED
@@ -1,5 +1,64 @@
1
1
  # @dudousxd/nestjs-authz-typeorm
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#76](https://github.com/DavideCarvalho/nestjs-authz/pull/76) [`d2a9b06`](https://github.com/DavideCarvalho/nestjs-authz/commit/d2a9b06c398b80c68957ae573c1f5bd866a9ff72) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Add MCP dev tools: `AuthzModule` registers `authz_explain_check`, `authz_list_effective_roles` and `authz_list_effective_permissions` in the Aviary dev-tools slot (`Symbol.for('@dudousxd/aviary:dev-tools')`, created when absent). They register without an `authorize`, so the agent dev endpoint's `devTools.authorize` gates them (open outside production, denied in production without it); a hub that cannot gate console-less libs leaves them out. `devTools: { loadSubject, loadResource }` hands checks your models (default: `resolveUser` and `resourceLoaders`); `devTools: false` turns the tools off. New: `gate.explainFor(user, ability, resource?)`, `runInTenantScope(tenantId, fn)`, and `RoleProvider.describeRbac?(user)`, which the RBAC adapters implement; the adapters honour a scope forced by `runInTenantScope` ahead of their `tenant` resolver and the context tenant.
8
+
9
+ - [#76](https://github.com/DavideCarvalho/nestjs-authz/pull/76) [`d2a9b06`](https://github.com/DavideCarvalho/nestjs-authz/commit/d2a9b06c398b80c68957ae573c1f5bd866a9ff72) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - A `schema` option puts the authz tables in their own database schema: a Postgres schema, or a MySQL database. Every statement names it, and `search_path` is never used.
10
+
11
+ - **TypeORM** (Postgres and MySQL): `storeOptions.schema`. Adds `authzEntities({ schema, type, tableNames })` for synchronize/migration-generated setups.
12
+ - **Drizzle** (Postgres): `createAuthzTables({ schema })` / `storeOptions.schema`.
13
+ - **MikroORM** (Postgres and MySQL): `createAuthzEntitySchemas(names, { schema })`. The store reads the schema from the entity metadata and qualifies its raw SQL. On MySQL, the heal narrows MikroORM's diff against the target database's `information_schema`. `authzSchemaSql()` includes the create statement.
14
+ - **Prisma** (Postgres): the `schema` option, for models with `@@schema`. The fast path uses `$queryRawUnsafe` with the schema in the SQL and every value bound.
15
+
16
+ Shared behaviour:
17
+
18
+ - Auto-create makes the schema only when the catalog says it is missing. A failure names the grant needed.
19
+ - On SQLite, a `schema` fails at boot. Prisma refuses it on MySQL and SQLite.
20
+ - Names are validated (a safe identifier, at most 63 characters).
21
+ - Without `schema`, nothing changes.
22
+
23
+ - [#76](https://github.com/DavideCarvalho/nestjs-authz/pull/76) [`d2a9b06`](https://github.com/DavideCarvalho/nestjs-authz/commit/d2a9b06c398b80c68957ae573c1f5bd866a9ff72) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Tenancy for nested tenants, tenant families and required tenants (nestjs-context's chain contract, read structurally, so older contexts keep working):
24
+
25
+ - A role or grant assigned at any level of the active tenant chain applies (a clinic role counts inside its units). `tenancy.kinds` picks the levels, and the context's own `kinds` apply when the module sets none.
26
+ - `tenancy.roles` maps the caller's role at every level of the chain.
27
+ - New `tenancy.family` option.
28
+ - New `tenancy.required` option, defaulting to the context's. A check with no tenant throws `TenantRequiredError` (403, `E_TENANT_REQUIRED`) instead of running in the global scope.
29
+ - Console `authorize` helpers, the MCP dev tools, and the new `runWithoutRequiredTenant(fn)` pass `required: false`.
30
+ - `describeRbac` reports the `tenantChain`.
31
+
32
+ ## 0.7.0
33
+
34
+ ### Minor Changes
35
+
36
+ - Back on the 0.x line. The 1.x and 2.x versions were published by accident: a release-tooling peer cascade bumped this package to a major, not an API decision. 0.7.0 contains everything those versions shipped (console `authorize` support, tenancy, Node 24+ `engines`) with no other change. Upgrade from 1.x/2.x to 0.7.0; those versions are deprecated.
37
+
38
+ ## 2.0.0
39
+
40
+ ### Major Changes
41
+
42
+ - [#74](https://github.com/DavideCarvalho/nestjs-authz/pull/74) [`35421dc`](https://github.com/DavideCarvalho/nestjs-authz/commit/35421dc5b09bd271d5087d26e8536191ef6ba342) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - **Breaking:** require Node.js 24 or newer (`engines.node` is now `>=24`; it was `>=22`, and `>=20` for `-client` and `-react`). CI tests on Node 24 and 26. No API changes: see the Upgrading page in the docs.
43
+
44
+ ## 1.1.0
45
+
46
+ ### Minor Changes
47
+
48
+ - [#72](https://github.com/DavideCarvalho/nestjs-authz/pull/72) [`58a5d72`](https://github.com/DavideCarvalho/nestjs-authz/commit/58a5d72d2964a7cfae9cbfe8506526c8518ba30a) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Tenancy for the RBAC modules, following the `@dudousxd/nestjs-context` tenancy switch.
49
+
50
+ - New `tenancy` option (`'inherit' | false | { enabled?, kinds?, nullRows?, roles? }`, default `'inherit'`). With context tenancy on, permission and role checks are scoped to the request's tenant from `Context.setTenant`. A request with no tenant, inside `Context.allTenants()`, or outside a request sees global assignments only. `kinds` limits the tenant kinds this module honours. With tenancy off nothing changes.
51
+ - `tenancy.roles` maps the caller's role inside the tenant (`tenant.role`) to authz roles that apply in that tenant only, e.g. `{ owner: 'org_admin' }`.
52
+ - New `tenant` resolver option, `(user) => tenantId | null | undefined`: an explicit tenant that wins over the context.
53
+ - MikroORM and Prisma can now store tenant-scoped role assignments like Drizzle and TypeORM: `assignRole`, `removeRole` and `setUserRoles` take `{ tenantId }`, and the read methods take a tenant scope. MikroORM: build the entities with `createAuthzEntitySchemas({}, { tenantScoped: true })`. Prisma: add `tenantId String @default("")` to `UserRole` and its `@@id`, then pass `tenantScoped: true`. Without that, every assignment stays global.
54
+
55
+ ## 1.0.0
56
+
57
+ ### Patch Changes
58
+
59
+ - Updated dependencies [[`750a6b3`](https://github.com/DavideCarvalho/nestjs-authz/commit/750a6b3f80deea3803dec8df5f9f8cf67a046ac1)]:
60
+ - @dudousxd/nestjs-authz@0.10.0
61
+
3
62
  ## 0.6.0
4
63
 
5
64
  ### Minor Changes
package/README.md CHANGED
@@ -79,6 +79,32 @@ The user is the one the official guard reads (`AuthorizationModule.forRoot({ get
79
79
  default `request.user`), mapped to a store ref with `userRefFrom` (default `{ type, id }` or
80
80
  `{ id }`).
81
81
 
82
+ ## Tenancy
83
+
84
+ With `@dudousxd/nestjs-context` installed, the module reads the current tenant from the context
85
+ accessor (`Context.tenantId()`). A tenant-scoped role then grants only inside its own tenant.
86
+ Global roles and direct grants apply everywhere.
87
+
88
+ With tenancy on (`ContextModule.forRoot({ tenancy: { enabled: true } })` in
89
+ `@dudousxd/nestjs-context`), checks are scoped to the request's tenant from `Context.setTenant(...)`.
90
+ A request with no tenant, or inside `Context.allTenants()`, sees global assignments only.
91
+
92
+ ```ts
93
+ AuthzRbacModule.forRoot({
94
+ connectionName: 'default',
95
+ tenancy: {
96
+ kinds: ['organization'], // optional: tenant kinds this module honours
97
+ roles: { owner: 'org_admin', member: 'org_member' }, // optional: tenant.role → authz roles in that tenant
98
+ },
99
+ tenant: (user) => (user as { orgId?: string }).orgId, // optional: an explicit tenant wins over the context
100
+ });
101
+ ```
102
+
103
+ `tenancy` defaults to `'inherit'` (follow the context switch); `false` keeps this module out.
104
+ Roles mapped with `roles` apply only inside that tenant and only to the context's current user.
105
+ The `tenant` resolver returns a tenant id, `null` for the global scope, or `undefined` to fall
106
+ back to the context.
107
+
82
108
  ## Query scopes
83
109
 
84
110
  ```ts
@@ -1,5 +1,6 @@
1
1
  import type { UserRef } from '@dudousxd/nestjs-authz/store-kit';
2
2
  import { type DynamicModule } from '@nestjs/common';
3
+ import { type AuthzTenancyOption, type TenantResolver } from './tenancy.js';
3
4
  import { TypeOrmAuthzStore } from './typeorm-authz.store.js';
4
5
  import type { AuthzStoreOptions } from './types.js';
5
6
  /** Injection token holding the {@link TypeOrmAuthzStore} the RBAC module manages. */
@@ -22,6 +23,17 @@ export interface AuthzRbacModuleBaseOptions {
22
23
  * {@link defaultUserRefMapper} (`{ type, id }` or `{ id }`).
23
24
  */
24
25
  userRefFrom?: UserRefMapper;
26
+ /**
27
+ * Tenancy, from `@dudousxd/nestjs-context`. `'inherit'` (default) follows `ContextModule`'s
28
+ * `tenancy.enabled`; with it on, checks are scoped to the context tenant. The object form adds
29
+ * `kinds` and `roles` (map the caller's `tenant.role` to authz roles in that tenant).
30
+ */
31
+ tenancy?: AuthzTenancyOption;
32
+ /**
33
+ * Explicit tenant for a check, from the user being checked. Wins over the context: return a
34
+ * tenant id, `null` for the global scope, or `undefined` to fall back to the context.
35
+ */
36
+ tenant?: TenantResolver;
25
37
  }
26
38
  /**
27
39
  * Where the store comes from: build it yourself (`store`), or name a TypeORM connection
@@ -1 +1 @@
1
- {"version":3,"file":"authz-rbac.module.d.ts","sourceRoot":"","sources":["../src/authz-rbac.module.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EACL,KAAK,aAAa,EAQnB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,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,0BAA0B;IACzC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;OAGG;IACH,WAAW,CAAC,EAAE,aAAa,CAAC;CAC7B;AAED;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG,0BAA0B,GAC7D,CACI;IACE,sEAAsE;IACtE,KAAK,EAAE,iBAAiB,CAAC;IACzB,cAAc,CAAC,EAAE,KAAK,CAAC;IACvB,YAAY,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CAAC,GAAG,sBAAsB,CAAC;IAC7F,cAAc,CAAC,EAAE,KAAK,CAAC;IACvB,YAAY,CAAC,EAAE,KAAK,CAAC;CACtB,GACD;IACE,qGAAqG;IACrG,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,iBAAiB,CAAC;IACjC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;IACnB,UAAU,CAAC,EAAE,CACX,GAAG,IAAI,EAAE,OAAO,EAAE,KACf,OAAO,CAAC,0BAA0B,CAAC,GAAG,0BAA0B,CAAC;CACvE,CAAC;AA6BN,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,SAAS,CAOvE;AAkLD;;;;;;;GAOG;AACH,qBACa,eAAe;IAC1B,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,sBAAsB,GAAG,aAAa;IAqB9D,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,aAAa;IA0CxE,OAAO,CAAC,MAAM,CAAC,eAAe;CAc/B"}
@@ -15,6 +15,7 @@ import { createRequire } from 'node:module';
15
15
  import { CONTEXT_ACCESSOR, PERMISSION_PROVIDER, ROLE_PROVIDER, } from '@dudousxd/nestjs-authz';
16
16
  import { Inject, Injectable, Module, Optional, } from '@nestjs/common';
17
17
  import { ModuleRef } from '@nestjs/core';
18
+ import { acrossScopes, inAnyScope, rbacTenant, } from './tenancy.js';
18
19
  import { TypeOrmAuthzStore } from './typeorm-authz.store.js';
19
20
  /** Injection token holding the {@link TypeOrmAuthzStore} the RBAC module manages. */
20
21
  export const AUTHZ_RBAC_STORE = Symbol.for('@dudousxd/nestjs-authz-typeorm:store');
@@ -42,42 +43,6 @@ function connectionToken(name) {
42
43
  }
43
44
  return official.getDataSourceToken(name);
44
45
  }
45
- /** Read the current tenant from the (optional) context accessor, defensively. */
46
- function tenantScopeFrom(context) {
47
- if (!context || typeof context.tenantId !== 'function')
48
- return {};
49
- let tenantId;
50
- try {
51
- tenantId = context.tenantId();
52
- }
53
- catch {
54
- tenantId = undefined;
55
- }
56
- return tenantId == null ? {} : { tenantId };
57
- }
58
- /**
59
- * Locate the context accessor for tenant scoping. Prefers a value injected into
60
- * this module; falls back to a non-strict {@link ModuleRef} lookup so an accessor
61
- * provided by ANY module (the app root, a global ContextModule) is still found —
62
- * the RBAC module is global and its providers don't import the app's modules, so a
63
- * plain `@Inject` would miss a root-provided accessor. Mirrors the Gate's seam.
64
- */
65
- function resolveTenantContext(injected, moduleRef, cache) {
66
- if (injected)
67
- return injected;
68
- if (cache.resolved)
69
- return cache.value;
70
- cache.resolved = true;
71
- if (moduleRef) {
72
- try {
73
- cache.value = moduleRef.get(CONTEXT_ACCESSOR, { strict: false });
74
- }
75
- catch {
76
- cache.value = undefined;
77
- }
78
- }
79
- return cache.value;
80
- }
81
46
  /** Default mapping: accept a `{ type, id }` ref, a `{ id }` object, or a bare id. */
82
47
  export function defaultUserRefMapper(user) {
83
48
  if (user == null)
@@ -110,8 +75,14 @@ let RbacPermissionProvider = class RbacPermissionProvider {
110
75
  this.context = context;
111
76
  this.moduleRef = moduleRef;
112
77
  }
113
- scope() {
114
- return tenantScopeFrom(resolveTenantContext(this.context, this.moduleRef, this.contextCache));
78
+ tenant(user, ref) {
79
+ return rbacTenant(this.options, user, ref, this.context, this.moduleRef, this.contextCache, true);
80
+ }
81
+ /** The permissions `tenancy.roles` grants through the caller's role in the tenant. */
82
+ async tenantRolePermissions(roles) {
83
+ if (roles.length === 0)
84
+ return [];
85
+ return Object.values(await this.options.store.getRolePermissions(roles)).flat();
115
86
  }
116
87
  // The core `PermissionProvider` interface passes an optional `resource` (3rd
117
88
  // arg); it is intentionally ignored here. RBAC grants are model-less,
@@ -124,7 +95,11 @@ let RbacPermissionProvider = class RbacPermissionProvider {
124
95
  const ref = map(user);
125
96
  if (ref === undefined)
126
97
  return undefined;
127
- return this.options.store.userHasPermission(ref, permission, this.scope());
98
+ const tenant = this.tenant(user, ref);
99
+ if (await inAnyScope(tenant, (scope) => this.options.store.userHasPermission(ref, permission, scope))) {
100
+ return true;
101
+ }
102
+ return (await this.tenantRolePermissions(tenant.roles)).includes(permission);
128
103
  }
129
104
  // Expose the user's full granted permission set so the core can apply
130
105
  // Laravel/spatie-style wildcard matching (a granted `posts.*` satisfies a check
@@ -135,7 +110,11 @@ let RbacPermissionProvider = class RbacPermissionProvider {
135
110
  const ref = map(user);
136
111
  if (ref === undefined)
137
112
  return undefined;
138
- return this.options.store.getPermissionsForUser(ref, this.scope());
113
+ const tenant = this.tenant(user, ref);
114
+ const own = await acrossScopes(tenant, (scope) => this.options.store.getPermissionsForUser(ref, scope));
115
+ if (tenant.roles.length === 0)
116
+ return own;
117
+ return [...new Set([...own, ...(await this.tenantRolePermissions(tenant.roles))])];
139
118
  }
140
119
  };
141
120
  RbacPermissionProvider = __decorate([
@@ -170,10 +149,37 @@ let RbacRoleProvider = class RbacRoleProvider {
170
149
  const ref = map(user);
171
150
  if (ref === undefined)
172
151
  return undefined;
173
- // Scope roles by the current tenant (when nestjs-context is present): a
174
- // tenant-scoped role only counts within its tenant; global roles always count.
175
- const scope = tenantScopeFrom(resolveTenantContext(this.context, this.moduleRef, this.contextCache));
176
- return this.options.store.getRolesForUser(ref, scope);
152
+ // Scope roles by the current tenant: a tenant-scoped role only counts within its
153
+ // tenant; global roles always count. `tenancy.roles` adds the caller's tenant roles.
154
+ const tenant = rbacTenant(this.options, user, ref, this.context, this.moduleRef, this.contextCache, true);
155
+ const own = await acrossScopes(tenant, (scope) => this.options.store.getRolesForUser(ref, scope));
156
+ return tenant.roles.length === 0 ? own : [...new Set([...own, ...tenant.roles])];
157
+ }
158
+ /**
159
+ * Where the user's roles and permissions come from, for the core's dev tools
160
+ * (`authz_explain_check`): the scope the lookups ran in, store vs `tenancy.roles` roles,
161
+ * each role's permissions, and every permission granted in that scope.
162
+ */
163
+ async describeRbac(user) {
164
+ const map = this.options.userRefFrom ?? defaultUserRefMapper;
165
+ const ref = map(user);
166
+ if (ref === undefined)
167
+ return undefined;
168
+ const tenant = rbacTenant(this.options, user, ref, this.context, this.moduleRef, this.contextCache, true);
169
+ const [own, permissions] = await Promise.all([
170
+ acrossScopes(tenant, (scope) => this.options.store.getRolesForUser(ref, scope)),
171
+ acrossScopes(tenant, (scope) => this.options.store.getPermissionsForUser(ref, scope)),
172
+ ]);
173
+ const roles = [...new Set([...own, ...tenant.roles])];
174
+ const rolePermissions = roles.length === 0 ? {} : await this.options.store.getRolePermissions(roles);
175
+ const fromTenantRoles = tenant.roles.flatMap((role) => rolePermissions[role] ?? []);
176
+ return {
177
+ tenantId: tenant.scope.tenantId ?? null,
178
+ tenantChain: tenant.scopes.flatMap((scope) => (scope.tenantId ? [scope.tenantId] : [])),
179
+ roles: { store: own, tenant: tenant.roles },
180
+ rolePermissions,
181
+ permissions: [...new Set([...permissions, ...fromTenantRoles])],
182
+ };
177
183
  }
178
184
  };
179
185
  RbacRoleProvider = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"authz-rbac.module.js","sourceRoot":"","sources":["../src/authz-rbac.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EAEnB,aAAa,GAEd,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAEL,MAAM,EACN,UAAU,EACV,MAAM,EAEN,QAAQ,GAGT,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAG7D,qFAAqF;AACrF,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;AACnF,2EAA2E;AAC3E,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CA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C;IAEO,MAAM,CAAC,eAAe;QAC5B,OAAO;YACL,sBAAsB;YACtB,EAAE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,sBAAsB,EAAE;YACrE,gBAAgB;YAChB,EAAE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;YACzD;gBACE,OAAO,EAAE,gBAAgB;gBACzB,UAAU,EAAE,CAAC,IAAyB,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK;gBACrD,MAAM,EAAE,CAAC,kBAAkB,CAAC;aAC7B;YACD,kBAAkB;SACnB,CAAC;IACJ,CAAC;CACF,CAAA;AA9EY,eAAe;IAD3B,MAAM,CAAC,EAAE,CAAC;GACE,eAAe,CA8E3B"}
@@ -85,4 +85,39 @@ export declare class UserPermissionEntity {
85
85
  }
86
86
  /** All entities, in dependency order — convenient for `entities: [...]` registration. */
87
87
  export declare const AUTHZ_ENTITIES: readonly [typeof RoleEntity, typeof PermissionEntity, typeof RolePermissionEntity, typeof UserRoleEntity, typeof UserPermissionEntity];
88
+ /** Options for {@link authzEntities}. */
89
+ export interface AuthzEntitiesOptions {
90
+ /**
91
+ * Put the tables in this schema: a Postgres schema, or a MySQL database. Every query and DDL
92
+ * statement names it; `search_path` is never used.
93
+ */
94
+ schema?: string;
95
+ /** The connection's database type: `schema` becomes the entities' `schema` on Postgres and their `database` on MySQL. Default `'postgres'`. */
96
+ type?: 'postgres' | 'mysql';
97
+ /** BYO table names, like the store's `tableNames`. */
98
+ tableNames?: Partial<Record<keyof typeof DEFAULT_TABLE_NAMES, string>>;
99
+ }
100
+ /**
101
+ * The authz entities under your table names and schema, for a DataSource whose `synchronize` or
102
+ * migrations generator manages them. Register these INSTEAD of {@link AUTHZ_ENTITIES} and pass
103
+ * the same `schema` / `tableNames` to the store:
104
+ *
105
+ * ```ts
106
+ * const entities = authzEntities({ schema: 'authz' });
107
+ * new DataSource({ type: 'postgres', entities: [...entities, ...appEntities] });
108
+ * new TypeOrmAuthzStore(dataSource, { schema: 'authz' });
109
+ * ```
110
+ */
111
+ export declare function authzEntities(options?: AuthzEntitiesOptions): [
112
+ typeof RoleEntity,
113
+ typeof PermissionEntity,
114
+ typeof RolePermissionEntity,
115
+ typeof UserRoleEntity,
116
+ typeof UserPermissionEntity
117
+ ];
118
+ /**
119
+ * Validate a `schema` option: a safe identifier (letters, digits, `_`, not starting with a
120
+ * digit) of at most 63 characters (the Postgres limit; MySQL allows 64).
121
+ */
122
+ export declare function assertSchemaName(schema: string): void;
88
123
  //# sourceMappingURL=entities.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entities.d.ts","sourceRoot":"","sources":["../src/entities.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB;;;;;;CAMtB,CAAC;AAEX;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,KAAK,CAAC;AAEhC;;;;;;;GAOG;AACH,qBACa,UAAU;IAErB,EAAE,EAAG,MAAM,CAAC;IAIZ,IAAI,EAAG,MAAM,CAAC;IAGd,KAAK,EAAG,MAAM,GAAG,IAAI,CAAC;IAGtB,SAAS,EAAG,IAAI,CAAC;CAClB;AAED,oGAAoG;AACpG,qBACa,gBAAgB;IAE3B,EAAE,EAAG,MAAM,CAAC;IAIZ,IAAI,EAAG,MAAM,CAAC;IAGd,KAAK,EAAG,MAAM,GAAG,IAAI,CAAC;IAGtB,SAAS,EAAG,IAAI,CAAC;CAClB;AAED,uEAAuE;AACvE,qBACa,oBAAoB;IAE/B,MAAM,EAAG,MAAM,CAAC;IAGhB,YAAY,EAAG,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;GAWG;AACH,qBAEa,cAAc;IAEzB,QAAQ,EAAG,MAAM,CAAC;IAGlB,MAAM,EAAG,MAAM,CAAC;IAKhB,MAAM,EAAG,MAAM,CAAC;IAGhB,QAAQ,EAAG,MAAM,CAAC;IAElB;;;;;;OAMG;IAEH,MAAM,EAAG,MAAM,CAAC;CACjB;AAED;;;;;G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AEX,yCAAyC;AACzC,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+IAA+I;IAC/I,IAAI,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC5B,sDAAsD;IACtD,UAAU,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,OAAO,mBAAmB,EAAE,MAAM,CAAC,CAAC,CAAC;CACxE;AAUD;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAC3B,OAAO,GAAE,oBAAyB,GACjC;IACD,OAAO,UAAU;IACjB,OAAO,gBAAgB;IACvB,OAAO,oBAAoB;IAC3B,OAAO,cAAc;IACrB,OAAO,oBAAoB;CAC5B,CAqBA;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAKrD"}
package/dist/entities.js CHANGED
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
+ import { assertSafeIdentifier } from '@dudousxd/nestjs-authz';
10
11
  import { DEFAULT_ROLE_SOURCE } from '@dudousxd/nestjs-authz/store-kit';
11
12
  import { Column, Entity, Index, PrimaryColumn } from 'typeorm';
12
13
  /**
@@ -200,4 +201,56 @@ export const AUTHZ_ENTITIES = [
200
201
  UserRoleEntity,
201
202
  UserPermissionEntity,
202
203
  ];
204
+ const BASES = {
205
+ roles: RoleEntity,
206
+ permissions: PermissionEntity,
207
+ rolePermission: RolePermissionEntity,
208
+ userRole: UserRoleEntity,
209
+ userPermission: UserPermissionEntity,
210
+ };
211
+ /**
212
+ * The authz entities under your table names and schema, for a DataSource whose `synchronize` or
213
+ * migrations generator manages them. Register these INSTEAD of {@link AUTHZ_ENTITIES} and pass
214
+ * the same `schema` / `tableNames` to the store:
215
+ *
216
+ * ```ts
217
+ * const entities = authzEntities({ schema: 'authz' });
218
+ * new DataSource({ type: 'postgres', entities: [...entities, ...appEntities] });
219
+ * new TypeOrmAuthzStore(dataSource, { schema: 'authz' });
220
+ * ```
221
+ */
222
+ export function authzEntities(options = {}) {
223
+ const { schema, type = 'postgres', tableNames = {} } = options;
224
+ if (schema !== undefined)
225
+ assertSchemaName(schema);
226
+ const make = (key) => {
227
+ const name = tableNames[key] ?? DEFAULT_TABLE_NAMES[key];
228
+ assertSafeIdentifier(name, `table name (${key})`);
229
+ const base = BASES[key];
230
+ // A subclass per call: TypeORM reads the columns from the decorated base class.
231
+ const entity = class extends base {
232
+ };
233
+ Object.defineProperty(entity, 'name', { value: base.name });
234
+ const where = schema === undefined ? {} : type === 'mysql' ? { database: schema } : { schema };
235
+ Entity({ name, ...where })(entity);
236
+ return entity;
237
+ };
238
+ return [
239
+ make('roles'),
240
+ make('permissions'),
241
+ make('rolePermission'),
242
+ make('userRole'),
243
+ make('userPermission'),
244
+ ];
245
+ }
246
+ /**
247
+ * Validate a `schema` option: a safe identifier (letters, digits, `_`, not starting with a
248
+ * digit) of at most 63 characters (the Postgres limit; MySQL allows 64).
249
+ */
250
+ export function assertSchemaName(schema) {
251
+ assertSafeIdentifier(schema, 'schema name');
252
+ if (schema.length > 63) {
253
+ throw new Error(`Schema name ${JSON.stringify(schema)} is longer than 63 characters.`);
254
+ }
255
+ }
203
256
  //# sourceMappingURL=entities.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"entities.js","sourceRoot":"","sources":["../src/entities.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,KAAK,EAAE,aAAa;IACpB,WAAW,EAAE,mBAAmB;IAChC,c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C,gBAAgB,CAAC;KACvB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAc;IAC7C,oBAAoB,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC5C,IAAI,MAAM,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,eAAe,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,gCAAgC,CAAC,CAAC;IACzF,CAAC;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- export { AUTHZ_ENTITIES, DEFAULT_TABLE_NAMES, GLOBAL_TENANT, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, } from './entities.js';
1
+ export { AUTHZ_ENTITIES, type AuthzEntitiesOptions, DEFAULT_TABLE_NAMES, authzEntities, GLOBAL_TENANT, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, } from './entities.js';
2
2
  export { createAuthzTables, ensureAuthzSchema } from './schema.js';
3
3
  export { TypeOrmAuthzStore } from './typeorm-authz.store.js';
4
4
  export type { RoleAssignment, RoleAssignmentFilter, UserAuthz, UserRoleAssignment, } from './typeorm-authz.store.js';
5
5
  export { AUTHZ_RBAC_OPTIONS, AUTHZ_RBAC_STORE, AuthzRbacModule, defaultUserRefMapper, } from './authz-rbac.module.js';
6
6
  export type { AuthzRbacModuleAsyncOptions, AuthzRbacModuleBaseOptions, AuthzRbacModuleOptions, UserRefMapper, } from './authz-rbac.module.js';
7
7
  export type { AuthzStoreOptions, RoleAssignmentScope, TableNames, TenantScope } from './types.js';
8
+ export type { AuthzTenancyOption, TenantResolver } from './tenancy.js';
8
9
  export type { UserRef, UserRefInput } from '@dudousxd/nestjs-authz/store-kit';
9
10
  export { applyScope, applyScopeConstraint, compileScope } from './scope.js';
10
11
  export type { CompiledScope, ScopeResolver } from './scope.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,YAAY,EACV,cAAc,EACd,oBAAoB,EACpB,SAAS,EACT,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GACrB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,2BAA2B,EAC3B,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,GACd,MAAM,wBAAwB,CAAC;AAChC,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAClG,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC5E,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,oBAAoB,EACzB,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,YAAY,EACV,cAAc,EACd,oBAAoB,EACpB,SAAS,EACT,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GACrB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,2BAA2B,EAC3B,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,GACd,MAAM,wBAAwB,CAAC;AAChC,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAClG,YAAY,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACvE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC5E,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { AUTHZ_ENTITIES, DEFAULT_TABLE_NAMES, GLOBAL_TENANT, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, } from './entities.js';
1
+ export { AUTHZ_ENTITIES, DEFAULT_TABLE_NAMES, authzEntities, GLOBAL_TENANT, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, } from './entities.js';
2
2
  export { createAuthzTables, ensureAuthzSchema } from './schema.js';
3
3
  export { TypeOrmAuthzStore } from './typeorm-authz.store.js';
4
4
  export { AUTHZ_RBAC_OPTIONS, AUTHZ_RBAC_STORE, AuthzRbacModule, defaultUserRefMapper, } from './authz-rbac.module.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAO7D,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GACrB,MAAM,wBAAwB,CAAC;AAShC,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAO7D,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,GACrB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC"}
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type DataSource, type QueryRunner } from 'typeorm';
2
2
  import type { AuthzStoreOptions } from './types.js';
3
+ /** Throws when `schema` is set on a connection that has no schemas (SQLite). */
4
+ export declare function assertSchemaSupported(dataSource: DataSource, schema: string | undefined): void;
3
5
  /**
4
6
  * Create the RBAC tables (roles, permissions, and the two pivots) if they don't exist.
5
7
  * Strictly non-destructive — `CREATE TABLE` only runs for a table that is absent. Call it
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,WAAW,EAGjB,MAAM,SAAS,CAAC;AAUjB,OAAO,KAAK,EAAE,iBAAiB,EAAc,MAAM,YAAY,CAAC;AAqFhE;;;;;;;;;;;;GAYG;AACH,wBAAsB,iBAAiB,CACrC,WAAW,EAAE,WAAW,EACxB,IAAI,CAAC,EAAE,iBAAiB,GACvB,OAAO,CAAC,IAAI,CAAC,CAUf;AAsCD;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,UAAU,EACtB,IAAI,CAAC,EAAE,iBAAiB,GACvB,OAAO,CAAC,IAAI,CAAC,CAkBf"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,WAAW,EAGjB,MAAM,SAAS,CAAC;AAWjB,OAAO,KAAK,EAAE,iBAAiB,EAAc,MAAM,YAAY,CAAC;AAgGhE,gFAAgF;AAChF,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAO9F;AA8CD;;;;;;;;;;;;GAYG;AACH,wBAAsB,iBAAiB,CACrC,WAAW,EAAE,WAAW,EACxB,IAAI,CAAC,EAAE,iBAAiB,GACvB,OAAO,CAAC,IAAI,CAAC,CAYf;AAsCD;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,UAAU,EACtB,IAAI,CAAC,EAAE,iBAAiB,GACvB,OAAO,CAAC,IAAI,CAAC,CAqBf"}
package/dist/schema.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { assertSafeIdentifier } from '@dudousxd/nestjs-authz';
2
2
  import { Table, TableColumn, } from 'typeorm';
3
3
  import { TableUtils } from 'typeorm/schema-builder/util/TableUtils.js';
4
- import { DEFAULT_TABLE_NAMES, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, } from './entities.js';
4
+ import { DEFAULT_TABLE_NAMES, PermissionEntity, RoleEntity, RolePermissionEntity, UserPermissionEntity, UserRoleEntity, assertSchemaName, } from './entities.js';
5
5
  /** Resolve the (schema-qualified) table name for an entity, applying BYO overrides. */
6
6
  function tableName(base, schema) {
7
7
  return schema ? `${schema}.${base}` : base;
@@ -24,7 +24,7 @@ function plans(opts) {
24
24
  assertSafeIdentifier(name, `table name (${key})`);
25
25
  }
26
26
  if (schema !== undefined)
27
- assertSafeIdentifier(schema, 'schema name');
27
+ assertSchemaName(schema);
28
28
  return [
29
29
  { entity: RoleEntity, name: tableName(names.roles, schema) },
30
30
  { entity: PermissionEntity, name: tableName(names.permissions, schema) },
@@ -65,6 +65,58 @@ function tableFromMetadata(connection, metadata, driver, name) {
65
65
  }
66
66
  return table;
67
67
  }
68
+ const SQLITE_TYPES = new Set([
69
+ 'sqlite',
70
+ 'better-sqlite3',
71
+ 'sqljs',
72
+ 'capacitor',
73
+ 'cordova',
74
+ 'expo',
75
+ 'nativescript',
76
+ 'react-native',
77
+ ]);
78
+ /** Throws when `schema` is set on a connection that has no schemas (SQLite). */
79
+ export function assertSchemaSupported(dataSource, schema) {
80
+ if (schema === undefined)
81
+ return;
82
+ if (SQLITE_TYPES.has(String(dataSource.options.type))) {
83
+ throw new Error(`nestjs-authz: \`schema: '${schema}'\` is not supported on SQLite (${dataSource.options.type}), which has no schemas. Remove \`schema\`, or use Postgres or MySQL.`);
84
+ }
85
+ }
86
+ const isMysql = (dataSource) => ['mysql', 'mariadb', 'aurora-mysql'].includes(String(dataSource.options.type));
87
+ /**
88
+ * Create `schema` (a Postgres schema, or a MySQL database) when it is missing. It checks the
89
+ * catalog first: `CREATE SCHEMA IF NOT EXISTS` needs the CREATE privilege even when the schema
90
+ * already exists.
91
+ */
92
+ async function ensureSchemaExists(queryRunner, schema) {
93
+ const dataSource = queryRunner.connection;
94
+ assertSchemaSupported(dataSource, schema);
95
+ const mysql = isMysql(dataSource);
96
+ const rows = (await queryRunner.query(`SELECT 1 AS found FROM information_schema.schemata WHERE schema_name = ${mysql ? '?' : '$1'}`, [schema]));
97
+ if (rows.length > 0)
98
+ return;
99
+ const quoted = dataSource.driver.escape(schema);
100
+ try {
101
+ await queryRunner.query(mysql ? `CREATE DATABASE IF NOT EXISTS ${quoted}` : `CREATE SCHEMA IF NOT EXISTS ${quoted}`);
102
+ }
103
+ catch (error) {
104
+ const grant = mysql
105
+ ? `GRANT CREATE ON *.* TO <user>, or create the database \`${schema}\` yourself`
106
+ : `GRANT CREATE ON DATABASE <database> TO <role>, or create the schema "${schema}" yourself`;
107
+ throw new Error(`nestjs-authz: could not create the ${mysql ? 'database' : 'schema'} ${JSON.stringify(schema)} for the authz tables (${error.message}). ${grant}.`);
108
+ }
109
+ }
110
+ /**
111
+ * The entity metadata for one authz table: the base entity's, or that of an
112
+ * {@link authzEntities} subclass registered in its place.
113
+ */
114
+ function metadataFor(connection, entity) {
115
+ const all = connection.entityMetadatas;
116
+ const found = all.find((m) => m.target === entity) ??
117
+ all.find((m) => typeof m.target === 'function' && m.target.prototype instanceof entity);
118
+ return found ?? connection.getMetadata(entity);
119
+ }
68
120
  /**
69
121
  * Create the RBAC tables (roles, permissions, and the two pivots) if they don't exist.
70
122
  * Strictly non-destructive — `CREATE TABLE` only runs for a table that is absent. Call it
@@ -80,10 +132,13 @@ function tableFromMetadata(connection, metadata, driver, name) {
80
132
  */
81
133
  export async function createAuthzTables(queryRunner, opts) {
82
134
  const driver = queryRunner.connection.driver;
83
- for (const plan of plans(opts)) {
135
+ const tablePlans = plans(opts);
136
+ if (opts?.schema !== undefined)
137
+ await ensureSchemaExists(queryRunner, opts.schema);
138
+ for (const plan of tablePlans) {
84
139
  if (await queryRunner.hasTable(plan.name))
85
140
  continue;
86
- const metadata = queryRunner.connection.getMetadata(plan.entity);
141
+ const metadata = metadataFor(queryRunner.connection, plan.entity);
87
142
  await queryRunner.createTable(tableFromMetadata(queryRunner.connection, metadata, driver, plan.name), true);
88
143
  }
89
144
  }
@@ -100,7 +155,7 @@ export async function createAuthzTables(queryRunner, opts) {
100
155
  * a default. `ADD COLUMN` of a NOT NULL column without a default fails on a populated table.
101
156
  */
102
157
  async function addMissingColumns(queryRunner, plan) {
103
- const metadata = queryRunner.connection.getMetadata(plan.entity);
158
+ const metadata = metadataFor(queryRunner.connection, plan.entity);
104
159
  const driver = queryRunner.connection.driver;
105
160
  const table = await queryRunner.getTable(plan.name);
106
161
  if (!table)
@@ -129,15 +184,19 @@ const PLAIN_ON_UPGRADE = new Set(['source']);
129
184
  * {@link addMissingColumns}). Never drops/alters/renames — safe to run on every boot.
130
185
  */
131
186
  export async function ensureAuthzSchema(dataSource, opts) {
187
+ assertSchemaSupported(dataSource, opts?.schema);
188
+ const tablePlans = plans(opts);
132
189
  const queryRunner = dataSource.createQueryRunner();
133
190
  try {
134
191
  const driver = dataSource.driver;
135
- for (const plan of plans(opts)) {
192
+ if (opts?.schema !== undefined)
193
+ await ensureSchemaExists(queryRunner, opts.schema);
194
+ for (const plan of tablePlans) {
136
195
  if (await queryRunner.hasTable(plan.name)) {
137
196
  await addMissingColumns(queryRunner, plan);
138
197
  }
139
198
  else {
140
- const metadata = queryRunner.connection.getMetadata(plan.entity);
199
+ const metadata = metadataFor(queryRunner.connection, plan.entity);
141
200
  await queryRunner.createTable(tableFromMetadata(queryRunner.connection, metadata, driver, plan.name), true);
142
201
  }
143
202
  }