@warlock.js/access 4.2.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 +13 -0
- package/LICENSE +21 -0
- package/README.md +76 -0
- package/cjs/index.cjs +367 -0
- package/cjs/index.cjs.map +1 -0
- package/esm/contracts/access-resolver.d.mts +40 -0
- package/esm/contracts/access-resolver.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +2 -0
- package/esm/contracts/types.d.mts +38 -0
- package/esm/contracts/types.d.mts.map +1 -0
- package/esm/index.d.mts +11 -0
- package/esm/index.mjs +12 -0
- package/esm/middleware/gate.middleware.d.mts +20 -0
- package/esm/middleware/gate.middleware.d.mts.map +1 -0
- package/esm/middleware/gate.middleware.mjs +44 -0
- package/esm/middleware/gate.middleware.mjs.map +1 -0
- package/esm/middleware/index.d.mts +1 -0
- package/esm/middleware/index.mjs +3 -0
- package/esm/services/access-config.d.mts +19 -0
- package/esm/services/access-config.d.mts.map +1 -0
- package/esm/services/access-config.mjs +50 -0
- package/esm/services/access-config.mjs.map +1 -0
- package/esm/services/access.d.mts +51 -0
- package/esm/services/access.d.mts.map +1 -0
- package/esm/services/access.mjs +80 -0
- package/esm/services/access.mjs.map +1 -0
- package/esm/services/default-resolver.d.mts +27 -0
- package/esm/services/default-resolver.d.mts.map +1 -0
- package/esm/services/default-resolver.mjs +35 -0
- package/esm/services/default-resolver.mjs.map +1 -0
- package/esm/services/engine.d.mts +8 -0
- package/esm/services/engine.d.mts.map +1 -0
- package/esm/services/engine.mjs +87 -0
- package/esm/services/engine.mjs.map +1 -0
- package/esm/services/index.d.mts +5 -0
- package/esm/services/index.mjs +7 -0
- package/esm/services/matcher.mjs +22 -0
- package/esm/services/matcher.mjs.map +1 -0
- package/esm/services/policies.d.mts +17 -0
- package/esm/services/policies.d.mts.map +1 -0
- package/esm/services/policies.mjs +25 -0
- package/esm/services/policies.mjs.map +1 -0
- package/esm/utils/access-config-error.d.mts +12 -0
- package/esm/utils/access-config-error.d.mts.map +1 -0
- package/esm/utils/access-config-error.mjs +16 -0
- package/esm/utils/access-config-error.mjs.map +1 -0
- package/esm/utils/access-error-codes.d.mts +13 -0
- package/esm/utils/access-error-codes.d.mts.map +1 -0
- package/esm/utils/access-error-codes.mjs +15 -0
- package/esm/utils/access-error-codes.mjs.map +1 -0
- package/llms-full.txt +470 -0
- package/llms.txt +14 -0
- package/package.json +43 -0
- package/skills/check-permissions/SKILL.md +71 -0
- package/skills/configure-access/SKILL.md +80 -0
- package/skills/define-policies/SKILL.md +68 -0
- package/skills/implement-resolver/SKILL.md +106 -0
- package/skills/manage-roles/SKILL.md +71 -0
- package/skills/overview/SKILL.md +44 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog — @warlock.js/access
|
|
2
|
+
|
|
3
|
+
All notable changes to `@warlock.js/access` are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## 4.2.0
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Shipped Warlock.js Access Package.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Hassan Zohdy
|
|
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,76 @@
|
|
|
1
|
+
# Warlock Access
|
|
2
|
+
|
|
3
|
+
Authorization (RBAC + ABAC) for [Warlock.js](https://github.com/warlockjs/core) applications — permission checks (`can` / `authorize` / `gate`), attribute-based `definePolicy` conditions, role checks, and a pluggable `AccessResolver` that connects the engine to however your app stores roles.
|
|
4
|
+
|
|
5
|
+
`@warlock.js/auth` answers _who you are_; `@warlock.js/access` answers _what you can do_.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx warlock add access
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
This ejects `src/config/access.ts`, a DB-backed `DatabaseAccessResolver`, the `Role` + `UserRole` tables, and registers the locale. `@warlock.js/access` reads `request.user`, so it lives inside a Warlock project alongside `@warlock.js/auth`.
|
|
14
|
+
|
|
15
|
+
## Configure
|
|
16
|
+
|
|
17
|
+
The resolver is the **one required piece** — it tells the engine how to read a user's roles + permissions. The ejected `DatabaseAccessResolver` reads roles from the `user_roles` table and maps them through the `roles` catalog table (so roles + their permissions are managed at runtime, in the DB):
|
|
18
|
+
|
|
19
|
+
```ts title="src/config/access.ts"
|
|
20
|
+
import { type AccessConfigurations } from "@warlock.js/access";
|
|
21
|
+
import { DatabaseAccessResolver } from "app/access/services/access-resolver";
|
|
22
|
+
|
|
23
|
+
const access: AccessConfigurations = {
|
|
24
|
+
resolver: new DatabaseAccessResolver(),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export default access;
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
For a fixed, code-defined catalog with no tables, swap in `DefaultAccessResolver` (reads `user.get("roles")` and maps through an inline map):
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { DefaultAccessResolver } from "@warlock.js/access";
|
|
34
|
+
|
|
35
|
+
const access: AccessConfigurations = {
|
|
36
|
+
resolver: new DefaultAccessResolver({ owner: ["*"], editor: ["orders.*"] }),
|
|
37
|
+
};
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
See the `configure-access` and `implement-resolver` skills for the full story.
|
|
41
|
+
|
|
42
|
+
## Use it
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { authMiddleware } from "@warlock.js/auth";
|
|
46
|
+
import { authorize, can, definePolicy, gate } from "@warlock.js/access";
|
|
47
|
+
|
|
48
|
+
// route gate (class-level)
|
|
49
|
+
router.post("/orders", createOrder, {
|
|
50
|
+
middleware: [authMiddleware([]), gate("orders.create")],
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// in a service (instance-level — runs the policy)
|
|
54
|
+
definePolicy("orders.update", (user, order) => order.get("customer_id") === user.id);
|
|
55
|
+
await authorize(user, "orders.update", { resource: order });
|
|
56
|
+
|
|
57
|
+
// boolean, anywhere
|
|
58
|
+
if (await can(user, "orders.viewCost")) { /* … */ }
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
> Register `definePolicy` calls per module, in `src/app/<module>/policies/`, loaded by an `import "./policies";` side-effect in that module's `main.ts` — a policy defined in an unimported module silently never registers.
|
|
62
|
+
|
|
63
|
+
## Documentation
|
|
64
|
+
|
|
65
|
+
Task-focused guides live under [`skills/`](./skills):
|
|
66
|
+
|
|
67
|
+
- **overview** — what the package does and the engine + resolver mental model
|
|
68
|
+
- **configure-access** — the required resolver (`DefaultAccessResolver` vs the ejected `DatabaseAccessResolver`), cache + tenant
|
|
69
|
+
- **check-permissions** — `can` / `authorize` / `gate` and friends
|
|
70
|
+
- **define-policies** — attribute conditions (ownership / tenant / state)
|
|
71
|
+
- **manage-roles** — assign / revoke via the ejected `UserRole` (auto-flushes), plus `hasRole` and out-of-band `access.flush`
|
|
72
|
+
- **implement-resolver** — connect the engine to your storage (DB catalog, column, pivot, token claim)
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT © Hasan Zohdy
|
package/cjs/index.cjs
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let _warlock_js_core = require("@warlock.js/core");
|
|
3
|
+
let _warlock_js_cache = require("@warlock.js/cache");
|
|
4
|
+
let _warlock_js_logger = require("@warlock.js/logger");
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/access/src/utils/access-error-codes.ts
|
|
7
|
+
/**
|
|
8
|
+
* Wire-stable error codes emitted by `@warlock.js/access`. Map these in your
|
|
9
|
+
* error transformer the way you map `AuthErrorCodes`. A value change here is a
|
|
10
|
+
* breaking change for any client that reacts to the code.
|
|
11
|
+
*/
|
|
12
|
+
let AccessErrorCodes = /* @__PURE__ */ function(AccessErrorCodes) {
|
|
13
|
+
/** EC100 — authenticated, but missing the required permission. */
|
|
14
|
+
AccessErrorCodes["Forbidden"] = "EC100";
|
|
15
|
+
return AccessErrorCodes;
|
|
16
|
+
}({});
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region ../@warlock.js/access/src/utils/access-config-error.ts
|
|
20
|
+
/**
|
|
21
|
+
* Thrown when `@warlock.js/access` is misconfigured (e.g. no resolver). Unlike a
|
|
22
|
+
* runtime resolution failure — which fails CLOSED (denies) — a config error is a
|
|
23
|
+
* developer mistake, so the engine re-throws it LOUD instead of silently denying.
|
|
24
|
+
*/
|
|
25
|
+
var AccessConfigError = class extends Error {
|
|
26
|
+
constructor(message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = "AccessConfigError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region ../@warlock.js/access/src/services/access-config.ts
|
|
34
|
+
/**
|
|
35
|
+
* The active configuration, fed once at boot by the framework's access connector
|
|
36
|
+
* via {@link setAccessConfig} (the connector reads `src/config/access.ts`).
|
|
37
|
+
* Reading it before it's set throws {@link AccessConfigError} — a loud
|
|
38
|
+
* misconfiguration, never a silent deny.
|
|
39
|
+
*/
|
|
40
|
+
let current;
|
|
41
|
+
/**
|
|
42
|
+
* Register the access configuration. The framework's access connector calls this
|
|
43
|
+
* at boot with the default export of `src/config/access.ts`. It validates that a
|
|
44
|
+
* `resolver` is present, so a misconfigured authorization layer fails at STARTUP
|
|
45
|
+
* rather than on the first protected request.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* setAccessConfig({ resolver: new DefaultAccessResolver({ admin: ["*"] }) });
|
|
49
|
+
*/
|
|
50
|
+
function setAccessConfig(configuration) {
|
|
51
|
+
if (!configuration?.resolver) throw new AccessConfigError("No access resolver configured. Set `resolver` in src/config/access.ts to a class implementing AccessResolver — the ejected DatabaseAccessResolver, or `new DefaultAccessResolver(rolesMap)` for a fixed-role catalog.");
|
|
52
|
+
current = configuration;
|
|
53
|
+
}
|
|
54
|
+
/** Clear the active config. Used by the connector on dev-restart and by tests. */
|
|
55
|
+
function resetAccessConfig() {
|
|
56
|
+
current = void 0;
|
|
57
|
+
}
|
|
58
|
+
/** Accessors over the active access configuration. */
|
|
59
|
+
const accessConfig = {
|
|
60
|
+
/**
|
|
61
|
+
* The configured resolver. Throws {@link AccessConfigError} if access was never
|
|
62
|
+
* configured (no `src/config/access.ts`, or the connector hasn't run).
|
|
63
|
+
*/
|
|
64
|
+
resolver() {
|
|
65
|
+
if (!current) throw new AccessConfigError("@warlock.js/access is not configured. Add src/config/access.ts (exporting a `resolver`) — it is wired at boot by the access connector.");
|
|
66
|
+
return current.resolver;
|
|
67
|
+
},
|
|
68
|
+
/** Cache TTL for resolved permission sets. */
|
|
69
|
+
cacheTtl() {
|
|
70
|
+
return current?.cache?.ttl ?? "10m";
|
|
71
|
+
},
|
|
72
|
+
/** Ambient tenant for this user, delegated to the resolver's optional hook. */
|
|
73
|
+
tenant(user) {
|
|
74
|
+
return this.resolver().resolveTenant?.(user);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region ../@warlock.js/access/src/services/matcher.ts
|
|
80
|
+
/**
|
|
81
|
+
* Whether a set of granted permission patterns covers a requested permission.
|
|
82
|
+
*
|
|
83
|
+
* Supports three forms:
|
|
84
|
+
* - exact — `"orders.update"` covers `"orders.update"`
|
|
85
|
+
* - global — `"*"` covers everything (the super-grant)
|
|
86
|
+
* - prefix wildcard — `"orders.*"` covers `"orders.update"` and `"orders.update.status"`
|
|
87
|
+
*
|
|
88
|
+
* `"orders.*"` does NOT cover the bare `"orders"` (no trailing segment).
|
|
89
|
+
*/
|
|
90
|
+
function matchesPermission(granted, permission) {
|
|
91
|
+
for (const pattern of granted) {
|
|
92
|
+
if (pattern === "*" || pattern === permission) return true;
|
|
93
|
+
if (pattern.endsWith(".*") && permission.startsWith(pattern.slice(0, -1))) return true;
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region ../@warlock.js/access/src/services/policies.ts
|
|
100
|
+
const policies = /* @__PURE__ */ new Map();
|
|
101
|
+
/**
|
|
102
|
+
* Register an ABAC condition for a permission. It runs ON TOP of the RBAC grant
|
|
103
|
+
* whenever an authorization check carries a `resource` — letting you express
|
|
104
|
+
* "...but only their own / only in their tenant / only while pending".
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* definePolicy("orders.update", (user, order) => order.get("customer_id") === user.id);
|
|
108
|
+
*/
|
|
109
|
+
function definePolicy(permission, policy) {
|
|
110
|
+
policies.set(permission, policy);
|
|
111
|
+
}
|
|
112
|
+
/** The policy registered for a permission, if any. */
|
|
113
|
+
function getPolicy(permission) {
|
|
114
|
+
return policies.get(permission);
|
|
115
|
+
}
|
|
116
|
+
/** Remove every registered policy. Primarily for tests. */
|
|
117
|
+
function clearPolicies() {
|
|
118
|
+
policies.clear();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region ../@warlock.js/access/src/services/engine.ts
|
|
123
|
+
const PERMISSIONS_PREFIX = "access.perms.";
|
|
124
|
+
const ROLES_PREFIX = "access.roles.";
|
|
125
|
+
/** Resolve the effective tenant for a check (explicit → ambient → undefined). */
|
|
126
|
+
function tenantFor(user, context) {
|
|
127
|
+
return context.tenant ?? accessConfig.tenant(user);
|
|
128
|
+
}
|
|
129
|
+
function cacheKey(prefix, user, tenant) {
|
|
130
|
+
const segment = (value) => encodeURIComponent(String(value));
|
|
131
|
+
return `${prefix}${segment(user.userType)}.${segment(user.id)}.${segment(tenant ?? "_")}`;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Read a list through the cache, falling back to the loader.
|
|
135
|
+
*
|
|
136
|
+
* The cache is **best-effort**: a cache failure degrades to the loader (the
|
|
137
|
+
* source of truth) and is logged, never denied. A loader failure propagates —
|
|
138
|
+
* so the DECISION fails closed in {@link check}.
|
|
139
|
+
*/
|
|
140
|
+
async function cached(key, loader) {
|
|
141
|
+
try {
|
|
142
|
+
const hit = await _warlock_js_cache.cache.get(key);
|
|
143
|
+
if (hit) return hit;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
_warlock_js_logger.log.error("access", "cache", error);
|
|
146
|
+
}
|
|
147
|
+
const value = await loader();
|
|
148
|
+
try {
|
|
149
|
+
await _warlock_js_cache.cache.set(key, value, { ttl: accessConfig.cacheTtl() });
|
|
150
|
+
} catch (error) {
|
|
151
|
+
_warlock_js_logger.log.error("access", "cache", error);
|
|
152
|
+
}
|
|
153
|
+
return value;
|
|
154
|
+
}
|
|
155
|
+
/** The user's effective permission set for a tenant (cached). */
|
|
156
|
+
function permissionsFor(user, tenant) {
|
|
157
|
+
return cached(cacheKey(PERMISSIONS_PREFIX, user, tenant), () => accessConfig.resolver().resolvePermissions(user, tenant));
|
|
158
|
+
}
|
|
159
|
+
/** The user's roles for a tenant (cached). */
|
|
160
|
+
function rolesFor(user, tenant) {
|
|
161
|
+
return cached(cacheKey(ROLES_PREFIX, user, tenant), () => accessConfig.resolver().resolveRoles(user, tenant));
|
|
162
|
+
}
|
|
163
|
+
/** Drop the cached role/permission sets for a user (after any out-of-band role change). */
|
|
164
|
+
async function flush(user, tenant) {
|
|
165
|
+
try {
|
|
166
|
+
await _warlock_js_cache.cache.remove(cacheKey(PERMISSIONS_PREFIX, user, tenant));
|
|
167
|
+
await _warlock_js_cache.cache.remove(cacheKey(ROLES_PREFIX, user, tenant));
|
|
168
|
+
} catch (error) {
|
|
169
|
+
_warlock_js_logger.log.error("access", "cache", error);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The core decision: does the user hold `permission`, and — when a `resource`
|
|
174
|
+
* is supplied — does its policy pass too?
|
|
175
|
+
*
|
|
176
|
+
* Fails CLOSED: any error while resolving the decision denies (and logs).
|
|
177
|
+
*/
|
|
178
|
+
async function check(user, permission, context = {}) {
|
|
179
|
+
try {
|
|
180
|
+
const tenant = tenantFor(user, context);
|
|
181
|
+
const permissions = await permissionsFor(user, tenant);
|
|
182
|
+
if (!matchesPermission(permissions, permission)) return false;
|
|
183
|
+
const policy = getPolicy(permission);
|
|
184
|
+
if (policy === void 0 || context.resource === void 0) return true;
|
|
185
|
+
const roles = await rolesFor(user, tenant);
|
|
186
|
+
return Boolean(await policy(user, context.resource, {
|
|
187
|
+
...context,
|
|
188
|
+
tenant,
|
|
189
|
+
hasRole: (role) => roles.includes(role),
|
|
190
|
+
hasPermission: (perm) => matchesPermission(permissions, perm)
|
|
191
|
+
}));
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (error instanceof AccessConfigError) throw error;
|
|
194
|
+
_warlock_js_logger.log.error("access", "check", error);
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region ../@warlock.js/access/src/services/access.ts
|
|
201
|
+
/** Whether the user holds `permission` (and passes its policy when a resource is given). */
|
|
202
|
+
function can(user, permission, context) {
|
|
203
|
+
return check(user, permission, context);
|
|
204
|
+
}
|
|
205
|
+
/** Inverse of {@link can}. */
|
|
206
|
+
async function cannot(user, permission, context) {
|
|
207
|
+
return !await can(user, permission, context);
|
|
208
|
+
}
|
|
209
|
+
/** Whether the user holds EVERY listed permission. Short-circuits on the first miss. */
|
|
210
|
+
async function canAll(user, permissions, context) {
|
|
211
|
+
for (const permission of permissions) if (!await can(user, permission, context)) return false;
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
/** Whether the user holds ANY listed permission. Short-circuits on the first hit. */
|
|
215
|
+
async function canAny(user, permissions, context) {
|
|
216
|
+
for (const permission of permissions) if (await can(user, permission, context)) return true;
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
function forbidden() {
|
|
220
|
+
throw new _warlock_js_core.ForbiddenError((0, _warlock_js_core.t)("access.errors.forbidden"), { errorCode: "EC100" });
|
|
221
|
+
}
|
|
222
|
+
/** Assert the user holds `permission`; throw `ForbiddenError` (403) otherwise. */
|
|
223
|
+
async function authorize(user, permission, context) {
|
|
224
|
+
if (!await can(user, permission, context)) forbidden();
|
|
225
|
+
}
|
|
226
|
+
/** Assert the user holds EVERY listed permission; throw otherwise. */
|
|
227
|
+
async function authorizeAll(user, permissions, context) {
|
|
228
|
+
if (!await canAll(user, permissions, context)) forbidden();
|
|
229
|
+
}
|
|
230
|
+
/** Assert the user holds ANY listed permission; throw otherwise. */
|
|
231
|
+
async function authorizeAny(user, permissions, context) {
|
|
232
|
+
if (!await canAny(user, permissions, context)) forbidden();
|
|
233
|
+
}
|
|
234
|
+
/** Whether the user has the given role. */
|
|
235
|
+
async function hasRole(user, role, tenant) {
|
|
236
|
+
return (await rolesFor(user, tenant)).includes(role);
|
|
237
|
+
}
|
|
238
|
+
/** Whether the user has ANY of the given roles. */
|
|
239
|
+
async function hasAnyRole(user, roles, tenant) {
|
|
240
|
+
const held = await rolesFor(user, tenant);
|
|
241
|
+
return roles.some((role) => held.includes(role));
|
|
242
|
+
}
|
|
243
|
+
/** Whether the user has ALL of the given roles. */
|
|
244
|
+
async function hasAllRoles(user, roles, tenant) {
|
|
245
|
+
const held = await rolesFor(user, tenant);
|
|
246
|
+
return roles.every((role) => held.includes(role));
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The access facade — every check plus `flush` to drop a user's cached set.
|
|
250
|
+
* Role assignment lives on the ejected `UserRole` model in app-land; callers do
|
|
251
|
+
* `UserRole.assign(...)` then `access.flush(user, tenant)`.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* import { access } from "@warlock.js/access";
|
|
255
|
+
* if (await access.can(user, "orders.update", { resource: order })) { ... }
|
|
256
|
+
* await access.flush(user, "tenant-1");
|
|
257
|
+
*/
|
|
258
|
+
const access = {
|
|
259
|
+
can,
|
|
260
|
+
cannot,
|
|
261
|
+
canAll,
|
|
262
|
+
canAny,
|
|
263
|
+
authorize,
|
|
264
|
+
authorizeAll,
|
|
265
|
+
authorizeAny,
|
|
266
|
+
hasRole,
|
|
267
|
+
hasAnyRole,
|
|
268
|
+
hasAllRoles,
|
|
269
|
+
/** Drop the user's cached role/permission set (call after you mutate role rows). */
|
|
270
|
+
flush
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region ../@warlock.js/access/src/middleware/gate.middleware.ts
|
|
275
|
+
function deny(response) {
|
|
276
|
+
return response.forbidden({
|
|
277
|
+
error: (0, _warlock_js_core.t)("access.errors.forbidden"),
|
|
278
|
+
errorCode: "EC100"
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Gate a route on a single permission (class-level). Stack it AFTER
|
|
283
|
+
* `authMiddleware`, which sets `request.user`.
|
|
284
|
+
*
|
|
285
|
+
* @example
|
|
286
|
+
* router.post("/orders", createOrder, {
|
|
287
|
+
* middleware: [authMiddleware([]), gate("orders.create")],
|
|
288
|
+
* });
|
|
289
|
+
*/
|
|
290
|
+
function gate(permission) {
|
|
291
|
+
return async (request, response) => {
|
|
292
|
+
if (!request.user) return deny(response);
|
|
293
|
+
if (!await can(request.user, permission)) return deny(response);
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/** Gate a route on holding ANY of the listed permissions. */
|
|
297
|
+
function gateAny(permissions) {
|
|
298
|
+
return async (request, response) => {
|
|
299
|
+
if (!request.user) return deny(response);
|
|
300
|
+
if (!await canAny(request.user, permissions)) return deny(response);
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/** Gate a route on holding ALL of the listed permissions. */
|
|
304
|
+
function gateAll(permissions) {
|
|
305
|
+
return async (request, response) => {
|
|
306
|
+
if (!request.user) return deny(response);
|
|
307
|
+
if (!await canAll(request.user, permissions)) return deny(response);
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
//#endregion
|
|
312
|
+
//#region ../@warlock.js/access/src/services/default-resolver.ts
|
|
313
|
+
/** Coerce a roles value (`undefined` / single string / array) into a string array. */
|
|
314
|
+
function toRoleList(value) {
|
|
315
|
+
if (Array.isArray(value)) return value;
|
|
316
|
+
if (typeof value === "string" && value.length > 0) return [value];
|
|
317
|
+
return [];
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* The zero-config resolver: reads a user's roles from a model field and maps
|
|
321
|
+
* them to permissions through your `roles` catalog. Works out of the box for
|
|
322
|
+
* both a `roles` array column and a single `role` column.
|
|
323
|
+
*
|
|
324
|
+
* Swap `readRoles` to read from anywhere else (a relation, a token claim); for
|
|
325
|
+
* a different storage shape entirely, implement {@link AccessResolver} directly.
|
|
326
|
+
*
|
|
327
|
+
* @example
|
|
328
|
+
* new DefaultAccessResolver({ editor: ["orders.*"], viewer: ["orders.view"] });
|
|
329
|
+
* new DefaultAccessResolver(rolesMap, (user) => user.get("memberRoles"));
|
|
330
|
+
*/
|
|
331
|
+
var DefaultAccessResolver = class {
|
|
332
|
+
constructor(roles, readRoles = (user) => user.get("roles") ?? user.get("role")) {
|
|
333
|
+
this.roles = roles;
|
|
334
|
+
this.readRoles = readRoles;
|
|
335
|
+
}
|
|
336
|
+
async resolveRoles(user) {
|
|
337
|
+
return toRoleList(await this.readRoles(user));
|
|
338
|
+
}
|
|
339
|
+
async resolvePermissions(user) {
|
|
340
|
+
return (await this.resolveRoles(user)).flatMap((role) => Object.prototype.hasOwnProperty.call(this.roles, role) ? this.roles[role] : []);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
//#endregion
|
|
345
|
+
exports.AccessConfigError = AccessConfigError;
|
|
346
|
+
exports.AccessErrorCodes = AccessErrorCodes;
|
|
347
|
+
exports.DefaultAccessResolver = DefaultAccessResolver;
|
|
348
|
+
exports.access = access;
|
|
349
|
+
exports.authorize = authorize;
|
|
350
|
+
exports.authorizeAll = authorizeAll;
|
|
351
|
+
exports.authorizeAny = authorizeAny;
|
|
352
|
+
exports.can = can;
|
|
353
|
+
exports.canAll = canAll;
|
|
354
|
+
exports.canAny = canAny;
|
|
355
|
+
exports.cannot = cannot;
|
|
356
|
+
exports.clearPolicies = clearPolicies;
|
|
357
|
+
exports.definePolicy = definePolicy;
|
|
358
|
+
exports.flush = flush;
|
|
359
|
+
exports.gate = gate;
|
|
360
|
+
exports.gateAll = gateAll;
|
|
361
|
+
exports.gateAny = gateAny;
|
|
362
|
+
exports.hasAllRoles = hasAllRoles;
|
|
363
|
+
exports.hasAnyRole = hasAnyRole;
|
|
364
|
+
exports.hasRole = hasRole;
|
|
365
|
+
exports.resetAccessConfig = resetAccessConfig;
|
|
366
|
+
exports.setAccessConfig = setAccessConfig;
|
|
367
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["cache","ForbiddenError","flushUser"],"sources":["../../../../../../@warlock.js/access/src/utils/access-error-codes.ts","../../../../../../@warlock.js/access/src/utils/access-config-error.ts","../../../../../../@warlock.js/access/src/services/access-config.ts","../../../../../../@warlock.js/access/src/services/matcher.ts","../../../../../../@warlock.js/access/src/services/policies.ts","../../../../../../@warlock.js/access/src/services/engine.ts","../../../../../../@warlock.js/access/src/services/access.ts","../../../../../../@warlock.js/access/src/middleware/gate.middleware.ts","../../../../../../@warlock.js/access/src/services/default-resolver.ts"],"sourcesContent":["/**\n * Wire-stable error codes emitted by `@warlock.js/access`. Map these in your\n * error transformer the way you map `AuthErrorCodes`. A value change here is a\n * breaking change for any client that reacts to the code.\n */\nexport enum AccessErrorCodes {\n /** EC100 — authenticated, but missing the required permission. */\n Forbidden = \"EC100\",\n}\n","/**\n * Thrown when `@warlock.js/access` is misconfigured (e.g. no resolver). Unlike a\n * runtime resolution failure — which fails CLOSED (denies) — a config error is a\n * developer mistake, so the engine re-throws it LOUD instead of silently denying.\n */\nexport class AccessConfigError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"AccessConfigError\";\n }\n}\n","import type { Auth } from \"@warlock.js/auth\";\nimport type { AccessResolver } from \"../contracts/access-resolver\";\nimport type { AccessConfigurations } from \"../contracts/types\";\nimport { AccessConfigError } from \"../utils/access-config-error\";\n\n/**\n * The active configuration, fed once at boot by the framework's access connector\n * via {@link setAccessConfig} (the connector reads `src/config/access.ts`).\n * Reading it before it's set throws {@link AccessConfigError} — a loud\n * misconfiguration, never a silent deny.\n */\nlet current: AccessConfigurations | undefined;\n\n/**\n * Register the access configuration. The framework's access connector calls this\n * at boot with the default export of `src/config/access.ts`. It validates that a\n * `resolver` is present, so a misconfigured authorization layer fails at STARTUP\n * rather than on the first protected request.\n *\n * @example\n * setAccessConfig({ resolver: new DefaultAccessResolver({ admin: [\"*\"] }) });\n */\nexport function setAccessConfig(configuration: AccessConfigurations): void {\n if (!configuration?.resolver) {\n throw new AccessConfigError(\n \"No access resolver configured. Set `resolver` in src/config/access.ts to a class \" +\n \"implementing AccessResolver — the ejected DatabaseAccessResolver, or \" +\n \"`new DefaultAccessResolver(rolesMap)` for a fixed-role catalog.\",\n );\n }\n\n current = configuration;\n}\n\n/** Clear the active config. Used by the connector on dev-restart and by tests. */\nexport function resetAccessConfig(): void {\n current = undefined;\n}\n\n/** Accessors over the active access configuration. */\nexport const accessConfig = {\n /**\n * The configured resolver. Throws {@link AccessConfigError} if access was never\n * configured (no `src/config/access.ts`, or the connector hasn't run).\n */\n resolver(): AccessResolver {\n if (!current) {\n throw new AccessConfigError(\n \"@warlock.js/access is not configured. Add src/config/access.ts (exporting a `resolver`) \" +\n \"— it is wired at boot by the access connector.\",\n );\n }\n\n return current.resolver;\n },\n\n /** Cache TTL for resolved permission sets. */\n cacheTtl(): string | number {\n return current?.cache?.ttl ?? \"10m\";\n },\n\n /** Ambient tenant for this user, delegated to the resolver's optional hook. */\n tenant(user: Auth): string | undefined {\n return this.resolver().resolveTenant?.(user);\n },\n};\n","/**\n * Whether a set of granted permission patterns covers a requested permission.\n *\n * Supports three forms:\n * - exact — `\"orders.update\"` covers `\"orders.update\"`\n * - global — `\"*\"` covers everything (the super-grant)\n * - prefix wildcard — `\"orders.*\"` covers `\"orders.update\"` and `\"orders.update.status\"`\n *\n * `\"orders.*\"` does NOT cover the bare `\"orders\"` (no trailing segment).\n */\nexport function matchesPermission(granted: string[], permission: string): boolean {\n for (const pattern of granted) {\n if (pattern === \"*\" || pattern === permission) {\n return true;\n }\n\n // \"orders.*\" → prefix \"orders.\" — matches any nested permission.\n if (pattern.endsWith(\".*\") && permission.startsWith(pattern.slice(0, -1))) {\n return true;\n }\n }\n\n return false;\n}\n","import type { PolicyFn } from \"../contracts/types\";\n\nconst policies = new Map<string, PolicyFn>();\n\n/**\n * Register an ABAC condition for a permission. It runs ON TOP of the RBAC grant\n * whenever an authorization check carries a `resource` — letting you express\n * \"...but only their own / only in their tenant / only while pending\".\n *\n * @example\n * definePolicy(\"orders.update\", (user, order) => order.get(\"customer_id\") === user.id);\n */\nexport function definePolicy(permission: string, policy: PolicyFn): void {\n policies.set(permission, policy);\n}\n\n/** The policy registered for a permission, if any. */\nexport function getPolicy(permission: string): PolicyFn | undefined {\n return policies.get(permission);\n}\n\n/** Remove every registered policy. Primarily for tests. */\nexport function clearPolicies(): void {\n policies.clear();\n}\n","import type { Auth } from \"@warlock.js/auth\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { AccessContext } from \"../contracts/types\";\nimport { AccessConfigError } from \"../utils/access-config-error\";\nimport { accessConfig } from \"./access-config\";\nimport { matchesPermission } from \"./matcher\";\nimport { getPolicy } from \"./policies\";\n\nconst PERMISSIONS_PREFIX = \"access.perms.\";\nconst ROLES_PREFIX = \"access.roles.\";\n\n/** Resolve the effective tenant for a check (explicit → ambient → undefined). */\nfunction tenantFor(user: Auth, context: AccessContext): string | undefined {\n return context.tenant ?? accessConfig.tenant(user);\n}\n\nfunction cacheKey(prefix: string, user: Auth, tenant?: string): string {\n // Encode each segment so a `.` in an id or tenant can't collide two distinct\n // principals onto the same cache key (and serve one's grants to the other).\n const segment = (value: unknown) => encodeURIComponent(String(value));\n\n return `${prefix}${segment(user.userType)}.${segment(user.id)}.${segment(tenant ?? \"_\")}`;\n}\n\n/**\n * Read a list through the cache, falling back to the loader.\n *\n * The cache is **best-effort**: a cache failure degrades to the loader (the\n * source of truth) and is logged, never denied. A loader failure propagates —\n * so the DECISION fails closed in {@link check}.\n */\nasync function cached(\n key: string,\n loader: () => Promise<string[]>,\n): Promise<string[]> {\n try {\n const hit = await cache.get<string[]>(key);\n\n if (hit) return hit;\n } catch (error) {\n log.error(\"access\", \"cache\", error);\n }\n\n const value = await loader();\n\n try {\n await cache.set(key, value, { ttl: accessConfig.cacheTtl() });\n } catch (error) {\n log.error(\"access\", \"cache\", error);\n }\n\n return value;\n}\n\n/** The user's effective permission set for a tenant (cached). */\nexport function permissionsFor(user: Auth, tenant?: string): Promise<string[]> {\n return cached(cacheKey(PERMISSIONS_PREFIX, user, tenant), () =>\n accessConfig.resolver().resolvePermissions(user, tenant),\n );\n}\n\n/** The user's roles for a tenant (cached). */\nexport function rolesFor(user: Auth, tenant?: string): Promise<string[]> {\n return cached(cacheKey(ROLES_PREFIX, user, tenant), () =>\n accessConfig.resolver().resolveRoles(user, tenant),\n );\n}\n\n/** Drop the cached role/permission sets for a user (after any out-of-band role change). */\nexport async function flush(user: Auth, tenant?: string): Promise<void> {\n try {\n await cache.remove(cacheKey(PERMISSIONS_PREFIX, user, tenant));\n await cache.remove(cacheKey(ROLES_PREFIX, user, tenant));\n } catch (error) {\n log.error(\"access\", \"cache\", error);\n }\n}\n\n/**\n * The core decision: does the user hold `permission`, and — when a `resource`\n * is supplied — does its policy pass too?\n *\n * Fails CLOSED: any error while resolving the decision denies (and logs).\n */\nexport async function check(\n user: Auth,\n permission: string,\n context: AccessContext = {},\n): Promise<boolean> {\n try {\n const tenant = tenantFor(user, context);\n const permissions = await permissionsFor(user, tenant);\n\n if (!matchesPermission(permissions, permission)) return false;\n\n const policy = getPolicy(permission);\n\n // A policy only runs on an instance check (a resource was supplied);\n // class-level checks (`gate`) stop at the grant.\n if (policy === undefined || context.resource === undefined) return true;\n\n const roles = await rolesFor(user, tenant);\n\n return Boolean(\n await policy(user, context.resource, {\n ...context,\n tenant,\n hasRole: (role) => roles.includes(role),\n hasPermission: (perm) => matchesPermission(permissions, perm),\n }),\n );\n } catch (error) {\n if (error instanceof AccessConfigError) throw error; // misconfig is loud, not a silent deny\n\n log.error(\"access\", \"check\", error);\n\n return false;\n }\n}\n","import type { Auth } from \"@warlock.js/auth\";\nimport { ForbiddenError, t } from \"@warlock.js/core\";\nimport type { AccessContext } from \"../contracts/types\";\nimport { AccessErrorCodes } from \"../utils/access-error-codes\";\nimport { check, flush as flushUser, rolesFor } from \"./engine\";\n\n/** Whether the user holds `permission` (and passes its policy when a resource is given). */\nexport function can(\n user: Auth,\n permission: string,\n context?: AccessContext,\n): Promise<boolean> {\n return check(user, permission, context);\n}\n\n/** Inverse of {@link can}. */\nexport async function cannot(\n user: Auth,\n permission: string,\n context?: AccessContext,\n): Promise<boolean> {\n return !(await can(user, permission, context));\n}\n\n/** Whether the user holds EVERY listed permission. Short-circuits on the first miss. */\nexport async function canAll(\n user: Auth,\n permissions: string[],\n context?: AccessContext,\n): Promise<boolean> {\n for (const permission of permissions) {\n if (!(await can(user, permission, context))) return false;\n }\n\n return true;\n}\n\n/** Whether the user holds ANY listed permission. Short-circuits on the first hit. */\nexport async function canAny(\n user: Auth,\n permissions: string[],\n context?: AccessContext,\n): Promise<boolean> {\n for (const permission of permissions) {\n if (await can(user, permission, context)) return true;\n }\n\n return false;\n}\n\nfunction forbidden(): never {\n throw new ForbiddenError(t(\"access.errors.forbidden\"), {\n errorCode: AccessErrorCodes.Forbidden,\n });\n}\n\n/** Assert the user holds `permission`; throw `ForbiddenError` (403) otherwise. */\nexport async function authorize(\n user: Auth,\n permission: string,\n context?: AccessContext,\n): Promise<void> {\n if (!(await can(user, permission, context))) forbidden();\n}\n\n/** Assert the user holds EVERY listed permission; throw otherwise. */\nexport async function authorizeAll(\n user: Auth,\n permissions: string[],\n context?: AccessContext,\n): Promise<void> {\n if (!(await canAll(user, permissions, context))) forbidden();\n}\n\n/** Assert the user holds ANY listed permission; throw otherwise. */\nexport async function authorizeAny(\n user: Auth,\n permissions: string[],\n context?: AccessContext,\n): Promise<void> {\n if (!(await canAny(user, permissions, context))) forbidden();\n}\n\n/** Whether the user has the given role. */\nexport async function hasRole(\n user: Auth,\n role: string,\n tenant?: string,\n): Promise<boolean> {\n return (await rolesFor(user, tenant)).includes(role);\n}\n\n/** Whether the user has ANY of the given roles. */\nexport async function hasAnyRole(\n user: Auth,\n roles: string[],\n tenant?: string,\n): Promise<boolean> {\n const held = await rolesFor(user, tenant);\n\n return roles.some((role) => held.includes(role));\n}\n\n/** Whether the user has ALL of the given roles. */\nexport async function hasAllRoles(\n user: Auth,\n roles: string[],\n tenant?: string,\n): Promise<boolean> {\n const held = await rolesFor(user, tenant);\n\n return roles.every((role) => held.includes(role));\n}\n\n/**\n * The access facade — every check plus `flush` to drop a user's cached set.\n * Role assignment lives on the ejected `UserRole` model in app-land; callers do\n * `UserRole.assign(...)` then `access.flush(user, tenant)`.\n *\n * @example\n * import { access } from \"@warlock.js/access\";\n * if (await access.can(user, \"orders.update\", { resource: order })) { ... }\n * await access.flush(user, \"tenant-1\");\n */\nexport const access = {\n can,\n cannot,\n canAll,\n canAny,\n authorize,\n authorizeAll,\n authorizeAny,\n hasRole,\n hasAnyRole,\n hasAllRoles,\n /** Drop the user's cached role/permission set (call after you mutate role rows). */\n flush: flushUser,\n};\n","import { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { can, canAll, canAny } from \"../services/access\";\nimport { AccessErrorCodes } from \"../utils/access-error-codes\";\n\nfunction deny(response: Response) {\n return response.forbidden({\n error: t(\"access.errors.forbidden\"),\n errorCode: AccessErrorCodes.Forbidden,\n });\n}\n\n/**\n * Gate a route on a single permission (class-level). Stack it AFTER\n * `authMiddleware`, which sets `request.user`.\n *\n * @example\n * router.post(\"/orders\", createOrder, {\n * middleware: [authMiddleware([]), gate(\"orders.create\")],\n * });\n */\nexport function gate(permission: string): Middleware {\n return async (request: Request, response: Response) => {\n if (!request.user) return deny(response);\n\n if (!(await can(request.user, permission))) return deny(response);\n };\n}\n\n/** Gate a route on holding ANY of the listed permissions. */\nexport function gateAny(permissions: string[]): Middleware {\n return async (request: Request, response: Response) => {\n if (!request.user) return deny(response);\n\n if (!(await canAny(request.user, permissions))) return deny(response);\n };\n}\n\n/** Gate a route on holding ALL of the listed permissions. */\nexport function gateAll(permissions: string[]): Middleware {\n return async (request: Request, response: Response) => {\n if (!request.user) return deny(response);\n\n if (!(await canAll(request.user, permissions))) return deny(response);\n };\n}\n","import type { Auth } from \"@warlock.js/auth\";\nimport type { AccessResolver } from \"../contracts/access-resolver\";\nimport type { RolesMap } from \"../contracts/types\";\n\n/** Coerce a roles value (`undefined` / single string / array) into a string array. */\nfunction toRoleList(value: unknown): string[] {\n if (Array.isArray(value)) return value as string[];\n\n if (typeof value === \"string\" && value.length > 0) return [value];\n\n return [];\n}\n\n/**\n * The zero-config resolver: reads a user's roles from a model field and maps\n * them to permissions through your `roles` catalog. Works out of the box for\n * both a `roles` array column and a single `role` column.\n *\n * Swap `readRoles` to read from anywhere else (a relation, a token claim); for\n * a different storage shape entirely, implement {@link AccessResolver} directly.\n *\n * @example\n * new DefaultAccessResolver({ editor: [\"orders.*\"], viewer: [\"orders.view\"] });\n * new DefaultAccessResolver(rolesMap, (user) => user.get(\"memberRoles\"));\n */\nexport class DefaultAccessResolver implements AccessResolver {\n public constructor(\n private readonly roles: RolesMap,\n private readonly readRoles: (user: Auth) => unknown = (user) =>\n user.get(\"roles\") ?? user.get(\"role\"),\n ) {}\n\n public async resolveRoles(user: Auth): Promise<string[]> {\n return toRoleList(await this.readRoles(user));\n }\n\n public async resolvePermissions(user: Auth): Promise<string[]> {\n const roles = await this.resolveRoles(user);\n\n // Guard against a role named `__proto__` / `constructor` resolving to an\n // inherited (non-array) value.\n return roles.flatMap((role) =>\n Object.prototype.hasOwnProperty.call(this.roles, role)\n ? this.roles[role]\n : [],\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AAKA,IAAY,mBAAL;;CAEL;;AACF;;;;;;;;;ACHA,IAAa,oBAAb,cAAuC,MAAM;CAC3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;;;;;;;;;;;;AAcA,IAAa,wBAAb,MAA6D;CAC3D,AAAO,YACL,AAAiB,OACjB,AAAiB,aAAsC,SACrD,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,MAAM,GACtC;EAHiB;EACA;CAEhB;CAEH,MAAa,aAAa,MAA+B;EACvD,OAAO,WAAW,MAAM,KAAK,UAAU,IAAI,CAAC;CAC9C;CAEA,MAAa,mBAAmB,MAA+B;EAK7D,QAAO,MAJa,KAAK,aAAa,IAAI,EAI9B,CAAC,SAAS,SACpB,OAAO,UAAU,eAAe,KAAK,KAAK,OAAO,IAAI,IACjD,KAAK,MAAM,QACX,CAAC,CACP;CACF;AACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Auth } from "@warlock.js/auth";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/access/src/contracts/access-resolver.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The one adapter the engine depends on. Implement it to connect the engine to
|
|
6
|
+
* however YOUR app stores roles and permissions — a user column, a pivot table,
|
|
7
|
+
* a token claim, an external directory.
|
|
8
|
+
*
|
|
9
|
+
* The engine owns the hard parts (wildcard matching, caching, policies,
|
|
10
|
+
* fail-closed); the resolver only fetches. Keep it dumb — never cache inside it.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* export class AppAccessResolver implements AccessResolver {
|
|
14
|
+
* public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {
|
|
15
|
+
* const rows = await UserRole.query().where({ user_id: user.id, tenant: tenant ?? null }).get();
|
|
16
|
+
* return rows.map((row) => row.get("role") as string);
|
|
17
|
+
* }
|
|
18
|
+
* public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {
|
|
19
|
+
* const names = await this.resolveRoles(user, tenant);
|
|
20
|
+
* const roles = await Role.query().whereIn("name", names).get();
|
|
21
|
+
* return roles.flatMap((role) => role.get("permissions") as string[]);
|
|
22
|
+
* }
|
|
23
|
+
* }
|
|
24
|
+
*/
|
|
25
|
+
interface AccessResolver {
|
|
26
|
+
/** The role names this user holds (powers `hasRole` / `hasAnyRole`). */
|
|
27
|
+
resolveRoles(user: Auth, tenant?: string): Promise<string[]>;
|
|
28
|
+
/** The effective permission strings this user has (powers `can` / `authorize`). */
|
|
29
|
+
resolvePermissions(user: Auth, tenant?: string): Promise<string[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Optional. The ambient tenant for this user when a check doesn't pass one
|
|
32
|
+
* explicitly — commonly derived from the user (e.g. `user.get("organization_id")`),
|
|
33
|
+
* which is safer than trusting client-supplied request input. Return `undefined`
|
|
34
|
+
* for single-tenant apps.
|
|
35
|
+
*/
|
|
36
|
+
resolveTenant?(user: Auth): string | undefined;
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
export { AccessResolver };
|
|
40
|
+
//# sourceMappingURL=access-resolver.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"access-resolver.d.mts","names":[],"sources":["../../../../../../../@warlock.js/access/src/contracts/access-resolver.ts"],"mappings":";;;;;AAuBA;;;;;;;;;;;;;;;;;;;UAAiB,cAAA;EAaf;EAXA,YAAA,CAAa,IAAA,EAAM,IAAA,EAAM,MAAA,YAAkB,OAAA;EAW5B;EARf,kBAAA,CAAmB,IAAA,EAAM,IAAA,EAAM,MAAA,YAAkB,OAAA;EAQxB;;;;;;EAAzB,aAAA,EAAe,IAAA,EAAM,IAAA;AAAA"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { AccessResolver } from "./access-resolver.mjs";
|
|
2
|
+
import { Auth } from "@warlock.js/auth";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/access/src/contracts/types.d.ts
|
|
5
|
+
/** A role name mapped to the permission strings it grants. */
|
|
6
|
+
type RolesMap = Record<string, string[]>;
|
|
7
|
+
/**
|
|
8
|
+
* Extra context for an authorization check. `resource` and `tenant` are
|
|
9
|
+
* **reserved** (the engine acts on them); every other key is forwarded to the
|
|
10
|
+
* policy verbatim.
|
|
11
|
+
*/
|
|
12
|
+
type AccessContext = {
|
|
13
|
+
/** The object being authorized. Its presence is what enables the ABAC policy. */resource?: unknown; /** Tenant scope. Defaults to the resolver's optional `resolveTenant()`. */
|
|
14
|
+
tenant?: string;
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
};
|
|
17
|
+
/** The context a policy receives — the access context plus engine-injected helpers. */
|
|
18
|
+
type PolicyContext = AccessContext & {
|
|
19
|
+
tenant?: string; /** Whether the user holds the given role (in the resolved tenant). */
|
|
20
|
+
hasRole: (role: string) => boolean; /** Whether the user's effective set covers the given permission. */
|
|
21
|
+
hasPermission: (permission: string) => boolean;
|
|
22
|
+
};
|
|
23
|
+
/** An ABAC policy: may the user act on this specific resource? */
|
|
24
|
+
type PolicyFn = (user: Auth, resource: unknown, context: PolicyContext) => boolean | Promise<boolean>;
|
|
25
|
+
type AccessConfigurations = {
|
|
26
|
+
/**
|
|
27
|
+
* REQUIRED. The adapter that reads a user's roles + permissions (and,
|
|
28
|
+
* optionally, the ambient tenant). The role→permission catalog lives INSIDE
|
|
29
|
+
* the resolver — there is no separate config map.
|
|
30
|
+
*/
|
|
31
|
+
resolver: AccessResolver; /** Cache settings for resolved permission sets. */
|
|
32
|
+
cache?: {
|
|
33
|
+
/** TTL for a cached set. @default "10m" */ttl?: string | number;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { AccessConfigurations, AccessContext, PolicyContext, PolicyFn, RolesMap };
|
|
38
|
+
//# sourceMappingURL=types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../@warlock.js/access/src/contracts/types.ts"],"mappings":";;;;;KAIY,QAAA,GAAW,MAAM;AAA7B;;;;AAA6B;AAA7B,KAOY,aAAA;EAAa,iFAEvB,QAAA,YAFuB;EAIvB,MAAA;EAAA,CACC,GAAA;AAAA;;KAIS,aAAA,GAAgB,aAAa;EACvC,MAAA,WADuB;EAGvB,OAAA,GAAU,IAAA,sBAH6B;EAKvC,aAAA,GAAgB,UAAA;AAAA;;KAIN,QAAA,IACV,IAAA,EAAM,IAAA,EACN,QAAA,WACA,OAAA,EAAS,aAAA,eACI,OAAA;AAAA,KAEH,oBAAA;EAVM;;AAAkB;AAIpC;;EAYE,QAAA,EAAU,cAAc,EAXlB;EAcN,KAAA;IAXa,2CAaX,GAAA;EAAA;AAAA"}
|
package/esm/index.d.mts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AccessResolver } from "./contracts/access-resolver.mjs";
|
|
2
|
+
import { AccessConfigurations, AccessContext, PolicyContext, PolicyFn, RolesMap } from "./contracts/types.mjs";
|
|
3
|
+
import { gate, gateAll, gateAny } from "./middleware/gate.middleware.mjs";
|
|
4
|
+
import { flush } from "./services/engine.mjs";
|
|
5
|
+
import { access, authorize, authorizeAll, authorizeAny, can, canAll, canAny, cannot, hasAllRoles, hasAnyRole, hasRole } from "./services/access.mjs";
|
|
6
|
+
import { DefaultAccessResolver } from "./services/default-resolver.mjs";
|
|
7
|
+
import { clearPolicies, definePolicy } from "./services/policies.mjs";
|
|
8
|
+
import { resetAccessConfig, setAccessConfig } from "./services/access-config.mjs";
|
|
9
|
+
import { AccessConfigError } from "./utils/access-config-error.mjs";
|
|
10
|
+
import { AccessErrorCodes } from "./utils/access-error-codes.mjs";
|
|
11
|
+
export { AccessConfigError, AccessConfigurations, AccessContext, AccessErrorCodes, AccessResolver, DefaultAccessResolver, PolicyContext, PolicyFn, RolesMap, access, authorize, authorizeAll, authorizeAny, can, canAll, canAny, cannot, clearPolicies, definePolicy, flush, gate, gateAll, gateAny, hasAllRoles, hasAnyRole, hasRole, resetAccessConfig, setAccessConfig };
|
package/esm/index.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AccessErrorCodes } from "./utils/access-error-codes.mjs";
|
|
2
|
+
import { AccessConfigError } from "./utils/access-config-error.mjs";
|
|
3
|
+
import { resetAccessConfig, setAccessConfig } from "./services/access-config.mjs";
|
|
4
|
+
import { clearPolicies, definePolicy } from "./services/policies.mjs";
|
|
5
|
+
import { flush } from "./services/engine.mjs";
|
|
6
|
+
import { access, authorize, authorizeAll, authorizeAny, can, canAll, canAny, cannot, hasAllRoles, hasAnyRole, hasRole } from "./services/access.mjs";
|
|
7
|
+
import { gate, gateAll, gateAny } from "./middleware/gate.middleware.mjs";
|
|
8
|
+
import "./middleware/index.mjs";
|
|
9
|
+
import { DefaultAccessResolver } from "./services/default-resolver.mjs";
|
|
10
|
+
import "./services/index.mjs";
|
|
11
|
+
|
|
12
|
+
export { AccessConfigError, AccessErrorCodes, DefaultAccessResolver, access, authorize, authorizeAll, authorizeAny, can, canAll, canAny, cannot, clearPolicies, definePolicy, flush, gate, gateAll, gateAny, hasAllRoles, hasAnyRole, hasRole, resetAccessConfig, setAccessConfig };
|