@vielzeug/ward 2.3.0 → 26.10.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/README.md +30 -35
- package/dist/_compile.cjs +1 -1
- package/dist/_compile.cjs.map +1 -1
- package/dist/_compile.d.ts +5 -23
- package/dist/_compile.d.ts.map +1 -1
- package/dist/_compile.js +1 -42
- 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 +9 -19
- package/dist/_match.d.ts.map +1 -1
- package/dist/_match.js +1 -55
- 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.d.ts +3 -16
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -15
- 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 +16 -10
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +1 -137
- package/dist/factory.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +4 -4
- 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 +0 -18
- 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 +2 -0
- package/dist/rules.cjs.map +1 -0
- package/dist/rules.d.ts +14 -0
- package/dist/rules.d.ts.map +1 -0
- package/dist/rules.js +2 -0
- package/dist/rules.js.map +1 -0
- package/dist/types.d.ts +68 -133
- 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 +10 -7
- package/dist/_conflict.cjs +0 -2
- package/dist/_conflict.cjs.map +0 -1
- package/dist/_conflict.d.ts +0 -10
- package/dist/_conflict.d.ts.map +0 -1
- package/dist/_conflict.js +0 -51
- package/dist/_conflict.js.map +0 -1
- package/dist/_dev.cjs +0 -2
- package/dist/_dev.cjs.map +0 -1
- package/dist/_dev.d.ts +0 -8
- package/dist/_dev.d.ts.map +0 -1
- package/dist/_dev.js +0 -6
- package/dist/_dev.js.map +0 -1
- package/dist/builder.cjs +0 -2
- package/dist/builder.cjs.map +0 -1
- package/dist/builder.d.ts +0 -71
- package/dist/builder.d.ts.map +0 -1
- package/dist/builder.js +0 -39
- package/dist/builder.js.map +0 -1
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** 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 or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** 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"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,SAAU,CAAC,EAGnC,mBAAb,cAAwC,SAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQ,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAY,CACnB,CACF"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -2,24 +2,11 @@
|
|
|
2
2
|
export declare class WardError extends Error {
|
|
3
3
|
constructor(message: string, opts?: ErrorOptions);
|
|
4
4
|
}
|
|
5
|
-
/** Thrown when a rule definition or principal is malformed. */
|
|
5
|
+
/** Thrown when a rule definition, decision attributes, or principal is malformed. */
|
|
6
6
|
export declare class WardConfigError extends WardError {
|
|
7
7
|
}
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
*
|
|
11
|
-
* Catch this to distinguish predicate failures from other errors:
|
|
12
|
-
* ```ts
|
|
13
|
-
* try {
|
|
14
|
-
* ward.explain(principal, resource, action, data);
|
|
15
|
-
* } catch (e) {
|
|
16
|
-
* if (e instanceof WardPredicateError) {
|
|
17
|
-
* console.error(`Predicate in Rule[${e.ruleIndex}] threw`, e.cause);
|
|
18
|
-
* }
|
|
19
|
-
* }
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
export declare class WardPredicateError extends WardError {
|
|
8
|
+
/** Thrown when an application-provided rule condition fails. */
|
|
9
|
+
export declare class WardConditionError extends WardError {
|
|
23
10
|
readonly ruleIndex: number;
|
|
24
11
|
constructor(ruleIndex: number, cause: unknown);
|
|
25
12
|
}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAKjD;AAED
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAKjD;AAED,qFAAqF;AACrF,qBAAa,eAAgB,SAAQ,SAAS;CAAG;AAEjD,gEAAgE;AAChE,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;gBAEf,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO;CAI9C"}
|
package/dist/errors.js
CHANGED
|
@@ -1,16 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
var e = class extends Error {
|
|
3
|
-
constructor(e, t) {
|
|
4
|
-
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
|
-
}
|
|
6
|
-
}, t = class extends e {}, n = class extends e {
|
|
7
|
-
ruleIndex;
|
|
8
|
-
constructor(e, t) {
|
|
9
|
-
let n = t instanceof Error ? t.message : String(t);
|
|
10
|
-
super(`Rule[${e}] threw: ${n}`, { cause: t }), this.ruleIndex = e;
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
//#endregion
|
|
14
|
-
export { t as WardConfigError, e as WardError, n as WardPredicateError };
|
|
15
|
-
|
|
1
|
+
var 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}};export{WardConditionError,WardConfigError,WardError};
|
|
16
2
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** 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 or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** 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"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,SAAU,CAAC,EAGnC,mBAAb,cAAwC,SAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQ,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAY,CACnB,CACF"}
|
package/dist/factory.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./
|
|
1
|
+
const e=require("./_compile.cjs"),t=require("./_match.cjs");let n=require("@vielzeug/arsenal");function createWard(r=[]){let i=Object.freeze(r.flat().map((t,n)=>e.compileRule(t,n))),a=Object.freeze([...new Set(i.flatMap(e=>e.effect===`allow`&&!e.action.includes(`*`)?[e.action]:[]))]),o=(0,n.tapper)();function evaluate(e,n){let r=t.snapshotDecisionInput(e);for(let e=0;e<i.length;e++){let a=i[e];if(t.ruleMatches(a,e,r)){let t=Object.freeze({effect:a.effect,matched:!0,reason:`rule[${e}] ${a.effect===`allow`?`allows`:`denies`} '${r.action}' on '${r.resource}'`,rule:a});return n&&emitDecision(r,t),t}}let a=Object.freeze({effect:`deny`,matched:!1,reason:`no matching rule for '${r.action}' on '${r.resource}' (default deny)`});return n&&emitDecision(r,a),a}function emitDecision(e,t){o.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??a,n=new Set;return t.filter(t=>!n.has(t)&&(n.add(t),evaluate({...e,action:t},!1).effect===`allow`))}function forPrincipal(e){let n=t.snapshotPrincipal(e);return{allowedActions:e=>allowedActions({...e,principal:n}),checkAll:e=>checkAll(e.map(e=>({...e,principal:n}))),decide:e=>decide({...e,principal:n})}}return{allowedActions,checkAll,decide,forPrincipal,knownActions:a,rules:i,tap:(e,t)=>o.tap(e,t)}}exports.createWard=createWard;
|
|
2
2
|
//# sourceMappingURL=factory.cjs.map
|
package/dist/factory.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.cjs","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import type { CompiledEntry } from './_compile';\nimport { compileEntry } from './_compile';\nimport { computeConflicts } from './_conflict';\nimport { warnAnonymousPredicates } from './_dev';\nimport { assertUserPrincipal, isOverriddenBy, matchesRule, pickWinner, toDecision, validatePrincipal } from './_match';\nimport { WardConfigError } from './errors';\nimport type {\n BoundWard,\n BoundWardAllowedActionsInput,\n BoundWardDecisionInput,\n BoundWardRulesInScopeInput,\n NormalizedWardRule,\n Principal,\n UserPrincipal,\n Ward,\n WardAllowedActionsInput,\n WardCheck,\n WardConflict,\n WardDecision,\n WardDecisionInput,\n WardDecisionResult,\n WardEvent,\n WardOptions,\n WardRule,\n WardRulesInScopeInput,\n WardTrace,\n WardTraceCandidate,\n} from './types';\n\nconst warn = warnAnonymousPredicates;\n\n// ---------------------------------------------------------------------------\n// Shared loop cores (validation-free; used by both public API and forUser)\n// ---------------------------------------------------------------------------\n\nfunction coreAllowedActions<TAction extends string, TData>(\n entries: CompiledEntry<TAction, TData>[],\n principal: Principal,\n resource: string,\n knownActions: readonly TAction[],\n data: TData | undefined,\n): TAction[] {\n const seen = new Set<TAction>();\n const result: TAction[] = [];\n\n for (const action of knownActions) {\n if (seen.has(action)) continue;\n\n seen.add(action);\n\n const winner = pickWinner(entries, principal, resource, action, data);\n\n if (winner?.rule.effect === 'allow') result.push(action);\n }\n\n return result;\n}\n\nfunction coreRulesInScope<TAction extends string, TData>(\n entries: CompiledEntry<TAction, TData>[],\n principal: Principal,\n resource: string,\n data: TData | undefined,\n): NormalizedWardRule<TAction, TData>[] {\n const skipPredicate = data === undefined;\n const result: NormalizedWardRule<TAction, TData>[] = [];\n\n for (const entry of entries) {\n if (!matchesRule(entry, principal, resource, undefined, data, skipPredicate)) continue;\n\n result.push(entry.rule as NormalizedWardRule<TAction, TData>);\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an authorization ward from a set of rules.\n *\n * **Winner selection** when multiple rules match a request:\n * 1. Higher `priority` wins.\n * 2. On priority tie, higher specificity score wins (exact > namespace-wildcard > global-wildcard,\n * applied independently to role, resource, and action).\n * 3. On specificity tie, `deny` beats `allow` (denyBonus tiebreaker).\n * 4. On absolute tie (identical priority, specificity, and effect), the rule declared\n * **first in the input array** wins.\n */\nexport function createWard<TAction extends string = string, TData = unknown>(\n rules: readonly (WardRule<TAction, TData> | readonly WardRule<TAction, TData>[])[] = [],\n options: WardOptions<TAction, TData> = {},\n): Ward<TAction, TData> {\n if (options.maxConflicts !== undefined) {\n if (!Number.isFinite(options.maxConflicts) || options.maxConflicts < 0) {\n throw new WardConfigError('maxConflicts must be a finite non-negative number.');\n }\n }\n\n if (options.onConflict !== undefined && typeof options.onConflict !== 'function') {\n throw new WardConfigError('onConflict must be a function.');\n }\n\n const { maxConflicts = Infinity } = options;\n const tappers = new Set<(event: WardEvent<TAction, TData>) => void>();\n const flat: WardRule<TAction, TData>[] = [];\n\n for (const entry of rules) {\n if (Array.isArray(entry)) {\n for (const rule of entry) flat.push(rule);\n } else {\n flat.push(entry as WardRule<TAction, TData>);\n }\n }\n\n const entries = flat.map((rule, i) => compileEntry(rule, i));\n\n // Warn in development when an ANONYMOUS-role rule has a predicate.\n warn(entries);\n\n // -------------------------------------------------------------------------\n // Core decision + logging\n // -------------------------------------------------------------------------\n\n function emitTap(event: WardEvent<TAction, TData>): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect ward behavior.\n }\n }\n }\n\n function evaluateAndLog(\n principal: Principal,\n resource: string,\n action: TAction,\n data: TData | undefined,\n ): WardDecision<TAction, TData> {\n const winner = pickWinner(entries, principal, resource, action, data);\n const decision = toDecision(winner);\n\n emitTap({ action, data, decision, principal, resource });\n\n return decision;\n }\n\n // -------------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------------\n // Request objects avoid call-site ambiguity between resource/action/data and\n // make later API growth additive instead of positional-breaking.\n\n function explain(input: WardDecisionInput<TAction, TData>): WardDecision<TAction, TData> {\n const { action, data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return evaluateAndLog(principal, resource, action, data);\n }\n\n function runCheckAll(\n principal: Principal,\n checks: readonly WardCheck<TAction, TData>[],\n ): WardDecisionResult<TAction, TData>[] {\n return checks.map((check) => ({\n ...evaluateAndLog(principal, check.resource, check.action, check.data),\n action: check.action,\n resource: check.resource,\n }));\n }\n\n function checkAll(\n principal: Principal,\n checks: readonly WardCheck<TAction, TData>[],\n ): WardDecisionResult<TAction, TData>[] {\n if (checks.length === 0) return [];\n\n validatePrincipal(principal);\n\n return runCheckAll(principal, checks);\n }\n\n function allowedActions(input: WardAllowedActionsInput<TAction, TData>): TAction[] {\n const { data, knownActions, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return coreAllowedActions(entries, principal, resource, knownActions, data);\n }\n\n function rulesInScope(\n input: WardRulesInScopeInput<TData>,\n ): ReadonlyArray<Readonly<NormalizedWardRule<TAction, TData>>> {\n const { data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return coreRulesInScope(entries, principal, resource, data);\n }\n\n function trace(input: WardDecisionInput<TAction, TData>): WardTrace<TAction, TData> {\n const { action, data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n const matching: CompiledEntry<TAction, TData>[] = [];\n\n for (const entry of entries) {\n if (matchesRule(entry, principal, resource, action, data)) {\n matching.push(entry);\n }\n }\n\n let winner: CompiledEntry<TAction, TData> | undefined;\n\n for (const entry of matching) {\n if (!winner || isOverriddenBy(winner, entry)) winner = entry;\n }\n\n const decision = toDecision(winner);\n\n const candidates: WardTraceCandidate<TAction, TData>[] = matching.map((entry) => ({\n index: entry.index,\n priority: entry.priority,\n rule: entry.rule,\n score: entry.score,\n won: entry === winner,\n }));\n\n return { candidates, decision };\n }\n\n function forUser(principal: UserPrincipal): BoundWard<TAction, TData> {\n assertUserPrincipal(principal);\n\n const snap: UserPrincipal = {\n attributes: principal.attributes ? structuredClone(principal.attributes) : undefined,\n id: principal.id,\n roles: [...principal.roles],\n };\n\n return {\n allowedActions: (input: BoundWardAllowedActionsInput<TAction, TData>) =>\n coreAllowedActions(entries, snap, input.resource, input.knownActions, input.data),\n checkAll: (checks) => (checks.length === 0 ? [] : runCheckAll(snap, checks)),\n explain: (input: BoundWardDecisionInput<TAction, TData>) =>\n evaluateAndLog(snap, input.resource, input.action, input.data),\n rulesInScope: (input: BoundWardRulesInScopeInput<TData>) =>\n coreRulesInScope(entries, snap, input.resource, input.data),\n trace: (input: BoundWardDecisionInput<TAction, TData>) =>\n trace({ action: input.action, data: input.data, principal: snap, resource: input.resource }),\n };\n }\n\n // -------------------------------------------------------------------------\n // Conflict detection (lazy, cached)\n // -------------------------------------------------------------------------\n\n let conflictsCache: readonly WardConflict<TAction, TData>[] | undefined;\n\n function detectConflicts(): readonly WardConflict<TAction, TData>[] {\n return (conflictsCache ??= Object.freeze(computeConflicts(entries, maxConflicts)));\n }\n\n if (options.strict || options.onConflict) {\n const conflicts = detectConflicts();\n\n if (conflicts.length > 0) {\n if (options.onConflict) conflicts.forEach(options.onConflict);\n\n if (options.strict) {\n const details = conflicts\n .map((c) =>\n c.kind === 'duplicate'\n ? `Rule[${c.indexB}] ${c.kind} of Rule[${c.indexA}]`\n : `Rule[${c.shadowedIndex}] ${c.kind} by Rule[${c.shadowingIndex}]`,\n )\n .join('; ');\n\n throw new WardConfigError(`${conflicts.length} rule conflict(s) detected: ${details}`);\n }\n }\n }\n\n function tap(handler: (event: WardEvent<TAction, TData>) => void, opts?: { signal?: AbortSignal }): () => void {\n tappers.add(handler);\n\n const onAbort = () => tappers.delete(handler);\n\n if (opts?.signal) {\n if (opts.signal.aborted) {\n tappers.delete(handler);\n return () => {};\n }\n opts.signal.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n tappers.delete(handler);\n opts?.signal?.removeEventListener('abort', onAbort);\n };\n }\n\n return { allowedActions, checkAll, detectConflicts, explain, forUser, rulesInScope, tap, trace };\n}\n"],"mappings":"mHA6BA,IAAM,sBAAO,CAAA,CAAA,wBAMb,SAAS,EACP,EACA,EACA,EACA,EACA,EACW,CACX,IAAM,EAAO,IAAI,IACX,EAAoB,CAAC,EAE3B,IAAK,IAAM,KAAU,EACf,EAAK,IAAI,CAAM,IAEnB,EAAK,IAAI,CAAM,EAEA,EAAA,WAAW,EAAS,EAAW,EAAU,EAAQ,CAE5D,CAAA,EAAQ,KAAK,SAAW,SAAS,EAAO,KAAK,CAAM,GAGzD,OAAO,CACT,CAEA,SAAS,EACP,EACA,EACA,EACA,EACsC,CACtC,IAAM,E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,EAAK,CAAC,CAC/D,CAEA,UAAa,CACX,EAAQ,OAAO,CAAO,EACtB,GAAM,QAAQ,oBAAoB,QAAS,CAAO,CACpD,CACF,CAEA,MAAO,CAAE,iBAAgB,WAAU,kBAAiB,UAAS,UAAS,eAAc,MAAK,OAAM,CACjG"}
|
|
1
|
+
{"version":3,"file":"factory.cjs","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,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":"+FAgCA,SAAgB,WAKd,EAGM,CAAC,EACgC,CACvC,IAAM,EAAW,OAAO,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,EAAM,IAAU,EAAA,YAAY,EAAM,CAAK,CAAC,CAAC,EACpF,EAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACL,EAAS,QAAS,GAAU,EAAK,SAAW,SAAW,CAAC,EAAK,OAAO,SAAS,GAAG,EAAI,CAAC,EAAK,MAAM,EAAI,CAAC,CAAE,CACzG,CACF,CAAC,EACK,GAAA,EAAU,EAAA,OAAA,CAAmD,EAEnE,SAAS,SACP,EACA,EAC+C,CAC/C,IAAM,EAAa,EAAA,sBAAsB,CAAK,EAE9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAS,OAAQ,IAAS,CACpD,IAAM,EAAO,EAAS,GAEtB,GAAI,EAAA,YAAY,EAAM,EAAO,CAAU,EAAG,CACxC,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,EAAK,OACb,QAAS,GACT,OAAQ,QAAQ,EAAM,IAAI,EAAK,SAAW,QAAU,SAAW,SAAS,IAAI,EAAW,OAAO,QAAQ,EAAW,SAAS,GAC1H,MACF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CACF,CAEA,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,OACR,QAAS,GACT,OAAQ,yBAAyB,EAAW,OAAO,QAAQ,EAAW,SAAS,iBACjF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CAEA,SAAS,aACP,EACA,EACM,CACN,EAAQ,KAAK,OAAO,OAAO,CAAE,WAAU,QAAO,KAAM,UAAoB,CAAC,CAAC,CAC5E,CAEA,SAAS,OACP,EAC+C,CAC/C,OAAO,SAAS,EAAO,EAAI,CAC7B,CAEA,SAAS,SACP,EACiD,CACjD,OAAO,EAAO,IAAI,MAAM,CAC1B,CAEA,SAAS,eAAe,EAKV,CACZ,IAAM,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,EAAA,kBAAkB,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/factory.d.ts
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
import type { Ward,
|
|
1
|
+
import type { Ward, WardAttributes, WardRule } from './types';
|
|
2
2
|
/**
|
|
3
|
-
* Creates an authorization ward from
|
|
3
|
+
* Creates an authorization ward from an ordered list of rules.
|
|
4
4
|
*
|
|
5
|
-
* **
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
5
|
+
* **Decision model**: rules are evaluated in declaration order; the first rule
|
|
6
|
+
* that matches the request wins. If no rule matches, the decision is **deny**
|
|
7
|
+
* (default deny). There is no priority, specificity scoring, or conflict
|
|
8
|
+
* detection — order is the only tiebreaker.
|
|
9
|
+
*
|
|
10
|
+
* A rule matches when:
|
|
11
|
+
* 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).
|
|
12
|
+
* 2. Its `resource` pattern matches the requested resource.
|
|
13
|
+
* 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`
|
|
14
|
+
* matches a null principal, and `WILDCARD` matches any authenticated principal.
|
|
15
|
+
* 4. Every key in its declarative `attributes` is present and equal in the
|
|
16
|
+
* request's `attributes` (deep equality).
|
|
17
|
+
* 5. Its `condition` escape-hatch callback (if any) returns `true`.
|
|
12
18
|
*/
|
|
13
|
-
export declare function createWard<TAction extends string = string,
|
|
19
|
+
export declare function createWard<TAction extends string = string, TResource extends string = string, TAttributes extends WardAttributes = WardAttributes>(rules?: readonly (WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>> | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[])[]): Ward<TAction, TResource, TAttributes>;
|
|
14
20
|
//# sourceMappingURL=factory.d.ts.map
|
package/dist/factory.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAGV,IAAI,EACJ,cAAc,EAId,QAAQ,EACT,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CACxB,OAAO,SAAS,MAAM,GAAG,MAAM,EAC/B,SAAS,SAAS,MAAM,GAAG,MAAM,EACjC,WAAW,SAAS,cAAc,GAAG,cAAc,EAEnD,KAAK,GAAE,SAAS,CACZ,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,GACpE,SAAS,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAClF,EAAO,GACP,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,CA+FvC"}
|
package/dist/factory.js
CHANGED
|
@@ -1,138 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { compileEntry as t } from "./_compile.js";
|
|
3
|
-
import { assertUserPrincipal as n, isOverriddenBy as r, matchesRule as i, pickWinner as a, toDecision as o, validatePrincipal as s } from "./_match.js";
|
|
4
|
-
import { computeConflicts as c } from "./_conflict.js";
|
|
5
|
-
import { warnAnonymousPredicates as l } from "./_dev.js";
|
|
6
|
-
//#region src/factory.ts
|
|
7
|
-
var u = l;
|
|
8
|
-
function d(e, t, n, r, i) {
|
|
9
|
-
let o = /* @__PURE__ */ new Set(), s = [];
|
|
10
|
-
for (let c of r) o.has(c) || (o.add(c), a(e, t, n, c, i)?.rule.effect === "allow" && s.push(c));
|
|
11
|
-
return s;
|
|
12
|
-
}
|
|
13
|
-
function f(e, t, n, r) {
|
|
14
|
-
let a = r === void 0, o = [];
|
|
15
|
-
for (let s of e) i(s, t, n, void 0, r, a) && o.push(s.rule);
|
|
16
|
-
return o;
|
|
17
|
-
}
|
|
18
|
-
function p(l = [], p = {}) {
|
|
19
|
-
if (p.maxConflicts !== void 0 && (!Number.isFinite(p.maxConflicts) || p.maxConflicts < 0)) throw new e("maxConflicts must be a finite non-negative number.");
|
|
20
|
-
if (p.onConflict !== void 0 && typeof p.onConflict != "function") throw new e("onConflict must be a function.");
|
|
21
|
-
let { maxConflicts: m = Infinity } = p, h = /* @__PURE__ */ new Set(), g = [];
|
|
22
|
-
for (let e of l) if (Array.isArray(e)) for (let t of e) g.push(t);
|
|
23
|
-
else g.push(e);
|
|
24
|
-
let _ = g.map((e, n) => t(e, n));
|
|
25
|
-
u(_);
|
|
26
|
-
function v(e) {
|
|
27
|
-
if (h.size !== 0) for (let t of h) try {
|
|
28
|
-
t(e);
|
|
29
|
-
} catch {}
|
|
30
|
-
}
|
|
31
|
-
function y(e, t, n, r) {
|
|
32
|
-
let i = a(_, e, t, n, r), s = o(i);
|
|
33
|
-
return v({
|
|
34
|
-
action: n,
|
|
35
|
-
data: r,
|
|
36
|
-
decision: s,
|
|
37
|
-
principal: e,
|
|
38
|
-
resource: t
|
|
39
|
-
}), s;
|
|
40
|
-
}
|
|
41
|
-
function b(e) {
|
|
42
|
-
let { action: t, data: n, principal: r, resource: i } = e;
|
|
43
|
-
return s(r), y(r, i, t, n);
|
|
44
|
-
}
|
|
45
|
-
function x(e, t) {
|
|
46
|
-
return t.map((t) => ({
|
|
47
|
-
...y(e, t.resource, t.action, t.data),
|
|
48
|
-
action: t.action,
|
|
49
|
-
resource: t.resource
|
|
50
|
-
}));
|
|
51
|
-
}
|
|
52
|
-
function S(e, t) {
|
|
53
|
-
return t.length === 0 ? [] : (s(e), x(e, t));
|
|
54
|
-
}
|
|
55
|
-
function C(e) {
|
|
56
|
-
let { data: t, knownActions: n, principal: r, resource: i } = e;
|
|
57
|
-
return s(r), d(_, r, i, n, t);
|
|
58
|
-
}
|
|
59
|
-
function w(e) {
|
|
60
|
-
let { data: t, principal: n, resource: r } = e;
|
|
61
|
-
return s(n), f(_, n, r, t);
|
|
62
|
-
}
|
|
63
|
-
function T(e) {
|
|
64
|
-
let { action: t, data: n, principal: a, resource: c } = e;
|
|
65
|
-
s(a);
|
|
66
|
-
let l = [];
|
|
67
|
-
for (let e of _) i(e, a, c, t, n) && l.push(e);
|
|
68
|
-
let u;
|
|
69
|
-
for (let e of l) (!u || r(u, e)) && (u = e);
|
|
70
|
-
let d = o(u);
|
|
71
|
-
return {
|
|
72
|
-
candidates: l.map((e) => ({
|
|
73
|
-
index: e.index,
|
|
74
|
-
priority: e.priority,
|
|
75
|
-
rule: e.rule,
|
|
76
|
-
score: e.score,
|
|
77
|
-
won: e === u
|
|
78
|
-
})),
|
|
79
|
-
decision: d
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
function E(e) {
|
|
83
|
-
n(e);
|
|
84
|
-
let t = {
|
|
85
|
-
attributes: e.attributes ? structuredClone(e.attributes) : void 0,
|
|
86
|
-
id: e.id,
|
|
87
|
-
roles: [...e.roles]
|
|
88
|
-
};
|
|
89
|
-
return {
|
|
90
|
-
allowedActions: (e) => d(_, t, e.resource, e.knownActions, e.data),
|
|
91
|
-
checkAll: (e) => e.length === 0 ? [] : x(t, e),
|
|
92
|
-
explain: (e) => y(t, e.resource, e.action, e.data),
|
|
93
|
-
rulesInScope: (e) => f(_, t, e.resource, e.data),
|
|
94
|
-
trace: (e) => T({
|
|
95
|
-
action: e.action,
|
|
96
|
-
data: e.data,
|
|
97
|
-
principal: t,
|
|
98
|
-
resource: e.resource
|
|
99
|
-
})
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
let D;
|
|
103
|
-
function O() {
|
|
104
|
-
return D ??= Object.freeze(c(_, m));
|
|
105
|
-
}
|
|
106
|
-
if (p.strict || p.onConflict) {
|
|
107
|
-
let t = O();
|
|
108
|
-
if (t.length > 0 && (p.onConflict && t.forEach(p.onConflict), p.strict)) {
|
|
109
|
-
let n = t.map((e) => e.kind === "duplicate" ? `Rule[${e.indexB}] ${e.kind} of Rule[${e.indexA}]` : `Rule[${e.shadowedIndex}] ${e.kind} by Rule[${e.shadowingIndex}]`).join("; ");
|
|
110
|
-
throw new e(`${t.length} rule conflict(s) detected: ${n}`);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function k(e, t) {
|
|
114
|
-
h.add(e);
|
|
115
|
-
let n = () => h.delete(e);
|
|
116
|
-
if (t?.signal) {
|
|
117
|
-
if (t.signal.aborted) return h.delete(e), () => {};
|
|
118
|
-
t.signal.addEventListener("abort", n, { once: !0 });
|
|
119
|
-
}
|
|
120
|
-
return () => {
|
|
121
|
-
h.delete(e), t?.signal?.removeEventListener("abort", n);
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
return {
|
|
125
|
-
allowedActions: C,
|
|
126
|
-
checkAll: S,
|
|
127
|
-
detectConflicts: O,
|
|
128
|
-
explain: b,
|
|
129
|
-
forUser: E,
|
|
130
|
-
rulesInScope: w,
|
|
131
|
-
tap: k,
|
|
132
|
-
trace: T
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
//#endregion
|
|
136
|
-
export { p as createWard };
|
|
137
|
-
|
|
1
|
+
import{compileRule as e}from"./_compile.js";import{ruleMatches as t,snapshotDecisionInput as n,snapshotPrincipal as r}from"./_match.js";import{tapper as i}from"@vielzeug/arsenal";function createWard(a=[]){let o=Object.freeze(a.flat().map((t,n)=>e(t,n))),s=Object.freeze([...new Set(o.flatMap(e=>e.effect===`allow`&&!e.action.includes(`*`)?[e.action]:[]))]),c=i();function evaluate(e,r){let i=n(e);for(let e=0;e<o.length;e++){let n=o[e];if(t(n,e,i)){let t=Object.freeze({effect:n.effect,matched:!0,reason:`rule[${e}] ${n.effect===`allow`?`allows`:`denies`} '${i.action}' on '${i.resource}'`,rule:n});return r&&emitDecision(i,t),t}}let a=Object.freeze({effect:`deny`,matched:!1,reason:`no matching rule for '${i.action}' on '${i.resource}' (default deny)`});return r&&emitDecision(i,a),a}function emitDecision(e,t){c.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??s,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=r(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:s,rules:o,tap:(e,t)=>c.tap(e,t)}}export{createWard};
|
|
138
2
|
//# sourceMappingURL=factory.js.map
|
package/dist/factory.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import type { CompiledEntry } from './_compile';\nimport { compileEntry } from './_compile';\nimport { computeConflicts } from './_conflict';\nimport { warnAnonymousPredicates } from './_dev';\nimport { assertUserPrincipal, isOverriddenBy, matchesRule, pickWinner, toDecision, validatePrincipal } from './_match';\nimport { WardConfigError } from './errors';\nimport type {\n BoundWard,\n BoundWardAllowedActionsInput,\n BoundWardDecisionInput,\n BoundWardRulesInScopeInput,\n NormalizedWardRule,\n Principal,\n UserPrincipal,\n Ward,\n WardAllowedActionsInput,\n WardCheck,\n WardConflict,\n WardDecision,\n WardDecisionInput,\n WardDecisionResult,\n WardEvent,\n WardOptions,\n WardRule,\n WardRulesInScopeInput,\n WardTrace,\n WardTraceCandidate,\n} from './types';\n\nconst warn = warnAnonymousPredicates;\n\n// ---------------------------------------------------------------------------\n// Shared loop cores (validation-free; used by both public API and forUser)\n// ---------------------------------------------------------------------------\n\nfunction coreAllowedActions<TAction extends string, TData>(\n entries: CompiledEntry<TAction, TData>[],\n principal: Principal,\n resource: string,\n knownActions: readonly TAction[],\n data: TData | undefined,\n): TAction[] {\n const seen = new Set<TAction>();\n const result: TAction[] = [];\n\n for (const action of knownActions) {\n if (seen.has(action)) continue;\n\n seen.add(action);\n\n const winner = pickWinner(entries, principal, resource, action, data);\n\n if (winner?.rule.effect === 'allow') result.push(action);\n }\n\n return result;\n}\n\nfunction coreRulesInScope<TAction extends string, TData>(\n entries: CompiledEntry<TAction, TData>[],\n principal: Principal,\n resource: string,\n data: TData | undefined,\n): NormalizedWardRule<TAction, TData>[] {\n const skipPredicate = data === undefined;\n const result: NormalizedWardRule<TAction, TData>[] = [];\n\n for (const entry of entries) {\n if (!matchesRule(entry, principal, resource, undefined, data, skipPredicate)) continue;\n\n result.push(entry.rule as NormalizedWardRule<TAction, TData>);\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an authorization ward from a set of rules.\n *\n * **Winner selection** when multiple rules match a request:\n * 1. Higher `priority` wins.\n * 2. On priority tie, higher specificity score wins (exact > namespace-wildcard > global-wildcard,\n * applied independently to role, resource, and action).\n * 3. On specificity tie, `deny` beats `allow` (denyBonus tiebreaker).\n * 4. On absolute tie (identical priority, specificity, and effect), the rule declared\n * **first in the input array** wins.\n */\nexport function createWard<TAction extends string = string, TData = unknown>(\n rules: readonly (WardRule<TAction, TData> | readonly WardRule<TAction, TData>[])[] = [],\n options: WardOptions<TAction, TData> = {},\n): Ward<TAction, TData> {\n if (options.maxConflicts !== undefined) {\n if (!Number.isFinite(options.maxConflicts) || options.maxConflicts < 0) {\n throw new WardConfigError('maxConflicts must be a finite non-negative number.');\n }\n }\n\n if (options.onConflict !== undefined && typeof options.onConflict !== 'function') {\n throw new WardConfigError('onConflict must be a function.');\n }\n\n const { maxConflicts = Infinity } = options;\n const tappers = new Set<(event: WardEvent<TAction, TData>) => void>();\n const flat: WardRule<TAction, TData>[] = [];\n\n for (const entry of rules) {\n if (Array.isArray(entry)) {\n for (const rule of entry) flat.push(rule);\n } else {\n flat.push(entry as WardRule<TAction, TData>);\n }\n }\n\n const entries = flat.map((rule, i) => compileEntry(rule, i));\n\n // Warn in development when an ANONYMOUS-role rule has a predicate.\n warn(entries);\n\n // -------------------------------------------------------------------------\n // Core decision + logging\n // -------------------------------------------------------------------------\n\n function emitTap(event: WardEvent<TAction, TData>): void {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect ward behavior.\n }\n }\n }\n\n function evaluateAndLog(\n principal: Principal,\n resource: string,\n action: TAction,\n data: TData | undefined,\n ): WardDecision<TAction, TData> {\n const winner = pickWinner(entries, principal, resource, action, data);\n const decision = toDecision(winner);\n\n emitTap({ action, data, decision, principal, resource });\n\n return decision;\n }\n\n // -------------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------------\n // Request objects avoid call-site ambiguity between resource/action/data and\n // make later API growth additive instead of positional-breaking.\n\n function explain(input: WardDecisionInput<TAction, TData>): WardDecision<TAction, TData> {\n const { action, data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return evaluateAndLog(principal, resource, action, data);\n }\n\n function runCheckAll(\n principal: Principal,\n checks: readonly WardCheck<TAction, TData>[],\n ): WardDecisionResult<TAction, TData>[] {\n return checks.map((check) => ({\n ...evaluateAndLog(principal, check.resource, check.action, check.data),\n action: check.action,\n resource: check.resource,\n }));\n }\n\n function checkAll(\n principal: Principal,\n checks: readonly WardCheck<TAction, TData>[],\n ): WardDecisionResult<TAction, TData>[] {\n if (checks.length === 0) return [];\n\n validatePrincipal(principal);\n\n return runCheckAll(principal, checks);\n }\n\n function allowedActions(input: WardAllowedActionsInput<TAction, TData>): TAction[] {\n const { data, knownActions, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return coreAllowedActions(entries, principal, resource, knownActions, data);\n }\n\n function rulesInScope(\n input: WardRulesInScopeInput<TData>,\n ): ReadonlyArray<Readonly<NormalizedWardRule<TAction, TData>>> {\n const { data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n return coreRulesInScope(entries, principal, resource, data);\n }\n\n function trace(input: WardDecisionInput<TAction, TData>): WardTrace<TAction, TData> {\n const { action, data, principal, resource } = input;\n\n validatePrincipal(principal);\n\n const matching: CompiledEntry<TAction, TData>[] = [];\n\n for (const entry of entries) {\n if (matchesRule(entry, principal, resource, action, data)) {\n matching.push(entry);\n }\n }\n\n let winner: CompiledEntry<TAction, TData> | undefined;\n\n for (const entry of matching) {\n if (!winner || isOverriddenBy(winner, entry)) winner = entry;\n }\n\n const decision = toDecision(winner);\n\n const candidates: WardTraceCandidate<TAction, TData>[] = matching.map((entry) => ({\n index: entry.index,\n priority: entry.priority,\n rule: entry.rule,\n score: entry.score,\n won: entry === winner,\n }));\n\n return { candidates, decision };\n }\n\n function forUser(principal: UserPrincipal): BoundWard<TAction, TData> {\n assertUserPrincipal(principal);\n\n const snap: UserPrincipal = {\n attributes: principal.attributes ? structuredClone(principal.attributes) : undefined,\n id: principal.id,\n roles: [...principal.roles],\n };\n\n return {\n allowedActions: (input: BoundWardAllowedActionsInput<TAction, TData>) =>\n coreAllowedActions(entries, snap, input.resource, input.knownActions, input.data),\n checkAll: (checks) => (checks.length === 0 ? [] : runCheckAll(snap, checks)),\n explain: (input: BoundWardDecisionInput<TAction, TData>) =>\n evaluateAndLog(snap, input.resource, input.action, input.data),\n rulesInScope: (input: BoundWardRulesInScopeInput<TData>) =>\n coreRulesInScope(entries, snap, input.resource, input.data),\n trace: (input: BoundWardDecisionInput<TAction, TData>) =>\n trace({ action: input.action, data: input.data, principal: snap, resource: input.resource }),\n };\n }\n\n // -------------------------------------------------------------------------\n // Conflict detection (lazy, cached)\n // -------------------------------------------------------------------------\n\n let conflictsCache: readonly WardConflict<TAction, TData>[] | undefined;\n\n function detectConflicts(): readonly WardConflict<TAction, TData>[] {\n return (conflictsCache ??= Object.freeze(computeConflicts(entries, maxConflicts)));\n }\n\n if (options.strict || options.onConflict) {\n const conflicts = detectConflicts();\n\n if (conflicts.length > 0) {\n if (options.onConflict) conflicts.forEach(options.onConflict);\n\n if (options.strict) {\n const details = conflicts\n .map((c) =>\n c.kind === 'duplicate'\n ? `Rule[${c.indexB}] ${c.kind} of Rule[${c.indexA}]`\n : `Rule[${c.shadowedIndex}] ${c.kind} by Rule[${c.shadowingIndex}]`,\n )\n .join('; ');\n\n throw new WardConfigError(`${conflicts.length} rule conflict(s) detected: ${details}`);\n }\n }\n }\n\n function tap(handler: (event: WardEvent<TAction, TData>) => void, opts?: { signal?: AbortSignal }): () => void {\n tappers.add(handler);\n\n const onAbort = () => tappers.delete(handler);\n\n if (opts?.signal) {\n if (opts.signal.aborted) {\n tappers.delete(handler);\n return () => {};\n }\n opts.signal.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n tappers.delete(handler);\n opts?.signal?.removeEventListener('abort', onAbort);\n };\n }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ACrE,CAAC,CACA,KAAK,IAAI;GAEZ,MAAM,IAAI,EAAgB,GAAG,EAAU,OAAO,8BAA8B,GAAS;EACvF;CAEJ;CAEA,SAAS,EAAI,GAAqD,GAA6C;EAC7G,EAAQ,IAAI,CAAO;EAEnB,IAAM,UAAgB,EAAQ,OAAO,CAAO;EAE5C,IAAI,GAAM,QAAQ;GAChB,IAAI,EAAK,OAAO,SAEd,OADA,EAAQ,OAAO,CAAO,SACT,CAAC;GAEhB,EAAK,OAAO,iBAAiB,SAAS,GAAS,EAAE,MAAM,GAAK,CAAC;EAC/D;EAEA,aAAa;GAEX,AADA,EAAQ,OAAO,CAAO,GACtB,GAAM,QAAQ,oBAAoB,SAAS,CAAO;EACpD;CACF;CAEA,OAAO;EAAE;EAAgB;EAAU;EAAiB;EAAS;EAAS;EAAc;EAAK;CAAM;AACjG"}
|
|
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,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":"mLAgCA,SAAgB,WAKd,EAGM,CAAC,EACgC,CACvC,IAAM,EAAW,OAAO,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,EAAM,IAAU,EAAY,EAAM,CAAK,CAAC,CAAC,EACpF,EAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACL,EAAS,QAAS,GAAU,EAAK,SAAW,SAAW,CAAC,EAAK,OAAO,SAAS,GAAG,EAAI,CAAC,EAAK,MAAM,EAAI,CAAC,CAAE,CACzG,CACF,CAAC,EACK,EAAU,EAAmD,EAEnE,SAAS,SACP,EACA,EAC+C,CAC/C,IAAM,EAAa,EAAsB,CAAK,EAE9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAS,OAAQ,IAAS,CACpD,IAAM,EAAO,EAAS,GAEtB,GAAI,EAAY,EAAM,EAAO,CAAU,EAAG,CACxC,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,EAAK,OACb,QAAS,GACT,OAAQ,QAAQ,EAAM,IAAI,EAAK,SAAW,QAAU,SAAW,SAAS,IAAI,EAAW,OAAO,QAAQ,EAAW,SAAS,GAC1H,MACF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CACF,CAEA,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,OACR,QAAS,GACT,OAAQ,yBAAyB,EAAW,OAAO,QAAQ,EAAW,SAAS,iBACjF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CAEA,SAAS,aACP,EACA,EACM,CACN,EAAQ,KAAK,OAAO,OAAO,CAAE,WAAU,QAAO,KAAM,UAAoB,CAAC,CAAC,CAC5E,CAEA,SAAS,OACP,EAC+C,CAC/C,OAAO,SAAS,EAAO,EAAI,CAC7B,CAEA,SAAS,SACP,EACiD,CACjD,OAAO,EAAO,IAAI,MAAM,CAC1B,CAEA,SAAS,eAAe,EAKV,CACZ,IAAM,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("./
|
|
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
|
-
export { allow, deny, predicate } from './builder';
|
|
2
1
|
export { ANONYMOUS, WILDCARD } from './constants';
|
|
3
|
-
export { WardConfigError, WardError
|
|
2
|
+
export { WardConditionError, WardConfigError, WardError } from './errors';
|
|
4
3
|
export { createWard } from './factory';
|
|
5
|
-
export { matchesPattern
|
|
6
|
-
export
|
|
4
|
+
export { matchesPattern } from './resource';
|
|
5
|
+
export { allow, deny, predicate } from './rules';
|
|
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,
|
|
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 { ANONYMOUS as r, WILDCARD as i } from "./constants.js";
|
|
3
|
-
import { WardConfigError as a, WardError as o, WardPredicateError as s } from "./errors.js";
|
|
4
|
-
import { matchesPattern as c, patternCovers as l } from "./resource.js";
|
|
5
|
-
import { createWard as u } from "./factory.js";
|
|
6
|
-
export { r as ANONYMOUS, i as WILDCARD, a as WardConfigError, o as WardError, s as WardPredicateError, e as allow, u as createWard, t as deny, c as matchesPattern, l as patternCovers, n 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 — 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
|
|
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
|
@@ -20,22 +20,4 @@
|
|
|
20
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 — 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
|
|
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
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
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
|
+
//# sourceMappingURL=rules.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { WardAttributes, WardCondition, WardPattern, WardRule } from './types';
|
|
2
|
+
type RuleOptions<TAttributes extends WardAttributes> = Readonly<{
|
|
3
|
+
when?: WardCondition<TAttributes>;
|
|
4
|
+
}>;
|
|
5
|
+
export declare const allow: <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>[];
|
|
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
|
+
export declare const predicate: {
|
|
8
|
+
readonly and: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(...conditions: readonly WardCondition<TAttributes>[]) => WardCondition<TAttributes>;
|
|
9
|
+
readonly not: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(condition: WardCondition<TAttributes>) => WardCondition<TAttributes>;
|
|
10
|
+
readonly or: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(...conditions: readonly WardCondition<TAttributes>[]) => WardCondition<TAttributes>;
|
|
11
|
+
readonly owns: <TAttributes extends WardAttributes = Readonly<Record<string, import("./types").WardAttributeValue>>>(attribute: keyof TAttributes & string) => WardCondition<TAttributes>;
|
|
12
|
+
};
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=rules.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
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};
|
|
2
|
+
//# sourceMappingURL=rules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|