@dudousxd/nestjs-authz-testing 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) 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,34 @@
1
+ # `@dudousxd/nestjs-authz-testing`
2
+
3
+ Test helpers for [`@dudousxd/nestjs-authz`](../core). Build a real `Gate`/`BoundGate`
4
+ from fixture users, policies, gates, and an in-memory permission/role provider — no
5
+ Nest module, no database — then assert verdicts with `expectCan` / `expectCannot`.
6
+
7
+ ```ts
8
+ import 'reflect-metadata';
9
+ import { Policy } from '@dudousxd/nestjs-authz';
10
+ import { buildGate, expectCan, expectCannot, FakePermissionProvider } from '@dudousxd/nestjs-authz-testing';
11
+
12
+ @Policy(Post)
13
+ class PostPolicy {
14
+ update(user, post) { return user?.id === post.authorId; }
15
+ }
16
+
17
+ const gate = buildGate({ policies: [new PostPolicy()] });
18
+ await expectCan(gate, { id: 1 }, 'update', new Post(10, 1));
19
+ await expectCannot(gate, { id: 2 }, 'update', new Post(10, 1));
20
+
21
+ // RBAC seam, zero DB — wildcard grants work via the core matcher:
22
+ const gate2 = buildGate({ permissionProvider: new FakePermissionProvider({ '1': ['posts.*'] }) });
23
+ await expectCan(gate2, { id: 1 }, 'posts.update');
24
+ ```
25
+
26
+ ## API
27
+
28
+ - `buildGate(options?)` → `Gate` from `{ policies, gates, superAdmin, after, resolveRoles, permissionProvider, roleProvider }`.
29
+ - `buildBoundGate(user, options?)` → `BoundGate` bound to a fixture user.
30
+ - `expectCan(gate, user, ability, resource?)` / `expectCannot(...)` — assert the verdict
31
+ (accept a `Gate` + user, or a `BoundGate` with `undefined` user). `expectCannot`
32
+ treats an unresolved ability as "cannot".
33
+ - `FakePermissionProvider` / `FakeRoleProvider` — in-memory RBAC seams keyed by user id.
34
+ - `AuthzAssertionError` — thrown on assertion failure.
@@ -0,0 +1,41 @@
1
+ import type { PermissionProvider, RoleProvider, User } from '@dudousxd/nestjs-authz';
2
+ /**
3
+ * A grants table for {@link FakePermissionProvider} / {@link FakeRoleProvider},
4
+ * keyed by a user identity. The default identity is the user's `id` (or the user
5
+ * itself when it has none), so `{ '1': ['posts.*'] }` grants user #1.
6
+ */
7
+ export type FakePermissionGrants = Record<string, string[]>;
8
+ /**
9
+ * An in-memory {@link PermissionProvider} for tests — no database. Grants are a
10
+ * `{ userId: permissions[] }` table; the user's granted set is exposed via
11
+ * `getPermissions`, so the core's wildcard matcher applies (`posts.*` satisfies
12
+ * `posts.update`, `*` satisfies anything) exactly as with a real RBAC adapter.
13
+ *
14
+ * @example
15
+ * const provider = new FakePermissionProvider({ '1': ['posts.*'], '2': ['posts.read'] });
16
+ * const gate = buildGate({ permissionProvider: provider });
17
+ * await expectCan(gate, { id: 1 }, 'posts.update'); // wildcard grant
18
+ */
19
+ export declare class FakePermissionProvider implements PermissionProvider {
20
+ private readonly grants;
21
+ private readonly identity;
22
+ constructor(grants?: FakePermissionGrants, identity?: (user: User) => string);
23
+ /** Grant `permission` to a user (chainable). */
24
+ grant(user: User, permission: string): this;
25
+ hasPermission(user: User, permission: string): boolean;
26
+ getPermissions(user: User): string[] | undefined;
27
+ }
28
+ /**
29
+ * An in-memory {@link RoleProvider} for tests — a `{ userId: roles[] }` table. Use
30
+ * with `buildGate({ roleProvider })` to exercise coarse role checks (`gate.hasRole`)
31
+ * without a database.
32
+ */
33
+ export declare class FakeRoleProvider implements RoleProvider {
34
+ private readonly roles;
35
+ private readonly identity;
36
+ constructor(roles?: FakePermissionGrants, identity?: (user: User) => string);
37
+ /** Assign `role` to a user (chainable). */
38
+ assign(user: User, role: string): this;
39
+ getRoles(user: User): string[] | undefined;
40
+ }
41
+ //# sourceMappingURL=fakes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fakes.d.ts","sourceRoot":"","sources":["../src/fakes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAErF;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAY5D;;;;;;;;;;GAUG;AACH,qBAAa,sBAAuB,YAAW,kBAAkB;IAC/D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2B;IAClD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;gBAGhD,MAAM,GAAE,oBAAyB,EACjC,QAAQ,GAAE,CAAC,IAAI,EAAE,IAAI,KAAK,MAAwB;IAMpD,gDAAgD;IAChD,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI;IAQ3C,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IAItD,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,EAAE,GAAG,SAAS;CAIjD;AAED;;;;GAIG;AACH,qBAAa,gBAAiB,YAAW,YAAY;IACnD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA2B;IACjD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;gBAGhD,KAAK,GAAE,oBAAyB,EAChC,QAAQ,GAAE,CAAC,IAAI,EAAE,IAAI,KAAK,MAAwB;IAMpD,2CAA2C;IAC3C,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAQtC,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,EAAE,GAAG,SAAS;CAI3C"}
package/dist/fakes.js ADDED
@@ -0,0 +1,71 @@
1
+ /** Default identity: the user's `id` (stringified), else the value itself. */
2
+ function defaultIdentity(user) {
3
+ if (user == null)
4
+ return '';
5
+ if (typeof user === 'object') {
6
+ const id = user.id;
7
+ if (id != null)
8
+ return String(id);
9
+ }
10
+ return String(user);
11
+ }
12
+ /**
13
+ * An in-memory {@link PermissionProvider} for tests — no database. Grants are a
14
+ * `{ userId: permissions[] }` table; the user's granted set is exposed via
15
+ * `getPermissions`, so the core's wildcard matcher applies (`posts.*` satisfies
16
+ * `posts.update`, `*` satisfies anything) exactly as with a real RBAC adapter.
17
+ *
18
+ * @example
19
+ * const provider = new FakePermissionProvider({ '1': ['posts.*'], '2': ['posts.read'] });
20
+ * const gate = buildGate({ permissionProvider: provider });
21
+ * await expectCan(gate, { id: 1 }, 'posts.update'); // wildcard grant
22
+ */
23
+ export class FakePermissionProvider {
24
+ grants;
25
+ identity;
26
+ constructor(grants = {}, identity = defaultIdentity) {
27
+ this.identity = identity;
28
+ this.grants = new Map(Object.entries(grants).map(([key, perms]) => [key, new Set(perms)]));
29
+ }
30
+ /** Grant `permission` to a user (chainable). */
31
+ grant(user, permission) {
32
+ const key = this.identity(user);
33
+ const set = this.grants.get(key) ?? new Set();
34
+ set.add(permission);
35
+ this.grants.set(key, set);
36
+ return this;
37
+ }
38
+ hasPermission(user, permission) {
39
+ return this.grants.get(this.identity(user))?.has(permission) ?? false;
40
+ }
41
+ getPermissions(user) {
42
+ const set = this.grants.get(this.identity(user));
43
+ return set ? [...set] : undefined;
44
+ }
45
+ }
46
+ /**
47
+ * An in-memory {@link RoleProvider} for tests — a `{ userId: roles[] }` table. Use
48
+ * with `buildGate({ roleProvider })` to exercise coarse role checks (`gate.hasRole`)
49
+ * without a database.
50
+ */
51
+ export class FakeRoleProvider {
52
+ roles;
53
+ identity;
54
+ constructor(roles = {}, identity = defaultIdentity) {
55
+ this.identity = identity;
56
+ this.roles = new Map(Object.entries(roles).map(([key, names]) => [key, new Set(names)]));
57
+ }
58
+ /** Assign `role` to a user (chainable). */
59
+ assign(user, role) {
60
+ const key = this.identity(user);
61
+ const set = this.roles.get(key) ?? new Set();
62
+ set.add(role);
63
+ this.roles.set(key, set);
64
+ return this;
65
+ }
66
+ getRoles(user) {
67
+ const set = this.roles.get(this.identity(user));
68
+ return set ? [...set] : undefined;
69
+ }
70
+ }
71
+ //# sourceMappingURL=fakes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fakes.js","sourceRoot":"","sources":["../src/fakes.ts"],"names":[],"mappings":"AASA,8EAA8E;AAC9E,SAAS,eAAe,CAAC,IAAU;IACjC,IAAI,IAAI,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC;IAC5B,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,MAAM,EAAE,GAAI,IAAyB,CAAC,EAAE,CAAC;QACzC,IAAI,EAAE,IAAI,IAAI;YAAE,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC;IACpC,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,OAAO,sBAAsB;IAChB,MAAM,CAA2B;IACjC,QAAQ,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AA8B,EAAE,EAChC,WAAmC,eAAe;QAElD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3F,CAAC;IAED,2CAA2C;IAC3C,MAAM,CAAC,IAAU,EAAE,IAAY;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAChC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,EAAU,CAAC;QACrD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACd,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,CAAC,IAAU;QACjB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;QAChD,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpC,CAAC;CACF"}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Test helpers for `@dudousxd/nestjs-authz`.
3
+ *
4
+ * Build a real {@link Gate} (no Nest module, no DB) from fixture policies, ad-hoc
5
+ * gates, hooks, and an optional in-memory permission/role provider — then assert
6
+ * verdicts with {@link expectCan}/{@link expectCannot}. The helpers exercise the
7
+ * SAME resolution path the production Gate uses, so a policy that passes here passes
8
+ * in the app.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const gate = buildGate({ policies: [new PostPolicy()] });
13
+ * await expectCan(gate, { id: 1 }, 'update', new Post(1, 1));
14
+ * await expectCannot(gate, { id: 2 }, 'update', new Post(1, 1));
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+ import { type AfterHook, BoundGate, Gate, type GateFn, type PermissionProvider, type PolicyInstance, type Resource, type RoleProvider, type SuperAdminHook, type User } from '@dudousxd/nestjs-authz';
20
+ export { FakePermissionProvider, FakeRoleProvider, } from './fakes.js';
21
+ export type { FakePermissionGrants } from './fakes.js';
22
+ /** Fixture configuration for {@link buildGate}. Every field is optional. */
23
+ export interface BuildGateOptions {
24
+ /**
25
+ * Policy INSTANCES to register (e.g. `new PostPolicy()`). Unlike the Nest module,
26
+ * the test helper does not run DI — pass already-constructed instances. Each MUST be
27
+ * `@Policy(Resource)`-decorated (the registry resolves by resource constructor and
28
+ * throws on an undecorated class, same as production).
29
+ */
30
+ policies?: PolicyInstance[];
31
+ /** Ad-hoc, model-less gates keyed by ability name (same as `gate.define(name, fn)`). */
32
+ gates?: Record<string, GateFn>;
33
+ /** Global super-admin before-hook (Laravel `Gate::before`). */
34
+ superAdmin?: SuperAdminHook;
35
+ /** Global `after` hook (Laravel `Gate::after`). */
36
+ after?: AfterHook;
37
+ /** Override how a user's roles are derived (default reads `user.roles`/`user.role`). */
38
+ resolveRoles?: (user: User) => string[] | undefined | Promise<string[] | undefined>;
39
+ /**
40
+ * An in-memory {@link PermissionProvider} (the RBAC seam) — grants named abilities
41
+ * when the fixture user holds the permission. Use {@link FakePermissionProvider} for
42
+ * a zero-DB stand-in.
43
+ */
44
+ permissionProvider?: PermissionProvider;
45
+ /** An in-memory {@link RoleProvider} for coarse role checks. Use {@link FakeRoleProvider}. */
46
+ roleProvider?: RoleProvider;
47
+ }
48
+ /**
49
+ * Build a real {@link Gate} from fixtures — no Nest container, no database. The
50
+ * returned Gate behaves exactly like the production one (same hooks, same RBAC seam,
51
+ * same resolution order); only the wiring is in-memory.
52
+ */
53
+ export declare function buildGate(options?: BuildGateOptions): Gate;
54
+ /**
55
+ * Build a {@link BoundGate} for a fixture `user` directly — sugar over
56
+ * `buildGate(options).forUser(user)` for tests that focus on a single principal.
57
+ */
58
+ export declare function buildBoundGate(user: User, options?: BuildGateOptions): BoundGate;
59
+ /**
60
+ * Accept either a {@link Gate} (then `user` is required) or an already-bound
61
+ * {@link BoundGate}. Lets the assertion helpers serve both styles.
62
+ */
63
+ export type GateLike = Gate | BoundGate;
64
+ /** A thrown assertion failure from {@link expectCan}/{@link expectCannot}. */
65
+ export declare class AuthzAssertionError extends Error {
66
+ constructor(message: string);
67
+ }
68
+ /**
69
+ * Assert the user CAN perform `ability` (optionally on `resource`). Resolves when
70
+ * allowed; throws {@link AuthzAssertionError} when denied. Works with either a
71
+ * {@link Gate} (+ `user`) or a {@link BoundGate} (pass `undefined` for `user`).
72
+ *
73
+ * @example await expectCan(gate, { id: 1 }, 'update', post);
74
+ * @example await expectCan(boundGate, undefined, 'create');
75
+ */
76
+ export declare function expectCan(gate: GateLike, user: User, ability: string, resource?: Resource): Promise<void>;
77
+ /**
78
+ * Assert the user CANNOT perform `ability` (optionally on `resource`). Resolves when
79
+ * denied; throws {@link AuthzAssertionError} when allowed. An unresolved ability
80
+ * (no policy/gate) counts as "cannot" — the deny-by-default outcome a caller wants
81
+ * to assert — so this never leaks the underlying `AbilityNotResolvedException`.
82
+ */
83
+ export declare function expectCannot(gate: GateLike, user: User, ability: string, resource?: Resource): Promise<void>;
84
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EACL,KAAK,SAAS,EACd,SAAS,EACT,IAAI,EACJ,KAAK,MAAM,EACX,KAAK,kBAAkB,EACvB,KAAK,cAAc,EAEnB,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,IAAI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,YAAY,CAChC,IAAI,EAAE,QAAQ,EACd,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,QAAQ,GAClB,OAAO,CAAC,IAAI,CAAC,CAaf"}
package/dist/index.js ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Test helpers for `@dudousxd/nestjs-authz`.
3
+ *
4
+ * Build a real {@link Gate} (no Nest module, no DB) from fixture policies, ad-hoc
5
+ * gates, hooks, and an optional in-memory permission/role provider — then assert
6
+ * verdicts with {@link expectCan}/{@link expectCannot}. The helpers exercise the
7
+ * SAME resolution path the production Gate uses, so a policy that passes here passes
8
+ * in the app.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const gate = buildGate({ policies: [new PostPolicy()] });
13
+ * await expectCan(gate, { id: 1 }, 'update', new Post(1, 1));
14
+ * await expectCannot(gate, { id: 2 }, 'update', new Post(1, 1));
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+ import { BoundGate, Gate, PolicyRegistry, } from '@dudousxd/nestjs-authz';
20
+ export { FakePermissionProvider, FakeRoleProvider, } from './fakes.js';
21
+ /**
22
+ * Build a real {@link Gate} from fixtures — no Nest container, no database. The
23
+ * returned Gate behaves exactly like the production one (same hooks, same RBAC seam,
24
+ * same resolution order); only the wiring is in-memory.
25
+ */
26
+ export function buildGate(options = {}) {
27
+ const registry = new PolicyRegistry();
28
+ for (const policy of options.policies ?? [])
29
+ registry.register(policy);
30
+ const moduleOptions = {
31
+ ...(options.superAdmin ? { superAdmin: options.superAdmin } : {}),
32
+ ...(options.after ? { after: options.after } : {}),
33
+ ...(options.resolveRoles ? { resolveRoles: options.resolveRoles } : {}),
34
+ };
35
+ // Ctor: (policies, options, context?, moduleRef?, permissionProvider?, roleProvider?).
36
+ const gate = new Gate(registry, moduleOptions, undefined, undefined, options.permissionProvider, options.roleProvider);
37
+ for (const [ability, fn] of Object.entries(options.gates ?? {})) {
38
+ gate.define(ability, fn);
39
+ }
40
+ return gate;
41
+ }
42
+ /**
43
+ * Build a {@link BoundGate} for a fixture `user` directly — sugar over
44
+ * `buildGate(options).forUser(user)` for tests that focus on a single principal.
45
+ */
46
+ export function buildBoundGate(user, options = {}) {
47
+ return buildGate(options).forUser(user);
48
+ }
49
+ function bind(gate, user) {
50
+ return gate instanceof BoundGate ? gate : gate.forUser(user);
51
+ }
52
+ /** A thrown assertion failure from {@link expectCan}/{@link expectCannot}. */
53
+ export class AuthzAssertionError extends Error {
54
+ constructor(message) {
55
+ super(message);
56
+ this.name = 'AuthzAssertionError';
57
+ }
58
+ }
59
+ /**
60
+ * Assert the user CAN perform `ability` (optionally on `resource`). Resolves when
61
+ * allowed; throws {@link AuthzAssertionError} when denied. Works with either a
62
+ * {@link Gate} (+ `user`) or a {@link BoundGate} (pass `undefined` for `user`).
63
+ *
64
+ * @example await expectCan(gate, { id: 1 }, 'update', post);
65
+ * @example await expectCan(boundGate, undefined, 'create');
66
+ */
67
+ export async function expectCan(gate, user, ability, resource) {
68
+ const allowed = await bind(gate, user).allows(ability, resource);
69
+ if (!allowed) {
70
+ throw new AuthzAssertionError(`Expected user to be able to "${ability}"${describeResource(resource)}, but it was DENIED.`);
71
+ }
72
+ }
73
+ /**
74
+ * Assert the user CANNOT perform `ability` (optionally on `resource`). Resolves when
75
+ * denied; throws {@link AuthzAssertionError} when allowed. An unresolved ability
76
+ * (no policy/gate) counts as "cannot" — the deny-by-default outcome a caller wants
77
+ * to assert — so this never leaks the underlying `AbilityNotResolvedException`.
78
+ */
79
+ export async function expectCannot(gate, user, ability, resource) {
80
+ let allowed;
81
+ try {
82
+ allowed = await bind(gate, user).allows(ability, resource);
83
+ }
84
+ catch {
85
+ // Unresolved/ambiguous ability → effectively "cannot" (deny by default).
86
+ return;
87
+ }
88
+ if (allowed) {
89
+ throw new AuthzAssertionError(`Expected user to be UNABLE to "${ability}"${describeResource(resource)}, but it was ALLOWED.`);
90
+ }
91
+ }
92
+ function describeResource(resource) {
93
+ if (resource === undefined)
94
+ return '';
95
+ const name = resource.constructor?.name;
96
+ return name && name !== 'Object' ? ` on a ${name}` : ' on the resource';
97
+ }
98
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAEL,SAAS,EACT,IAAI,EAIJ,cAAc,GAKf,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,sBAAsB,EACtB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AA8BpB;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;IACtD,MAAM,QAAQ,GAAG,IAAI,cAAc,EAAE,CAAC;IACtC,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,QAAQ,IAAI,EAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAEvE,MAAM,aAAa,GAAG;QACpB,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjE,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClD,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxE,CAAC;IAEF,uFAAuF;IACvF,MAAM,IAAI,GAAG,IAAI,IAAI,CACnB,QAAQ,EACR,aAAa,EACb,SAAS,EACT,SAAS,EACT,OAAO,CAAC,kBAAkB,EAC1B,OAAO,CAAC,YAAY,CACrB,CAAC;IAEF,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,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AAM,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC7D,CAAC;IAAC,MAAM,CAAC;QACP,yEAAyE;QACzE,OAAO;IACT,CAAC;IACD,IAAI,OAAO,EAAE,CAAC;QACZ,MAAM,IAAI,mBAAmB,CAC3B,kCAAkC,OAAO,IAAI,gBAAgB,CAAC,QAAQ,CAAC,uBAAuB,CAC/F,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA8B;IACtD,IAAI,QAAQ,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IACtC,MAAM,IAAI,GAAI,QAAgD,CAAC,WAAW,EAAE,IAAI,CAAC;IACjF,OAAO,IAAI,IAAI,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC;AAC1E,CAAC"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@dudousxd/nestjs-authz-testing",
3
+ "version": "0.1.0",
4
+ "description": "Test helpers for @dudousxd/nestjs-authz — build a Gate/BoundGate from fixture users & policies and assert with expectCan/expectCannot.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/DavideCarvalho/nestjs-authz.git",
9
+ "directory": "packages/testing"
10
+ },
11
+ "author": "Davi Carvalho <davi@goflip.ai>",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist/",
24
+ "README.md",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "peerDependencies": {
28
+ "@dudousxd/nestjs-authz": ">=0.5.0",
29
+ "reflect-metadata": ">=0.1.13"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^20.0.0",
33
+ "reflect-metadata": "^0.2.2",
34
+ "typescript": "^5.4.0",
35
+ "vitest": "^3.0.0",
36
+ "@dudousxd/nestjs-authz": "^0.6.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "keywords": [
42
+ "nestjs",
43
+ "authorization",
44
+ "authz",
45
+ "testing",
46
+ "gate",
47
+ "policy",
48
+ "fixtures"
49
+ ],
50
+ "scripts": {
51
+ "build": "tsc -p tsconfig.json",
52
+ "test": "vitest run --passWithNoTests",
53
+ "test:watch": "vitest",
54
+ "typecheck": "tsc -p tsconfig.json --noEmit"
55
+ }
56
+ }