@dudousxd/nestjs-authz-client 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 +20 -0
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/store.d.ts +105 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +142 -0
- package/dist/store.js.map +1 -0
- package/package.json +48 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# @dudousxd/nestjs-authz-client
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2](https://github.com/DavideCarvalho/nestjs-authz/pull/2) [`2ecb0f4`](https://github.com/DavideCarvalho/nestjs-authz/commit/2ecb0f46342fa4527fc01f1097720f2e7bcf9aa7) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Extract the framework-neutral ability store into a new `@dudousxd/nestjs-authz-client`
|
|
8
|
+
package and add a `@dudousxd/nestjs-authz-react` package.
|
|
9
|
+
|
|
10
|
+
- **`@dudousxd/nestjs-authz-client`** (new): the canonical home for the in-memory
|
|
11
|
+
`AbilityStore`, `createCan` (synchronous cache hit; configurable `fallback: 'deny' | 'fetch'`
|
|
12
|
+
to `POST /authz/can` on a miss), and `hydrateFromInertiaProps` / `hydrateResource`. Pure
|
|
13
|
+
TypeScript plus an injectable `fetch` — no React/Vue/NestJS/Inertia dependency.
|
|
14
|
+
- **`@dudousxd/nestjs-authz-react`** (new): `AuthzProvider` (holds a hydrated `AbilityStore`),
|
|
15
|
+
`useCan(ability, resource?)` (returns `{ allowed, loading }`, synchronous and request-free on a
|
|
16
|
+
cache hit; honors the store's fallback on a miss), and `<Can ability of fallback>`. A missing
|
|
17
|
+
provider fails closed (deny).
|
|
18
|
+
- **`@dudousxd/nestjs-authz-inertia`** (patch): now depends on `@dudousxd/nestjs-authz-client` and
|
|
19
|
+
re-exports its store instead of carrying a private copy. The
|
|
20
|
+
`@dudousxd/nestjs-authz-inertia/client` entry point is unchanged for consumers.
|
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,47 @@
|
|
|
1
|
+
# @dudousxd/nestjs-authz-client
|
|
2
|
+
|
|
3
|
+
Framework-neutral, in-memory ability store + `can()` resolver for
|
|
4
|
+
[`@dudousxd/nestjs-authz`](../core). Hydrate a user's decisions once (from Inertia
|
|
5
|
+
shared props, a JSON island, or any source) and answer client-side `can(...)` checks
|
|
6
|
+
**synchronously, with no network request**.
|
|
7
|
+
|
|
8
|
+
No dependency on React/Vue/NestJS/Inertia — it is pure TypeScript plus an injectable
|
|
9
|
+
`fetch`. The `-react` and `-inertia` packages, and the codegen client, all reuse it.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import {
|
|
13
|
+
AbilityStore,
|
|
14
|
+
hydrateFromInertiaProps,
|
|
15
|
+
hydrateResource,
|
|
16
|
+
createCan,
|
|
17
|
+
} from '@dudousxd/nestjs-authz-client';
|
|
18
|
+
|
|
19
|
+
const store = new AbilityStore();
|
|
20
|
+
hydrateFromInertiaProps(store, pageProps); // reads props.auth.can
|
|
21
|
+
hydrateResource(store, { type: 'Post', id: post.id }, post.can); // per-instance map
|
|
22
|
+
|
|
23
|
+
const can = createCan(store);
|
|
24
|
+
can('post.create'); // → boolean, synchronously, no fetch
|
|
25
|
+
can('update', { type: 'Post', id: post.id }); // → boolean
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Fallback on a cache miss
|
|
29
|
+
|
|
30
|
+
When an ability/resource is not hydrated, `createCan` behaves per `fallback`:
|
|
31
|
+
|
|
32
|
+
- `'deny'` (default) — returns `false` synchronously.
|
|
33
|
+
- `'fetch'` — `POST { ability, resource }` to `endpoint` (default `'/authz/can'`)
|
|
34
|
+
and returns a `Promise<boolean>` from the server's `{ allowed }`.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
const can = createCan(store, { fallback: 'fetch', endpoint: '/authz/can' });
|
|
38
|
+
const allowed = can('rare.ability'); // boolean (hit) | Promise<boolean> (miss → fetch)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## API
|
|
42
|
+
|
|
43
|
+
- `AbilityStore` — `setClassAbilities` / `mergeClassAbilities` / `setResourceAbilities` /
|
|
44
|
+
`has` / `peek` / `clear`.
|
|
45
|
+
- `hydrateFromInertiaProps(store, props, propKey?)`
|
|
46
|
+
- `hydrateResource(store, ref, can)`
|
|
47
|
+
- `createCan(store, options?)` → `CanResolver`
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const VERSION = "0.0.0";
|
|
2
|
+
export { AbilityStore, createCan, hydrateFromInertiaProps, hydrateResource, } from './store.js';
|
|
3
|
+
export type { CanMap, ResourceRef, HydratableProps, FallbackMode, AbilityStoreOptions, CanResolver, } from './store.js';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,UAAU,CAAC;AAE/B,OAAO,EACL,YAAY,EACZ,SAAS,EACT,uBAAuB,EACvB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,MAAM,EACN,WAAW,EACX,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,WAAW,GACZ,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B,OAAO,EACL,YAAY,EACZ,SAAS,EACT,uBAAuB,EACvB,eAAe,GAChB,MAAM,YAAY,CAAC"}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-neutral, in-memory ability store + `can()` resolver for the front end.
|
|
3
|
+
*
|
|
4
|
+
* The store is hydrated from Inertia shared props (`props.auth.can`) and from any
|
|
5
|
+
* per-resource `can` maps a controller serialized onto a resource. `can(...)` then
|
|
6
|
+
* answers SYNCHRONOUSLY from the cache — no network request — and only falls back
|
|
7
|
+
* (configurable: fetch the `/authz/can` endpoint, or deny) when the ability/resource
|
|
8
|
+
* is genuinely unknown.
|
|
9
|
+
*
|
|
10
|
+
* No dependency on React/Vue/NestJS/Inertia — `-react`, `-inertia`, and the codegen
|
|
11
|
+
* client can all reuse this.
|
|
12
|
+
*
|
|
13
|
+
* @module store
|
|
14
|
+
*/
|
|
15
|
+
/** A flat `ability -> verdict` record. */
|
|
16
|
+
export type CanMap = Record<string, boolean>;
|
|
17
|
+
/** A resource identifiable by `type` + `id` (for keying per-instance maps). */
|
|
18
|
+
export interface ResourceRef {
|
|
19
|
+
type: string;
|
|
20
|
+
id?: string | number | null;
|
|
21
|
+
}
|
|
22
|
+
/** Inertia shared-props subset the store reads from. */
|
|
23
|
+
export interface HydratableProps {
|
|
24
|
+
auth?: {
|
|
25
|
+
can?: CanMap | null;
|
|
26
|
+
} | null;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Strategy when an ability/resource is NOT in the store. */
|
|
30
|
+
export type FallbackMode = 'deny' | 'fetch';
|
|
31
|
+
export interface AbilityStoreOptions {
|
|
32
|
+
/** Prop key the class-ability map nests under (matches the server's `propKey`). Default `'auth'`. */
|
|
33
|
+
propKey?: string;
|
|
34
|
+
/**
|
|
35
|
+
* What to do when `can(...)` is asked about an ability/resource not in the store.
|
|
36
|
+
* - `'deny'` (default): return `false` synchronously.
|
|
37
|
+
* - `'fetch'`: POST to {@link AbilityStoreOptions.endpoint} and resolve a Promise.
|
|
38
|
+
*/
|
|
39
|
+
fallback?: FallbackMode;
|
|
40
|
+
/** Endpoint the `'fetch'` fallback POSTs `{ ability, resource }` to. Default `'/authz/can'`. */
|
|
41
|
+
endpoint?: string;
|
|
42
|
+
/** Injectable fetch (for tests / non-browser runtimes). Defaults to global `fetch`. */
|
|
43
|
+
fetchImpl?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* In-memory store of class-level abilities + per-resource `can` maps.
|
|
47
|
+
*
|
|
48
|
+
* Class abilities are keyed by ability name; per-resource maps are keyed by
|
|
49
|
+
* `type#id` then ability name.
|
|
50
|
+
*/
|
|
51
|
+
export declare class AbilityStore {
|
|
52
|
+
private readonly classAbilities;
|
|
53
|
+
private readonly resourceAbilities;
|
|
54
|
+
/** Replace the class-level ability map. */
|
|
55
|
+
setClassAbilities(map: CanMap): this;
|
|
56
|
+
/** Merge additional class-level abilities (does not clear existing). */
|
|
57
|
+
mergeClassAbilities(map: CanMap): this;
|
|
58
|
+
/** Store a per-instance `can` map for a resource. */
|
|
59
|
+
setResourceAbilities(ref: ResourceRef, map: CanMap): this;
|
|
60
|
+
/** True when `ability` (optionally on `resource`) has a cached verdict. */
|
|
61
|
+
has(ability: string, resource?: ResourceRef): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Synchronous lookup. Returns the cached verdict, or `undefined` when unknown.
|
|
64
|
+
* Never performs I/O.
|
|
65
|
+
*/
|
|
66
|
+
peek(ability: string, resource?: ResourceRef): boolean | undefined;
|
|
67
|
+
/** Empty the store. */
|
|
68
|
+
clear(): this;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Hydrate `store` from Inertia shared props. Reads `props.<propKey>.can` for the
|
|
72
|
+
* class-level abilities. Per-resource maps are hydrated separately via
|
|
73
|
+
* {@link hydrateResource} (a resource's `can` lives on the serialized resource,
|
|
74
|
+
* whose `type`/`id` only the caller knows).
|
|
75
|
+
*/
|
|
76
|
+
export declare function hydrateFromInertiaProps(store: AbilityStore, props: HydratableProps | undefined | null, propKey?: string): AbilityStore;
|
|
77
|
+
/**
|
|
78
|
+
* Hydrate a single resource's per-instance `can` map (e.g. from a serialized
|
|
79
|
+
* `{ ...post, can }`). `ref` identifies the instance (`type#id`).
|
|
80
|
+
*/
|
|
81
|
+
export declare function hydrateResource(store: AbilityStore, ref: ResourceRef, can: CanMap | undefined | null): AbilityStore;
|
|
82
|
+
/**
|
|
83
|
+
* The resolver function returned by {@link createCan}. When the verdict is cached
|
|
84
|
+
* it returns a `boolean` SYNCHRONOUSLY; only on a cache miss with `fallback: 'fetch'`
|
|
85
|
+
* does it return a `Promise<boolean>`.
|
|
86
|
+
*/
|
|
87
|
+
export type CanResolver = (ability: string, resource?: ResourceRef) => boolean | Promise<boolean>;
|
|
88
|
+
/**
|
|
89
|
+
* Build a `can(ability, resource?)` bound to `store`.
|
|
90
|
+
*
|
|
91
|
+
* - **Cache hit** → returns the cached `boolean` synchronously (NO request).
|
|
92
|
+
* - **Cache miss, `fallback: 'deny'`** (default) → returns `false` synchronously.
|
|
93
|
+
* - **Cache miss, `fallback: 'fetch'`** → POSTs `{ ability, resource }` to the
|
|
94
|
+
* endpoint and returns a `Promise<boolean>` from `{ allowed }`.
|
|
95
|
+
*
|
|
96
|
+
* **Resource-bound decisions and the fetch fallback:** per-instance decisions
|
|
97
|
+
* (`can(ability, { type, id })`) MUST be hydrated via shared props /
|
|
98
|
+
* `authorizeResource` (tiers 1-2). The `POST /authz/can` fetch fallback only
|
|
99
|
+
* resolves class-level abilities and ad-hoc gates — the `{ type, id }` shim it
|
|
100
|
+
* sends never matches a `@Policy` by constructor, so a resource-bound ability
|
|
101
|
+
* that misses the cache will DENY. On such a miss this logs a one-time
|
|
102
|
+
* `console.warn` so the silent deny is debuggable.
|
|
103
|
+
*/
|
|
104
|
+
export declare function createCan(store: AbilityStore, options?: AbilityStoreOptions): CanResolver;
|
|
105
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE7C,+EAA+E;AAC/E,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,wDA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AMd;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,EACnB,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAC7B,YAAY,CAGd;AAED;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,WAAW,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAElG;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,GAAE,mBAAwB,GAAG,WAAW,CAoC7F"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-neutral, in-memory ability store + `can()` resolver for the front end.
|
|
3
|
+
*
|
|
4
|
+
* The store is hydrated from Inertia shared props (`props.auth.can`) and from any
|
|
5
|
+
* per-resource `can` maps a controller serialized onto a resource. `can(...)` then
|
|
6
|
+
* answers SYNCHRONOUSLY from the cache — no network request — and only falls back
|
|
7
|
+
* (configurable: fetch the `/authz/can` endpoint, or deny) when the ability/resource
|
|
8
|
+
* is genuinely unknown.
|
|
9
|
+
*
|
|
10
|
+
* No dependency on React/Vue/NestJS/Inertia — `-react`, `-inertia`, and the codegen
|
|
11
|
+
* client can all reuse this.
|
|
12
|
+
*
|
|
13
|
+
* @module store
|
|
14
|
+
*/
|
|
15
|
+
/** Build the cache key for a per-instance decision. */
|
|
16
|
+
function resourceKey(ref) {
|
|
17
|
+
return `${ref.type}#${ref.id ?? ''}`;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* In-memory store of class-level abilities + per-resource `can` maps.
|
|
21
|
+
*
|
|
22
|
+
* Class abilities are keyed by ability name; per-resource maps are keyed by
|
|
23
|
+
* `type#id` then ability name.
|
|
24
|
+
*/
|
|
25
|
+
export class AbilityStore {
|
|
26
|
+
classAbilities = {};
|
|
27
|
+
resourceAbilities = new Map();
|
|
28
|
+
/** Replace the class-level ability map. */
|
|
29
|
+
setClassAbilities(map) {
|
|
30
|
+
for (const k of Object.keys(this.classAbilities))
|
|
31
|
+
delete this.classAbilities[k];
|
|
32
|
+
Object.assign(this.classAbilities, map);
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
/** Merge additional class-level abilities (does not clear existing). */
|
|
36
|
+
mergeClassAbilities(map) {
|
|
37
|
+
Object.assign(this.classAbilities, map);
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
/** Store a per-instance `can` map for a resource. */
|
|
41
|
+
setResourceAbilities(ref, map) {
|
|
42
|
+
this.resourceAbilities.set(resourceKey(ref), { ...map });
|
|
43
|
+
return this;
|
|
44
|
+
}
|
|
45
|
+
/** True when `ability` (optionally on `resource`) has a cached verdict. */
|
|
46
|
+
has(ability, resource) {
|
|
47
|
+
if (resource) {
|
|
48
|
+
const map = this.resourceAbilities.get(resourceKey(resource));
|
|
49
|
+
return map !== undefined && map[ability] !== undefined;
|
|
50
|
+
}
|
|
51
|
+
return this.classAbilities[ability] !== undefined;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Synchronous lookup. Returns the cached verdict, or `undefined` when unknown.
|
|
55
|
+
* Never performs I/O.
|
|
56
|
+
*/
|
|
57
|
+
peek(ability, resource) {
|
|
58
|
+
if (resource) {
|
|
59
|
+
const map = this.resourceAbilities.get(resourceKey(resource));
|
|
60
|
+
return map?.[ability];
|
|
61
|
+
}
|
|
62
|
+
return this.classAbilities[ability];
|
|
63
|
+
}
|
|
64
|
+
/** Empty the store. */
|
|
65
|
+
clear() {
|
|
66
|
+
for (const k of Object.keys(this.classAbilities))
|
|
67
|
+
delete this.classAbilities[k];
|
|
68
|
+
this.resourceAbilities.clear();
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Hydrate `store` from Inertia shared props. Reads `props.<propKey>.can` for the
|
|
74
|
+
* class-level abilities. Per-resource maps are hydrated separately via
|
|
75
|
+
* {@link hydrateResource} (a resource's `can` lives on the serialized resource,
|
|
76
|
+
* whose `type`/`id` only the caller knows).
|
|
77
|
+
*/
|
|
78
|
+
export function hydrateFromInertiaProps(store, props, propKey = 'auth') {
|
|
79
|
+
const bag = props?.[propKey];
|
|
80
|
+
if (bag?.can)
|
|
81
|
+
store.mergeClassAbilities(bag.can);
|
|
82
|
+
return store;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Hydrate a single resource's per-instance `can` map (e.g. from a serialized
|
|
86
|
+
* `{ ...post, can }`). `ref` identifies the instance (`type#id`).
|
|
87
|
+
*/
|
|
88
|
+
export function hydrateResource(store, ref, can) {
|
|
89
|
+
if (can)
|
|
90
|
+
store.setResourceAbilities(ref, can);
|
|
91
|
+
return store;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Build a `can(ability, resource?)` bound to `store`.
|
|
95
|
+
*
|
|
96
|
+
* - **Cache hit** → returns the cached `boolean` synchronously (NO request).
|
|
97
|
+
* - **Cache miss, `fallback: 'deny'`** (default) → returns `false` synchronously.
|
|
98
|
+
* - **Cache miss, `fallback: 'fetch'`** → POSTs `{ ability, resource }` to the
|
|
99
|
+
* endpoint and returns a `Promise<boolean>` from `{ allowed }`.
|
|
100
|
+
*
|
|
101
|
+
* **Resource-bound decisions and the fetch fallback:** per-instance decisions
|
|
102
|
+
* (`can(ability, { type, id })`) MUST be hydrated via shared props /
|
|
103
|
+
* `authorizeResource` (tiers 1-2). The `POST /authz/can` fetch fallback only
|
|
104
|
+
* resolves class-level abilities and ad-hoc gates — the `{ type, id }` shim it
|
|
105
|
+
* sends never matches a `@Policy` by constructor, so a resource-bound ability
|
|
106
|
+
* that misses the cache will DENY. On such a miss this logs a one-time
|
|
107
|
+
* `console.warn` so the silent deny is debuggable.
|
|
108
|
+
*/
|
|
109
|
+
export function createCan(store, options = {}) {
|
|
110
|
+
const fallback = options.fallback ?? 'deny';
|
|
111
|
+
const endpoint = options.endpoint ?? '/authz/can';
|
|
112
|
+
let warnedResourceFetch = false;
|
|
113
|
+
return (ability, resource) => {
|
|
114
|
+
const cached = store.peek(ability, resource);
|
|
115
|
+
if (cached !== undefined)
|
|
116
|
+
return cached;
|
|
117
|
+
if (fallback === 'deny')
|
|
118
|
+
return false;
|
|
119
|
+
// A resource-bound ability that misses the cache cannot be resolved by the
|
|
120
|
+
// endpoint fallback (the {type,id} shim never matches a @Policy). Warn once.
|
|
121
|
+
if (resource && !warnedResourceFetch) {
|
|
122
|
+
warnedResourceFetch = true;
|
|
123
|
+
const id = JSON.stringify(resource.id ?? null);
|
|
124
|
+
console.warn(`[nestjs-authz] can('${ability}', { type: '${resource.type}', id: ${id} }) missed the cache and fell through to the '${endpoint}' fetch fallback, which cannot resolve per-instance policy decisions and will DENY. Hydrate resource decisions via shared props / authorizeResource (tiers 1-2) instead.`);
|
|
125
|
+
}
|
|
126
|
+
const doFetch = options.fetchImpl ?? globalThis.fetch;
|
|
127
|
+
if (typeof doFetch !== 'function')
|
|
128
|
+
return false;
|
|
129
|
+
return doFetch(endpoint, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
headers: { 'content-type': 'application/json' },
|
|
132
|
+
body: JSON.stringify({
|
|
133
|
+
ability,
|
|
134
|
+
resource: resource ? { type: resource.type, id: resource.id ?? null } : null,
|
|
135
|
+
}),
|
|
136
|
+
})
|
|
137
|
+
.then((res) => (res.ok ? res.json() : null))
|
|
138
|
+
.then((data) => data?.allowed === true)
|
|
139
|
+
.catch(() => false);
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAmCH,uDAAuD;AACvD,SAAS,WAAW,CAAC,GAAgB;IACnC,OAA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C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;aACtC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dudousxd/nestjs-authz-client",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Framework-neutral, in-memory ability store + can() resolver for @dudousxd/nestjs-authz — hydrate decisions once and answer client checks with no network request.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/DavideCarvalho/nestjs-authz.git",
|
|
9
|
+
"directory": "packages/client"
|
|
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
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^5.4.0",
|
|
29
|
+
"vitest": "^3.0.0"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=20"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"nestjs",
|
|
36
|
+
"authorization",
|
|
37
|
+
"authz",
|
|
38
|
+
"abilities",
|
|
39
|
+
"can",
|
|
40
|
+
"client"
|
|
41
|
+
],
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsc -p tsconfig.json",
|
|
44
|
+
"test": "vitest run --passWithNoTests",
|
|
45
|
+
"test:watch": "vitest",
|
|
46
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
47
|
+
}
|
|
48
|
+
}
|