@vielzeug/ward 3.0.0 → 26.10.1
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/README.md +1 -1
- package/dist/_compile.cjs +1 -1
- package/dist/_compile.cjs.map +1 -1
- package/dist/_compile.d.ts.map +1 -1
- package/dist/_compile.js +1 -47
- package/dist/_compile.js.map +1 -1
- package/dist/_match.cjs +1 -1
- package/dist/_match.cjs.map +1 -1
- package/dist/_match.d.ts.map +1 -1
- package/dist/_match.js +1 -58
- package/dist/_match.js.map +1 -1
- package/dist/constants.js +1 -5
- package/dist/constants.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.js +1 -14
- package/dist/errors.js.map +1 -1
- package/dist/factory.cjs +1 -1
- package/dist/factory.cjs.map +1 -1
- package/dist/factory.d.ts +5 -3
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +1 -89
- package/dist/factory.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -6
- package/dist/resource.cjs +1 -1
- package/dist/resource.cjs.map +1 -1
- package/dist/resource.d.ts +7 -25
- package/dist/resource.d.ts.map +1 -1
- package/dist/resource.js +1 -16
- package/dist/resource.js.map +1 -1
- package/dist/rules.cjs +1 -1
- package/dist/rules.cjs.map +1 -1
- package/dist/rules.d.ts +0 -1
- package/dist/rules.d.ts.map +1 -1
- package/dist/rules.js +1 -25
- package/dist/rules.js.map +1 -1
- package/dist/types.d.ts +17 -13
- package/dist/types.d.ts.map +1 -1
- package/dist/ward.cjs +1 -1
- package/dist/ward.cjs.map +1 -1
- package/dist/ward.iife.js +1 -1
- package/dist/ward.iife.js.map +1 -1
- package/dist/ward.js +1 -1
- package/dist/ward.js.map +1 -1
- package/package.json +8 -5
package/dist/factory.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"factory.js","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,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EAAa,EAAM,QAAU,EAC7B,EAAO,IAAI,IAEjB,OAAO,EAAW,OAAQ,GACxB,CAAI,EAAK,IAAI,CAAM,IACnB,EAAK,IAAI,CAAM,EACR,SAAS,CAAE,GAAG,EAAO,QAAO,EAAG,EAAK,CAAC,CAAC,SAAW,QACzD,CACH,CAEA,SAAS,aAAa,EAAmE,CACvF,IAAM,EAAW,EAAkB,CAAS,EAE5C,MAAO,CACL,eAAiB,GAAU,eAAe,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,EAC3E,SAAW,GAAW,SAAS,EAAO,IAAK,IAAW,CAAE,GAAG,EAAO,UAAW,CAAS,EAAE,CAAC,EACzF,OAAS,GAAU,OAAO,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,CAC7D,CACF,CAEA,MAAO,CACL,eACA,SACA,OACA,aACA,eACA,MAAO,EACP,KAAM,EAAS,IAAY,EAAQ,IAAI,EAAS,CAAO,CACzD,CACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants.cjs"),t=require("./errors.cjs"),n=require("./resource.cjs"),r=require("./factory.cjs"),i=require("./rules.cjs");exports.ANONYMOUS=e.ANONYMOUS,exports.WILDCARD=e.WILDCARD,exports.WardConditionError=t.WardConditionError,exports.WardConfigError=t.WardConfigError,exports.WardError=t.WardError,exports.allow=i.allow,exports.createWard=r.createWard,exports.deny=i.deny,exports.matchesPattern=n.matchesPattern,exports.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants.cjs"),t=require("./errors.cjs"),n=require("./resource.cjs"),r=require("./factory.cjs"),i=require("./rules.cjs");exports.ANONYMOUS=e.ANONYMOUS,exports.WILDCARD=e.WILDCARD,exports.WardConditionError=t.WardConditionError,exports.WardConfigError=t.WardConfigError,exports.WardError=t.WardError,exports.allow=i.allow,exports.createWard=r.createWard,exports.deny=i.deny,exports.matchesPattern=n.matchesPattern,exports.predicate=i.predicate;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { ANONYMOUS, WILDCARD } from './constants';
|
|
2
2
|
export { WardConditionError, WardConfigError, WardError } from './errors';
|
|
3
3
|
export { createWard } from './factory';
|
|
4
|
-
export { matchesPattern
|
|
4
|
+
export { matchesPattern } from './resource';
|
|
5
5
|
export { allow, deny, predicate } from './rules';
|
|
6
|
-
export type { BoundWard,
|
|
6
|
+
export type { BoundWard, BoundWardDecisionInput, Principal, UserPrincipal, Ward, WardAttributes, WardAttributeValue, WardCondition, WardConditionInput, WardDecision, WardDecisionInput, WardEvent, WardPattern, WardRule, } from './types';
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACjD,YAAY,EACV,SAAS,EACT,sBAAsB,EACtB,SAAS,EACT,aAAa,EACb,IAAI,EACJ,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,SAAS,EACT,WAAW,EACX,QAAQ,GACT,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { WardConditionError as n, WardConfigError as r, WardError as i } from "./errors.js";
|
|
3
|
-
import { matchesPattern as a, patternCovers as o } from "./resource.js";
|
|
4
|
-
import { createWard as s } from "./factory.js";
|
|
5
|
-
import { allow as c, deny as l, predicate as u } from "./rules.js";
|
|
6
|
-
export { e as ANONYMOUS, t as WILDCARD, n as WardConditionError, r as WardConfigError, i as WardError, c as allow, s as createWard, l as deny, a as matchesPattern, o as patternCovers, u as predicate };
|
|
1
|
+
import{ANONYMOUS as e,WILDCARD as t}from"./constants.js";import{WardConditionError as n,WardConfigError as r,WardError as i}from"./errors.js";import{matchesPattern as a}from"./resource.js";import{createWard as o}from"./factory.js";import{allow as s,deny as c,predicate as l}from"./rules.js";export{e as ANONYMOUS,t as WILDCARD,n as WardConditionError,r as WardConfigError,i as WardError,s as allow,o as createWard,c as deny,a as matchesPattern,l as predicate};
|
package/dist/resource.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require("./constants.cjs");function
|
|
1
|
+
require("./constants.cjs");function matchesPattern(e,t){if(e===`*`||e===t)return!0;if(e.endsWith(`:*`)){let n=e.slice(0,-1);return t.startsWith(n)}return!1}exports.matchesPattern=matchesPattern;
|
|
2
2
|
//# sourceMappingURL=resource.cjs.map
|
package/dist/resource.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.cjs","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true
|
|
1
|
+
{"version":3,"file":"resource.cjs","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":"2BAuBA,SAAgB,eAAe,EAAiB,EAAwB,CAGtE,GAFI,IAAA,KAEA,IAAY,EAAO,MAAO,GAG9B,GAAI,EAAQ,SAAS,IAAI,EAAG,CAC1B,IAAM,EAAK,EAAQ,MAAM,EAAG,EAAE,EAE9B,OAAO,EAAM,WAAW,CAAE,CAC5B,CAEA,MAAO,EACT"}
|
package/dist/resource.d.ts
CHANGED
|
@@ -11,31 +11,13 @@
|
|
|
11
11
|
* `read:*` matches `read:own`, `read:all`, etc.
|
|
12
12
|
*
|
|
13
13
|
* @example
|
|
14
|
-
* matchesPattern('*', 'posts:123') // true
|
|
15
|
-
* matchesPattern('posts', 'posts') // true
|
|
16
|
-
* matchesPattern('posts:*', 'posts:123') // true
|
|
17
|
-
* matchesPattern('posts:*', 'comments:1') // false
|
|
18
|
-
* matchesPattern('posts:42', 'posts:42') // true
|
|
19
|
-
* matchesPattern('read:*', 'read:own') // true
|
|
20
|
-
* matchesPattern('read:*', 'write:all') // false
|
|
14
|
+
* matchesPattern('*', 'posts:123') // true: global wildcard
|
|
15
|
+
* matchesPattern('posts', 'posts') // true: exact
|
|
16
|
+
* matchesPattern('posts:*', 'posts:123') // true: namespace wildcard
|
|
17
|
+
* matchesPattern('posts:*', 'comments:1') // false: different namespace
|
|
18
|
+
* matchesPattern('posts:42', 'posts:42') // true: exact namespaced id
|
|
19
|
+
* matchesPattern('read:*', 'read:own') // true: action namespace wildcard
|
|
20
|
+
* matchesPattern('read:*', 'write:all') // false: different action namespace
|
|
21
21
|
*/
|
|
22
22
|
export declare function matchesPattern(pattern: string, value: string): boolean;
|
|
23
|
-
/**
|
|
24
|
-
* Returns true if every concrete value that matches `narrow` also matches `broad`.
|
|
25
|
-
* This is the coverage relation used for rule conflict detection.
|
|
26
|
-
*
|
|
27
|
-
* Pattern hierarchy (most to least permissive): `*` > `ns:*` > exact
|
|
28
|
-
*
|
|
29
|
-
* Unlike `matchesPattern(broad, narrow)` — which works accidentally — this
|
|
30
|
-
* function explicitly documents and tests the coverage semantics so it remains
|
|
31
|
-
* correct if new pattern syntax is added in the future.
|
|
32
|
-
*
|
|
33
|
-
* @example
|
|
34
|
-
* patternCovers('*', 'posts:*') // true — * covers everything
|
|
35
|
-
* patternCovers('posts:*', 'posts:123') // true — namespace covers exact
|
|
36
|
-
* patternCovers('posts:*', 'posts:*') // true — same pattern covers itself
|
|
37
|
-
* patternCovers('posts:*', '*') // false — namespace does not cover global wildcard
|
|
38
|
-
* patternCovers('posts', 'posts:*') // false — exact does not cover namespace
|
|
39
|
-
*/
|
|
40
|
-
export declare function patternCovers(broad: string, narrow: string): boolean;
|
|
41
23
|
//# sourceMappingURL=resource.d.ts.map
|
package/dist/resource.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAatE
|
|
1
|
+
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAatE"}
|
package/dist/resource.js
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
//#region src/resource.ts
|
|
3
|
-
function e(e, t) {
|
|
4
|
-
if (e === "*" || e === t) return !0;
|
|
5
|
-
if (e.endsWith(":*")) {
|
|
6
|
-
let n = e.slice(0, -1);
|
|
7
|
-
return t.startsWith(n);
|
|
8
|
-
}
|
|
9
|
-
return !1;
|
|
10
|
-
}
|
|
11
|
-
function t(e, t) {
|
|
12
|
-
return e === "*" ? !0 : t === "*" ? !1 : e.endsWith(":*") ? t.startsWith(e.slice(0, -1)) : e === t;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
|
-
export { e as matchesPattern, t as patternCovers };
|
|
16
|
-
|
|
1
|
+
import"./constants.js";function matchesPattern(e,t){if(e===`*`||e===t)return!0;if(e.endsWith(`:*`)){let n=e.slice(0,-1);return t.startsWith(n)}return!1}export{matchesPattern};
|
|
17
2
|
//# sourceMappingURL=resource.js.map
|
package/dist/resource.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.js","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true
|
|
1
|
+
{"version":3,"file":"resource.js","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":"uBAuBA,SAAgB,eAAe,EAAiB,EAAwB,CAGtE,GAFI,IAAA,KAEA,IAAY,EAAO,MAAO,GAG9B,GAAI,EAAQ,SAAS,IAAI,EAAG,CAC1B,IAAM,EAAK,EAAQ,MAAM,EAAG,EAAE,EAE9B,OAAO,EAAM,WAAW,CAAE,CAC5B,CAEA,MAAO,EACT"}
|
package/dist/rules.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
function buildRules(e,t,n,r,i){let a=Object.freeze(Array.isArray(t)?[...t]:[t]);return r.map(t=>({action:t,...i?.when===void 0?{}:{condition:i.when},effect:e,resource:n,roles:a}))}var allow=(e,t,n,r)=>buildRules(`allow`,e,t,n,r),deny=(e,t,n,r)=>buildRules(`deny`,e,t,n,r),owns=e=>({attributes:t,principal:n})=>n!==null&&t?.[e]===n.id,and=(...e)=>t=>e.every(e=>e(t)),or=(...e)=>t=>e.some(e=>e(t)),not=e=>t=>!e(t),e={and,not,or,owns};exports.allow=allow,exports.deny=deny,exports.predicate=e;
|
|
2
2
|
//# sourceMappingURL=rules.cjs.map
|
package/dist/rules.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.cjs","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"rules.cjs","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import type { WardAttributes, WardCondition, WardPattern, WardRule } from './types';\n\ntype RuleOptions<TAttributes extends WardAttributes> = Readonly<{\n when?: WardCondition<TAttributes>;\n}>;\n\nfunction buildRules<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n effect: 'allow' | 'deny',\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] {\n const roles = Object.freeze(Array.isArray(role) ? [...role] : [role]);\n\n return actions.map((action) => ({\n action,\n ...(options?.when === undefined ? {} : { condition: options.when }),\n effect,\n resource,\n roles,\n }));\n}\n\nexport const allow = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('allow', role, resource, actions, options);\n\nexport const deny = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('deny', role, resource, actions, options);\n\nconst owns =\n <TAttributes extends WardAttributes = WardAttributes>(\n attribute: keyof TAttributes & string,\n ): WardCondition<TAttributes> =>\n ({ attributes, principal }) =>\n principal !== null && attributes?.[attribute] === principal.id;\nconst and =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.every((condition) => condition(input));\nconst or =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.some((condition) => condition(input));\nconst not =\n <TAttributes extends WardAttributes = WardAttributes>(\n condition: WardCondition<TAttributes>,\n ): WardCondition<TAttributes> =>\n (input) =>\n !condition(input);\n\nexport const predicate = { and, not, or, owns } as const;\n"],"mappings":"AAMA,SAAS,WACP,EACA,EACA,EACA,EACA,EAC6C,CAC7C,IAAM,EAAQ,OAAO,OAAO,MAAM,QAAQ,CAAI,EAAI,CAAC,GAAG,CAAI,EAAI,CAAC,CAAI,CAAC,EAEpE,OAAO,EAAQ,IAAK,IAAY,CAC9B,SACA,GAAI,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,IAAK,EACjE,SACA,WACA,OACF,EAAE,CACJ,CAEA,IAAa,OAKX,EACA,EACA,EACA,IACgD,WAAW,QAAS,EAAM,EAAU,EAAS,CAAO,EAEzF,MAKX,EACA,EACA,EACA,IACgD,WAAW,OAAQ,EAAM,EAAU,EAAS,CAAO,EAE/F,KAEF,IAED,CAAE,aAAY,eACb,IAAc,MAAQ,IAAa,KAAe,EAAU,GAC1D,KAEF,GAAG,IAEJ,GACC,EAAW,MAAO,GAAc,EAAU,CAAK,CAAC,EAC9C,IAEF,GAAG,IAEJ,GACC,EAAW,KAAM,GAAc,EAAU,CAAK,CAAC,EAC7C,IAEF,GAED,GACC,CAAC,EAAU,CAAK,EAEP,EAAY,CAAE,IAAK,IAAK,GAAI,IAAK"}
|
package/dist/rules.d.ts
CHANGED
|
@@ -6,7 +6,6 @@ export declare const allow: <TAction extends string = string, TResource extends
|
|
|
6
6
|
export declare const deny: <TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes>(role: string | readonly string[], resource: WardPattern<TResource>, actions: readonly WardPattern<TAction>[], options?: RuleOptions<TAttributes>) => WardRule<TAction, TResource, TAttributes>[];
|
|
7
7
|
export declare const predicate: {
|
|
8
8
|
readonly and: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(...conditions: readonly WardCondition<TAttributes>[]) => WardCondition<TAttributes>;
|
|
9
|
-
readonly hasRole: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(role: string) => WardCondition<TAttributes>;
|
|
10
9
|
readonly not: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(condition: WardCondition<TAttributes>) => WardCondition<TAttributes>;
|
|
11
10
|
readonly or: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(...conditions: readonly WardCondition<TAttributes>[]) => WardCondition<TAttributes>;
|
|
12
11
|
readonly owns: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(attribute: keyof TAttributes & string) => WardCondition<TAttributes>;
|
package/dist/rules.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEpF,KAAK,WAAW,CAAC,WAAW,SAAS,cAAc,IAAI,QAAQ,CAAC;IAC9D,IAAI,CAAC,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC;CACnC,CAAC,CAAC;AAoBH,eAAO,MAAM,KAAK,GAChB,OAAO,SAAS,MAAM,GAAG,MAAM,EAC/B,SAAS,SAAS,MAAM,GAAG,MAAM,EACjC,WAAW,SAAS,cAAc,GAAG,cAAc,EAEnD,MAAM,MAAM,GAAG,SAAS,MAAM,EAAE,EAChC,UAAU,WAAW,CAAC,SAAS,CAAC,EAChC,SAAS,SAAS,WAAW,CAAC,OAAO,CAAC,EAAE,EACxC,UAAU,WAAW,CAAC,WAAW,CAAC,KACjC,QAAQ,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,EAA2D,CAAC;AAExG,eAAO,MAAM,IAAI,GACf,OAAO,SAAS,MAAM,GAAG,MAAM,EAC/B,SAAS,SAAS,MAAM,GAAG,MAAM,EACjC,WAAW,SAAS,cAAc,GAAG,cAAc,EAEnD,MAAM,MAAM,GAAG,SAAS,MAAM,EAAE,EAChC,UAAU,WAAW,CAAC,SAAS,CAAC,EAChC,SAAS,SAAS,WAAW,CAAC,OAAO,CAAC,EAAE,EACxC,UAAU,WAAW,CAAC,WAAW,CAAC,KACjC,QAAQ,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,EAA0D,CAAC;AA2BvG,eAAO,MAAM,SAAS;mBAlBnB,WAAW,SAAS,cAAc,kFAClB,SAAS,aAAa,CAAC,WAAW,CAAC,EAAE,KACnD,aAAa,CAAC,WAAW,CAAC;mBAU5B,WAAW,SAAS,cAAc,8EACtB,aAAa,CAAC,WAAW,CAAC,KACpC,aAAa,CAAC,WAAW,CAAC;kBAR5B,WAAW,SAAS,cAAc,kFAClB,SAAS,aAAa,CAAC,WAAW,CAAC,EAAE,KACnD,aAAa,CAAC,WAAW,CAAC;oBAd5B,WAAW,SAAS,cAAc,8EACtB,MAAM,WAAW,GAAG,MAAM,KACpC,aAAa,CAAC,WAAW,CAAC;CAsByB,CAAC"}
|
package/dist/rules.js
CHANGED
|
@@ -1,26 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
//#region src/rules.ts
|
|
3
|
-
function e(e) {
|
|
4
|
-
let t = Object.freeze(Array.isArray(e) ? [...e] : [e]);
|
|
5
|
-
return ({ principal: e }) => t.some((t) => t === "anonymous" ? e === null : t === "*" ? e !== null : e?.roles.includes(t));
|
|
6
|
-
}
|
|
7
|
-
function t(t, n, r, i, a) {
|
|
8
|
-
let o = e(n), s = a?.when ? (e) => o(e) && a.when(e) : o;
|
|
9
|
-
return i.map((e) => ({
|
|
10
|
-
action: e,
|
|
11
|
-
condition: s,
|
|
12
|
-
effect: t,
|
|
13
|
-
resource: r
|
|
14
|
-
}));
|
|
15
|
-
}
|
|
16
|
-
var n = (e, n, r, i) => t("allow", e, n, r, i), r = (e, n, r, i) => t("deny", e, n, r, i), i = {
|
|
17
|
-
and: (...e) => (t) => e.every((e) => e(t)),
|
|
18
|
-
hasRole: (e) => ({ principal: t }) => t?.roles.includes(e) ?? !1,
|
|
19
|
-
not: (e) => (t) => !e(t),
|
|
20
|
-
or: (...e) => (t) => e.some((e) => e(t)),
|
|
21
|
-
owns: (e) => ({ attributes: t, principal: n }) => n !== null && t?.[e] === n.id
|
|
22
|
-
};
|
|
23
|
-
//#endregion
|
|
24
|
-
export { n as allow, r as deny, i as predicate };
|
|
25
|
-
|
|
1
|
+
function buildRules(e,t,n,r,i){let a=Object.freeze(Array.isArray(t)?[...t]:[t]);return r.map(t=>({action:t,...i?.when===void 0?{}:{condition:i.when},effect:e,resource:n,roles:a}))}var allow=(e,t,n,r)=>buildRules(`allow`,e,t,n,r),deny=(e,t,n,r)=>buildRules(`deny`,e,t,n,r),owns=e=>({attributes:t,principal:n})=>n!==null&&t?.[e]===n.id,and=(...e)=>t=>e.every(e=>e(t)),or=(...e)=>t=>e.some(e=>e(t)),not=e=>t=>!e(t),e={and,not,or,owns};export{allow,deny,e as predicate};
|
|
26
2
|
//# sourceMappingURL=rules.js.map
|
package/dist/rules.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"rules.js","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import type { WardAttributes, WardCondition, WardPattern, WardRule } from './types';\n\ntype RuleOptions<TAttributes extends WardAttributes> = Readonly<{\n when?: WardCondition<TAttributes>;\n}>;\n\nfunction buildRules<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n effect: 'allow' | 'deny',\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] {\n const roles = Object.freeze(Array.isArray(role) ? [...role] : [role]);\n\n return actions.map((action) => ({\n action,\n ...(options?.when === undefined ? {} : { condition: options.when }),\n effect,\n resource,\n roles,\n }));\n}\n\nexport const allow = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('allow', role, resource, actions, options);\n\nexport const deny = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('deny', role, resource, actions, options);\n\nconst owns =\n <TAttributes extends WardAttributes = WardAttributes>(\n attribute: keyof TAttributes & string,\n ): WardCondition<TAttributes> =>\n ({ attributes, principal }) =>\n principal !== null && attributes?.[attribute] === principal.id;\nconst and =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.every((condition) => condition(input));\nconst or =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.some((condition) => condition(input));\nconst not =\n <TAttributes extends WardAttributes = WardAttributes>(\n condition: WardCondition<TAttributes>,\n ): WardCondition<TAttributes> =>\n (input) =>\n !condition(input);\n\nexport const predicate = { and, not, or, owns } as const;\n"],"mappings":"AAMA,SAAS,WACP,EACA,EACA,EACA,EACA,EAC6C,CAC7C,IAAM,EAAQ,OAAO,OAAO,MAAM,QAAQ,CAAI,EAAI,CAAC,GAAG,CAAI,EAAI,CAAC,CAAI,CAAC,EAEpE,OAAO,EAAQ,IAAK,IAAY,CAC9B,SACA,GAAI,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,IAAK,EACjE,SACA,WACA,OACF,EAAE,CACJ,CAEA,IAAa,OAKX,EACA,EACA,EACA,IACgD,WAAW,QAAS,EAAM,EAAU,EAAS,CAAO,EAEzF,MAKX,EACA,EACA,EACA,IACgD,WAAW,OAAQ,EAAM,EAAU,EAAS,CAAO,EAE/F,KAEF,IAED,CAAE,aAAY,eACb,IAAc,MAAQ,IAAa,KAAe,EAAU,GAC1D,KAEF,GAAG,IAEJ,GACC,EAAW,MAAO,GAAc,EAAU,CAAK,CAAC,EAC9C,IAEF,GAAG,IAEJ,GACC,EAAW,KAAM,GAAc,EAAU,CAAK,CAAC,EAC7C,IAEF,GAED,GACC,CAAC,EAAU,CAAK,EAEP,EAAY,CAAE,IAAK,IAAK,GAAI,IAAK"}
|
package/dist/types.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ export type WardRule<TAction extends string = string, TResource extends string =
|
|
|
21
21
|
condition?: WardCondition<TAttributes>;
|
|
22
22
|
effect: 'allow' | 'deny';
|
|
23
23
|
resource: WardPattern<TResource>;
|
|
24
|
+
/**
|
|
25
|
+
* Roles this rule applies to, evaluated beside action, resource, and
|
|
26
|
+
* attributes. `ANONYMOUS` matches a null principal, `WILDCARD` matches any
|
|
27
|
+
* authenticated principal. Omit to match every principal.
|
|
28
|
+
*/
|
|
29
|
+
roles?: readonly string[];
|
|
24
30
|
}>;
|
|
25
31
|
type MatchedWardDecision<TAction extends string, TResource extends string, TAttributes extends WardAttributes> = Readonly<{
|
|
26
32
|
effect: 'allow' | 'deny';
|
|
@@ -42,13 +48,6 @@ export type WardDecisionInput<TAction extends string = string, TResource extends
|
|
|
42
48
|
resource: TResource;
|
|
43
49
|
}>;
|
|
44
50
|
export type BoundWardDecisionInput<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = Omit<WardDecisionInput<TAction, TResource, TAttributes>, 'principal'>;
|
|
45
|
-
export type WardAllowedActionsInput<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = Readonly<{
|
|
46
|
-
attributes?: TAttributes;
|
|
47
|
-
knownActions: readonly TAction[];
|
|
48
|
-
principal?: Principal;
|
|
49
|
-
resource: TResource;
|
|
50
|
-
}>;
|
|
51
|
-
export type BoundWardAllowedActionsInput<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = Omit<WardAllowedActionsInput<TAction, TResource, TAttributes>, 'principal'>;
|
|
52
51
|
export type WardEvent<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = Readonly<{
|
|
53
52
|
decision: WardDecision<TAction, TResource, TAttributes>;
|
|
54
53
|
input: WardDecisionInput<TAction, TResource, TAttributes> & {
|
|
@@ -56,13 +55,18 @@ export type WardEvent<TAction extends string = string, TResource extends string
|
|
|
56
55
|
};
|
|
57
56
|
type: 'decision';
|
|
58
57
|
}>;
|
|
59
|
-
export type BoundWard<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> =
|
|
60
|
-
allowedActions(input: BoundWardAllowedActionsInput<TAction, TResource, TAttributes>): TAction[];
|
|
61
|
-
checkAll(inputs: readonly BoundWardDecisionInput<TAction, TResource, TAttributes>[]): WardDecision<TAction, TResource, TAttributes>[];
|
|
62
|
-
decide(input: BoundWardDecisionInput<TAction, TResource, TAttributes>): WardDecision<TAction, TResource, TAttributes>;
|
|
63
|
-
};
|
|
58
|
+
export type BoundWard<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = Pick<Ward<TAction, TResource, TAttributes>, 'allowedActions' | 'checkAll' | 'decide'>;
|
|
64
59
|
export type Ward<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes> = {
|
|
65
|
-
|
|
60
|
+
/**
|
|
61
|
+
* The actions this ward's rule set can ever allow, in declaration order.
|
|
62
|
+
* Derived from the compiled rules; exact (non-pattern) actions only, since
|
|
63
|
+
* wildcard actions have no enumerable value.
|
|
64
|
+
*/
|
|
65
|
+
readonly knownActions: readonly TAction[];
|
|
66
|
+
/** Actions the input is allowed to perform, drawn from {@link Ward.knownActions} unless filtered. */
|
|
67
|
+
allowedActions(input: Omit<WardDecisionInput<TAction, TResource, TAttributes>, 'action'> & {
|
|
68
|
+
filter?: readonly TAction[];
|
|
69
|
+
}): TAction[];
|
|
66
70
|
checkAll(inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[]): WardDecision<TAction, TResource, TAttributes>[];
|
|
67
71
|
decide(input: WardDecisionInput<TAction, TResource, TAttributes>): WardDecision<TAction, TResource, TAttributes>;
|
|
68
72
|
forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes>;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,MAAM,kBAAkB,GAC1B,OAAO,GACP,MAAM,GACN,MAAM,GACN,IAAI,GACJ,SAAS,kBAAkB,EAAE,GAC7B;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,kBAAkB,CAAA;CAAE,CAAC;AAEnD,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAE1E,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,MAAM,IAAI,MAAM,GAAG,OAAO,QAAQ,GAAG,GAAG,MAAM,IAAI,CAAC;AAE1F,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC;IACnC,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CAC1B,CAAC,CAAC;AAEH,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,IAAI,CAAC;AAE7C,MAAM,MAAM,kBAAkB,CAAC,WAAW,SAAS,cAAc,GAAG,cAAc,IAAI,QAAQ,CAAC;IAC7F,UAAU,CAAC,EAAE,WAAW,CAAC;IACzB,SAAS,EAAE,SAAS,CAAC;CACtB,CAAC,CAAC;AAEH,MAAM,MAAM,aAAa,CAAC,WAAW,SAAS,cAAc,GAAG,cAAc,IAAI,CAC/E,KAAK,EAAE,kBAAkB,CAAC,WAAW,CAAC,K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ward.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/arsenal");var t=`*`,n=`anonymous`,WardError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},WardConfigError=class extends WardError{},WardConditionError=class extends WardError{ruleIndex;constructor(e,t){super(`Rule[${e}].condition failed`,{cause:t}),this.ruleIndex=e}};function snapshotValue(e,t,n){if(e===null||typeof e==`boolean`||typeof e==`string`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw new WardConfigError(`${t} must contain only finite numbers`);return e}if(typeof e!=`object`)throw new WardConfigError(`${t} must contain only JSON-compatible values`);if(n.has(e))throw new WardConfigError(`${t} must not contain circular references`);let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new WardConfigError(`${t} must contain only arrays and plain objects`);n.add(e);try{return Object.freeze(Array.isArray(e)?Array.from(e,(e,r)=>snapshotValue(e,`${t}[${r}]`,n)):Object.fromEntries(Object.keys(e).map(r=>[r,snapshotValue(e[r],`${t}.${r}`,n)])))}finally{n.delete(e)}}function snapshotAttributes(e,t){if(e!==void 0){if(typeof e!=`object`||!e||Array.isArray(e))throw new WardConfigError(`${t} must be a plain object`);return snapshotValue(e,t,new Set)}}function compileRule(e,t){let n=`Rule[${t}]`;if(typeof e!=`object`||!e||Array.isArray(e))throw new WardConfigError(`${n} must be a plain object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new WardConfigError(`${n} must be a plain object`);if(typeof e.action!=`string`||!e.action.trim())throw new WardConfigError(`${n}.action must be a non-empty string`);if(e.action.endsWith(`:`))throw new WardConfigError(`${n}.action '${e.action}' ends with ':': did you mean '${e.action}*'?`);if(typeof e.resource!=`string`||!e.resource.trim())throw new WardConfigError(`${n}.resource must be a non-empty string`);if(e.resource.endsWith(`:`))throw new WardConfigError(`${n}.resource '${e.resource}' ends with ':': did you mean '${e.resource}*'?`);if(e.effect!==`allow`&&e.effect!==`deny`)throw new WardConfigError(`${n}.effect must be "allow" or "deny"`);if(e.condition!==void 0&&typeof e.condition!=`function`)throw new WardConfigError(`${n}.condition must be a function`);if(e.roles!==void 0&&(!Array.isArray(e.roles)||e.roles.some(e=>typeof e!=`string`||!e.trim())))throw new WardConfigError(`${n}.roles must be an array of non-empty strings`);return Object.freeze({action:e.action,...e.attributes===void 0?{}:{attributes:snapshotAttributes(e.attributes,`${n}.attributes`)},...e.condition===void 0?{}:{condition:e.condition},effect:e.effect,resource:e.resource,...e.roles===void 0?{}:{roles:Object.freeze([...e.roles])}})}function matchesPattern(e,t){if(e===`*`||e===t)return!0;if(e.endsWith(`:*`)){let n=e.slice(0,-1);return t.startsWith(n)}return!1}function assertUserPrincipal(e){if(typeof e!=`object`||!e)throw new WardConfigError(`Invalid principal: expected { id: string, roles: string[] }`);let t=e;if(typeof t.id!=`string`||!t.id.trim())throw new WardConfigError(`Invalid principal: id must be a non-empty string`);if(!Array.isArray(t.roles)||t.roles.some(e=>typeof e!=`string`||!e.trim()))throw new WardConfigError(`Invalid principal: roles must be an array of non-empty strings`)}function snapshotPrincipal(e){return e==null?null:(assertUserPrincipal(e),Object.freeze({...e.attributes===void 0?{}:{attributes:snapshotAttributes(e.attributes,`Principal.attributes`)},id:e.id,roles:Object.freeze([...e.roles])}))}function snapshotDecisionInput(e){if(typeof e.action!=`string`||!e.action.trim())throw new WardConfigError(`Decision.action must be a non-empty string`);if(typeof e.resource!=`string`||!e.resource.trim())throw new WardConfigError(`Decision.resource must be a non-empty string`);return Object.freeze({action:e.action,...e.attributes===void 0?{}:{attributes:snapshotAttributes(e.attributes,`Decision.attributes`)},principal:snapshotPrincipal(e.principal),resource:e.resource})}function deepEqual(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>deepEqual(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.hasOwn(r,e)&&deepEqual(n[e],r[e]))}function attributesMatch(e,t){return e?t?Object.keys(e).every(n=>Object.hasOwn(t,n)&&deepEqual(e[n],t[n])):!1:!0}function rolesMatch(e,t){return!e||e.some(e=>e===`anonymous`?t===null:e===`*`?t!==null:t?.roles.includes(e)??!1)}function isThenable(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`||typeof e==`function`&&`then`in e&&typeof e.then==`function`}function ruleMatches(e,t,n){if(!matchesPattern(e.action,n.action)||!matchesPattern(e.resource,n.resource)||!rolesMatch(e.roles,n.principal)||!attributesMatch(e.attributes,n.attributes))return!1;if(!e.condition)return!0;try{let t=e.condition({attributes:n.attributes,principal:n.principal});if(isThenable(t))throw TypeError(`Async conditions are not supported; return a boolean`);if(typeof t!=`boolean`)throw TypeError(`Conditions must return a boolean`);return t}catch(e){throw new WardConditionError(t,e)}}function createWard(t=[]){let n=Object.freeze(t.flat().map((e,t)=>compileRule(e,t))),r=Object.freeze([...new Set(n.flatMap(e=>e.effect===`allow`&&!e.action.includes(`*`)?[e.action]:[]))]),i=(0,e.tapper)();function evaluate(e,t){let r=snapshotDecisionInput(e);for(let e=0;e<n.length;e++){let i=n[e];if(ruleMatches(i,e,r)){let n=Object.freeze({effect:i.effect,matched:!0,reason:`rule[${e}] ${i.effect===`allow`?`allows`:`denies`} '${r.action}' on '${r.resource}'`,rule:i});return t&&emitDecision(r,n),n}}let i=Object.freeze({effect:`deny`,matched:!1,reason:`no matching rule for '${r.action}' on '${r.resource}' (default deny)`});return t&&emitDecision(r,i),i}function emitDecision(e,t){i.emit(Object.freeze({decision:t,input:e,type:`decision`}))}function decide(e){return evaluate(e,!0)}function checkAll(e){return e.map(decide)}function allowedActions(e){let t=e.filter??r,n=new Set;return t.filter(t=>!n.has(t)&&(n.add(t),evaluate({...e,action:t},!1).effect===`allow`))}function forPrincipal(e){let t=snapshotPrincipal(e);return{allowedActions:e=>allowedActions({...e,principal:t}),checkAll:e=>checkAll(e.map(e=>({...e,principal:t}))),decide:e=>decide({...e,principal:t})}}return{allowedActions,checkAll,decide,forPrincipal,knownActions:r,rules:n,tap:(e,t)=>i.tap(e,t)}}function buildRules(e,t,n,r,i){let a=Object.freeze(Array.isArray(t)?[...t]:[t]);return r.map(t=>({action:t,...i?.when===void 0?{}:{condition:i.when},effect:e,resource:n,roles:a}))}var allow=(e,t,n,r)=>buildRules(`allow`,e,t,n,r),deny=(e,t,n,r)=>buildRules(`deny`,e,t,n,r),owns=e=>({attributes:t,principal:n})=>n!==null&&t?.[e]===n.id,and=(...e)=>t=>e.every(e=>e(t)),or=(...e)=>t=>e.some(e=>e(t)),not=e=>t=>!e(t),r={and,not,or,owns};exports.ANONYMOUS=n,exports.WILDCARD=t,exports.WardConditionError=WardConditionError,exports.WardConfigError=WardConfigError,exports.WardError=WardError,exports.allow=allow,exports.createWard=createWard,exports.deny=deny,exports.matchesPattern=matchesPattern,exports.predicate=r;
|
|
2
2
|
//# sourceMappingURL=ward.cjs.map
|
package/dist/ward.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ward.cjs","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/_compile.ts","../src/resource.ts","../src/_match.ts","../src/factory.ts","../src/rules.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n","/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n","import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':' — did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':' — did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n","import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true — global wildcard\n * matchesPattern('posts', 'posts') // true — exact\n * matchesPattern('posts:*', 'posts:123') // true — namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false — different namespace\n * matchesPattern('posts:42', 'posts:42') // true — exact namespaced id\n * matchesPattern('read:*', 'read:own') // true — action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false — different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n\n/**\n * Returns true if every concrete value that matches `narrow` also matches `broad`.\n * This is the coverage relation used for rule conflict detection.\n *\n * Pattern hierarchy (most to least permissive): `*` > `ns:*` > exact\n *\n * Unlike `matchesPattern(broad, narrow)` — which works accidentally — this\n * function explicitly documents and tests the coverage semantics so it remains\n * correct if new pattern syntax is added in the future.\n *\n * @example\n * patternCovers('*', 'posts:*') // true — * covers everything\n * patternCovers('posts:*', 'posts:123') // true — namespace covers exact\n * patternCovers('posts:*', 'posts:*') // true — same pattern covers itself\n * patternCovers('posts:*', '*') // false — namespace does not cover global wildcard\n * patternCovers('posts', 'posts:*') // false — exact does not cover namespace\n */\nexport function patternCovers(broad: string, narrow: string): boolean {\n // Global wildcard covers everything\n if (broad === WILDCARD) return true;\n\n // Nothing else covers global wildcard\n if (narrow === WILDCARD) return false;\n\n // Namespace wildcard: covers any value starting with the same namespace prefix,\n // including nested namespace wildcards (\"posts:*\" covers \"posts:sub:*\") and exact IDs.\n if (broad.endsWith(':*')) {\n return narrow.startsWith(broad.slice(0, -1));\n }\n\n // Exact only covers itself\n return broad === narrow;\n}\n","import { snapshotAttributes } from './_compile';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n","import { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport { WardConfigError } from './errors';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection — order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 4. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const tappers = new Set<(event: WardEvent<TAction, TResource, TAttributes>) => void>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n if (tappers.size === 0) return;\n\n const event = Object.freeze({ decision, input, type: 'decision' as const });\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {}\n }\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n knownActions: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const seen = new Set<TAction>();\n\n return input.knownActions.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n function tap(\n handler: (event: WardEvent<TAction, TResource, TAttributes>) => void,\n options?: { readonly signal?: AbortSignal },\n ): () => void {\n if (typeof handler !== 'function') throw new WardConfigError('tap handler must be a function');\n if (options?.signal?.aborted) return () => {};\n\n tappers.add(handler);\n const onAbort = () => tappers.delete(handler);\n options?.signal?.addEventListener('abort', onAbort, { once: true });\n\n return () => {\n tappers.delete(handler);\n options?.signal?.removeEventListener('abort', onAbort);\n };\n }\n\n return { allowedActions, checkAll, decide, forPrincipal, rules: compiled, tap };\n}\n","import { ANONYMOUS, WILDCARD } from './constants';\nimport type { WardAttributes, WardCondition, WardPattern, WardRule } from './types';\n\ntype RuleOptions<TAttributes extends WardAttributes> = Readonly<{\n when?: WardCondition<TAttributes>;\n}>;\n\nfunction roleCondition<TAttributes extends WardAttributes>(\n role: string | readonly string[],\n): WardCondition<TAttributes> {\n const roles = Object.freeze(Array.isArray(role) ? [...role] : [role]);\n\n return ({ principal }) =>\n roles.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : principal?.roles.includes(candidate),\n );\n}\n\nfunction buildRules<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n effect: 'allow' | 'deny',\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] {\n const matchesRole = roleCondition<TAttributes>(role);\n const condition = options?.when\n ? (input: Parameters<WardCondition<TAttributes>>[0]) => matchesRole(input) && options.when!(input)\n : matchesRole;\n\n return actions.map((action) => ({ action, condition, effect, resource }));\n}\n\nexport const allow = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('allow', role, resource, actions, options);\n\nexport const deny = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('deny', role, resource, actions, options);\n\nconst hasRole =\n <TAttributes extends WardAttributes = WardAttributes>(role: string): WardCondition<TAttributes> =>\n ({ principal }) =>\n principal?.roles.includes(role) ?? false;\nconst owns =\n <TAttributes extends WardAttributes = WardAttributes>(\n attribute: keyof TAttributes & string,\n ): WardCondition<TAttributes> =>\n ({ attributes, principal }) =>\n principal !== null && attributes?.[attribute] === principal.id;\nconst and =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.every((condition) => condition(input));\nconst or =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.some((condition) => condition(input));\nconst not =\n <TAttributes extends WardAttributes = WardAttributes>(\n condition: WardCondition<TAttributes>,\n ): WardCondition<TAttributes> =>\n (input) =>\n !condition(input);\n\nexport const predicate = { and, hasRole, not, or, owns } as const;\n"],"mappings":"mEAAA,IAAa,EAAW,IACX,EAAY,YCAZ,EAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,EAAb,cAAqC,CAAU,CAAC,EAGnC,EAAb,cAAwC,CAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQ,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAY,CACnB,CACF,ECjBA,SAAS,EAAc,EAAgB,EAAc,EAA4C,CAC/F,GAAI,IAAU,MAAQ,OAAO,GAAU,WAAa,OAAO,GAAU,SAAU,OAAO,EAEtF,GAAI,OAAO,GAAU,SAAU,CAC7B,GAAI,CAAC,OAAO,SAAS,CAAK,EAAG,MAAM,IAAI,EAAgB,GAAG,EAAK,kCAAkC,EACjG,OAAO,CACT,CAEA,GAAI,OAAO,GAAU,SACnB,MAAM,IAAI,EAAgB,GAAG,EAAK,0CAA0C,EAG9E,GAAI,EAAU,IAAI,CAAK,EAAG,MAAM,IAAI,EAAgB,GAAG,EAAK,sCAAsC,EAElG,IAAM,EAAY,OAAO,eAAe,CAAK,EAC7C,GAAI,CAAC,MAAM,QAAQ,CAAK,GAAK,IAAc,OAAO,WAAa,IAAc,KAC3E,MAAM,IAAI,EAAgB,GAAG,EAAK,4CAA4C,EAGhF,EAAU,IAAI,CAAK,EAEnB,GAAI,CAKF,OAHS,OAAO,OADZ,MAAM,QAAQ,CAAK,EACA,MAAM,KAAK,GAAQ,EAAM,IAAU,EAAc,EAAM,GAAG,EAAK,GAAG,EAAM,GAAI,CAAS,CAAC,EAI3G,OAAO,YACL,OAAO,KAAK,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1
|
+
{"version":3,"file":"ward.cjs","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/_compile.ts","../src/resource.ts","../src/_match.ts","../src/factory.ts","../src/rules.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n","/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n","import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':': did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':': did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n if (rule.roles !== undefined) {\n if (!Array.isArray(rule.roles) || rule.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError(`${at}.roles must be an array of non-empty strings`);\n }\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n ...(rule.roles === undefined ? {} : { roles: Object.freeze([...rule.roles]) }),\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n","import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n","import { snapshotAttributes } from './_compile';\nimport { ANONYMOUS, WILDCARD } from './constants';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\n/**\n * Declarative role check: `ANONYMOUS` matches a null principal, `WILDCARD`\n * matches any authenticated principal, an exact role must be in the principal's\n * roles. A rule without `roles` matches every principal.\n */\nfunction rolesMatch(expected: readonly string[] | undefined, principal: Principal): boolean {\n if (!expected) return true;\n\n return expected.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : (principal?.roles.includes(candidate) ?? false),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!rolesMatch(rule.roles, input.principal)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n","import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n","import type { WardAttributes, WardCondition, WardPattern, WardRule } from './types';\n\ntype RuleOptions<TAttributes extends WardAttributes> = Readonly<{\n when?: WardCondition<TAttributes>;\n}>;\n\nfunction buildRules<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n effect: 'allow' | 'deny',\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] {\n const roles = Object.freeze(Array.isArray(role) ? [...role] : [role]);\n\n return actions.map((action) => ({\n action,\n ...(options?.when === undefined ? {} : { condition: options.when }),\n effect,\n resource,\n roles,\n }));\n}\n\nexport const allow = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('allow', role, resource, actions, options);\n\nexport const deny = <\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n role: string | readonly string[],\n resource: WardPattern<TResource>,\n actions: readonly WardPattern<TAction>[],\n options?: RuleOptions<TAttributes>,\n): WardRule<TAction, TResource, TAttributes>[] => buildRules('deny', role, resource, actions, options);\n\nconst owns =\n <TAttributes extends WardAttributes = WardAttributes>(\n attribute: keyof TAttributes & string,\n ): WardCondition<TAttributes> =>\n ({ attributes, principal }) =>\n principal !== null && attributes?.[attribute] === principal.id;\nconst and =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.every((condition) => condition(input));\nconst or =\n <TAttributes extends WardAttributes = WardAttributes>(\n ...conditions: readonly WardCondition<TAttributes>[]\n ): WardCondition<TAttributes> =>\n (input) =>\n conditions.some((condition) => condition(input));\nconst not =\n <TAttributes extends WardAttributes = WardAttributes>(\n condition: WardCondition<TAttributes>,\n ): WardCondition<TAttributes> =>\n (input) =>\n !condition(input);\n\nexport const predicate = { and, not, or, owns } as const;\n"],"mappings":"sGAAA,IAAa,EAAW,IACX,EAAY,YCAZ,UAAb,cAA+B,KAAM,CACnC,YAAY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