@authup/access 1.0.0-beta.52 → 1.0.0-beta.54
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/dist/index.d.mts +150 -24
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +309 -89
- package/dist/index.mjs.map +1 -1
- package/dist/permission/evaluator/module.d.ts +12 -1
- package/dist/permission/evaluator/module.d.ts.map +1 -1
- package/dist/permission/evaluator/types.d.ts +48 -0
- package/dist/permission/evaluator/types.d.ts.map +1 -1
- package/dist/permission/helpers/aggregate.d.ts +1 -1
- package/dist/permission/realm-scope/constants.d.ts +1 -1
- package/dist/permission/realm-scope/constants.d.ts.map +1 -1
- package/dist/permission/types.d.ts +7 -7
- package/dist/permission/types.d.ts.map +1 -1
- package/dist/policy/built-in/attribute-names/evaluator.d.ts +1 -0
- package/dist/policy/built-in/attribute-names/evaluator.d.ts.map +1 -1
- package/dist/policy/built-in/attributes/evaluator.d.ts +5 -0
- package/dist/policy/built-in/attributes/evaluator.d.ts.map +1 -1
- package/dist/policy/built-in/attributes/types.d.ts +2 -2
- package/dist/policy/built-in/attributes/types.d.ts.map +1 -1
- package/dist/policy/built-in/composite/evaluator.d.ts.map +1 -1
- package/dist/policy/built-in/composite/types.d.ts +1 -1
- package/dist/policy/built-in/composite/types.d.ts.map +1 -1
- package/dist/policy/built-in/constants.d.ts +0 -1
- package/dist/policy/built-in/constants.d.ts.map +1 -1
- package/dist/policy/built-in/identity/evaluator.d.ts +1 -0
- package/dist/policy/built-in/identity/evaluator.d.ts.map +1 -1
- package/dist/policy/built-in/identity/types.d.ts +1 -1
- package/dist/policy/built-in/permission-binding/module.d.ts +1 -0
- package/dist/policy/built-in/permission-binding/module.d.ts.map +1 -1
- package/dist/policy/built-in/realm-match/evaluator.d.ts +14 -0
- package/dist/policy/built-in/realm-match/evaluator.d.ts.map +1 -1
- package/dist/policy/built-in/realm-match/types.d.ts +6 -6
- package/dist/policy/built-in/realm-match/types.d.ts.map +1 -1
- package/dist/policy/built-in/time/types.d.ts +3 -3
- package/dist/policy/built-in/time/types.d.ts.map +1 -1
- package/dist/policy/built-in/types.d.ts +2 -0
- package/dist/policy/built-in/types.d.ts.map +1 -1
- package/dist/policy/engine/module.d.ts.map +1 -1
- package/dist/policy/evaluation/context/define.d.ts.map +1 -1
- package/dist/policy/evaluation/context/types.d.ts +7 -0
- package/dist/policy/evaluation/context/types.d.ts.map +1 -1
- package/dist/policy/evaluation/types.d.ts +42 -0
- package/dist/policy/evaluation/types.d.ts.map +1 -1
- package/package.json +6 -4
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["normalizeDate","toDate"],"sources":["../src/permission/error/module.ts","../src/permission/error/check.ts","../src/permission/realm-scope/constants.ts","../src/permission/realm-scope/helpers.ts","../src/permission/helpers/key.ts","../src/permission/helpers/aggregate.ts","../src/permission/helpers/equal.ts","../src/permission/helpers/grant.ts","../src/permission/provider/memory.ts","../src/policy/error/module.ts","../src/policy/error/check.ts","../src/policy/engine/module.ts","../src/policy/data.ts","../src/policy/evaluation/context/define.ts","../src/policy/issue/constants.ts","../src/policy/issue/define.ts","../src/policy/helpers/invert.ts","../src/policy/built-in/attribute-names/validator.ts","../src/policy/built-in/attributes/define.ts","../src/policy/built-in/constants.ts","../src/policy/built-in/attributes/validator.ts","../src/policy/built-in/attributes/evaluator.ts","../src/policy/built-in/attribute-names/evaluator.ts","../src/policy/built-in/composite/validator.ts","../src/policy/built-in/composite/evaluator.ts","../src/policy/built-in/composite/helper.ts","../src/policy/built-in/date/validator.ts","../src/policy/built-in/date/evaluator.ts","../src/policy/built-in/identity/data/validator.ts","../src/policy/built-in/identity/validator.ts","../src/policy/built-in/identity/evaluator.ts","../src/policy/built-in/permission-binding/validator.ts","../src/policy/built-in/permission-binding/module.ts","../src/policy/built-in/realm-match/validator.ts","../src/policy/built-in/realm-match/evaluator.ts","../src/policy/built-in/time/constants.ts","../src/policy/built-in/time/helpers.ts","../src/policy/built-in/time/validator.ts","../src/policy/built-in/time/evaluator.ts","../src/policy/built-in/define.ts","../src/policy/constants.ts","../src/policy/input.ts","../src/permission/evaluator/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { AuthupErrorOptions } from '@authup/errors';\nimport { AuthupError, ErrorCode, markInstanceof } from '@authup/errors';\nimport type { PolicyIssue } from '../../policy';\n\nexport const PERMISSION_ERROR_INSTANCE = Symbol.for('@authup/access/PermissionError');\n\nexport class PermissionError extends AuthupError {\n constructor(options: AuthupErrorOptions = {}) {\n super({\n ...options,\n message: options.message || 'A permission error occurred.',\n code: options.code || ErrorCode.PERMISSION_DENIED,\n });\n markInstanceof(this, PERMISSION_ERROR_INSTANCE);\n }\n\n addIssue(data: PolicyIssue) {\n this.issues.push(data);\n }\n\n addIssues(data: PolicyIssue[]) {\n this.issues.push(...data);\n }\n\n static notFound(name: string) {\n return new PermissionError({\n message: `The permission ${name} was not found.`,\n code: ErrorCode.PERMISSION_NOT_FOUND,\n });\n }\n\n static denied(name: string) {\n return new PermissionError({\n message: `The permission ${name} has not been granted.`,\n code: ErrorCode.PERMISSION_DENIED,\n });\n }\n\n static deniedAll(names: string[]) {\n return new PermissionError({\n message: `None of the permissions ${names.join(', ')} has been granted.`,\n code: ErrorCode.PERMISSION_DENIED,\n });\n }\n\n static evaluationFailed(name: string | string[]) {\n if (Array.isArray(name)) {\n return new PermissionError({\n message: `The evaluation of permissions ${name.join(', ')} failed`,\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n });\n }\n\n return new PermissionError({\n message: `The evaluation of permission ${name} failed`,\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode, hasInstanceof, isAuthupError } from '@authup/errors';\nimport { PERMISSION_ERROR_INSTANCE, type PermissionError } from './module';\n\nexport function isPermissionError(input: unknown): input is PermissionError {\n if (hasInstanceof(input, PERMISSION_ERROR_INSTANCE)) {\n return true;\n }\n\n if (!isAuthupError(input)) {\n return false;\n }\n\n return input.code === ErrorCode.PERMISSION_NOT_FOUND ||\n input.code === ErrorCode.PERMISSION_DENIED ||\n input.code === ErrorCode.PERMISSION_EVALUATION_FAILED;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Actor-relative realm reach of a permission grant.\n *\n * Total order (least -> most permissive): none < own < ownOrNull < any.\n * A missing/unknown column coerces to `own` (fail-closed); `none` is only ever an\n * explicit value (the grant reaches no realm at all).\n */\nexport enum RealmScope {\n /** No reach — the grant matches no resource realm. */\n NONE = 'none',\n /** Own realm only — resource realm must equal the actor's realm. */\n OWN = 'own',\n /** Own realm or null/global resources (realm_id === null). */\n OWN_OR_NULL = 'ownOrNull',\n /** Any realm, including null/global. */\n ANY = 'any',\n}\n\n/** Numeric restrictiveness order — internal to the fold/compare helpers. */\nexport const REALM_SCOPE_ORDER: Record<`${RealmScope}`, number> = {\n [RealmScope.NONE]: 0,\n [RealmScope.OWN]: 1,\n [RealmScope.OWN_OR_NULL]: 2,\n [RealmScope.ANY]: 3,\n};\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { REALM_SCOPE_ORDER, RealmScope } from './constants';\n\n/**\n * Coerce an arbitrary value to a RealmScope, defaulting to `own` for missing /\n * null / unknown input (fail-closed). `none` is honoured only when explicit.\n */\nexport function normalizeRealmScope(value?: `${RealmScope}` | null): `${RealmScope}` {\n return value === RealmScope.ANY ||\n value === RealmScope.OWN_OR_NULL ||\n value === RealmScope.NONE ?\n value :\n RealmScope.OWN;\n}\n\n/**\n * Numeric comparison of two realm scopes by restrictiveness.\n * Negative when `a` is more restrictive than `b`, positive when less.\n */\nexport function compareRealmScope(\n a?: `${RealmScope}` | null,\n b?: `${RealmScope}` | null,\n): number {\n return REALM_SCOPE_ORDER[normalizeRealmScope(a)] - REALM_SCOPE_ORDER[normalizeRealmScope(b)];\n}\n\n/** Fold scopes to the MOST permissive (ordered max). Empty folds to `own`. */\nexport function maxRealmScope(values: Array<`${RealmScope}` | null | undefined>): `${RealmScope}` {\n let max: `${RealmScope}` = RealmScope.NONE;\n let seen = false;\n for (const value of values) {\n seen = true;\n const scope = normalizeRealmScope(value);\n if (REALM_SCOPE_ORDER[scope] > REALM_SCOPE_ORDER[max]) {\n max = scope;\n }\n }\n // Empty input is fail-closed `own` (not `none`).\n return seen ? max : RealmScope.OWN;\n}\n\n/** Fold scopes to the MORE restrictive (ordered min) — used to CAP a grant. Empty folds to `own`. */\nexport function minRealmScope(values: Array<`${RealmScope}` | null | undefined>): `${RealmScope}` {\n let min: `${RealmScope}` = RealmScope.ANY;\n let seen = false;\n for (const value of values) {\n seen = true;\n const scope = normalizeRealmScope(value);\n if (REALM_SCOPE_ORDER[scope] < REALM_SCOPE_ORDER[min]) {\n min = scope;\n }\n }\n return seen ? min : RealmScope.OWN;\n}\n\n/**\n * Whether `scope` reaches a single resource realm `resourceRealmId` for an actor whose\n * realm is `identityRealmId`/`identityRealmName`.\n *\n * - `any` -> always.\n * - `none` -> never.\n * - realm-less actor (no realmId and no realmName) -> never `own`/`ownOrNull`.\n * - resource realm `null` (global) -> only `ownOrNull`.\n * - concrete resource realm -> must equal the actor's own realm (by id or name).\n */\nfunction matchesSingle(\n normalized: `${RealmScope}`,\n resourceRealmId: string | null,\n identityRealmId: string | null,\n identityRealmName: string | null,\n): boolean {\n if (resourceRealmId === null) {\n return normalized === RealmScope.OWN_OR_NULL;\n }\n return resourceRealmId === identityRealmId || resourceRealmId === identityRealmName;\n}\n\n/**\n * Whether `scope` reaches the resource. The resource realm may be presented as a single\n * id, `null` (global), or an array of realm ids — the array form (a resource that spans\n * multiple realms) requires the scope to reach EVERY listed realm (unanimous, fail-closed),\n * so any app/entity can express its realm via one or many keys under the canonical contract.\n */\nexport function realmScopeMatches(\n scope: `${RealmScope}` | null | undefined,\n resourceRealmId: string | string[] | null | undefined,\n identityRealmId: string | null | undefined,\n identityRealmName?: string | null,\n): boolean {\n const normalized = normalizeRealmScope(scope);\n if (normalized === RealmScope.ANY) {\n return true;\n }\n if (normalized === RealmScope.NONE) {\n return false;\n }\n\n const realmId = identityRealmId ?? null;\n const realmName = identityRealmName ?? null;\n if (realmId === null && realmName === null) {\n return false;\n }\n\n if (Array.isArray(resourceRealmId)) {\n // Fail closed: an empty realm set is unreachable for a scoped actor (`any`\n // already returned above). `[].every()` would otherwise vacuously pass.\n if (resourceRealmId.length === 0) {\n return false;\n }\n return resourceRealmId.every((id) => matchesSingle(normalized, id ?? null, realmId, realmName));\n }\n\n return matchesSingle(normalized, resourceRealmId ?? null, realmId, realmName);\n}\n","/*\n * Copyright (c) 2025-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n\nimport type { BasePermission } from '../types.ts';\n\nfunction formatKeySegment(value?: string | null): string {\n return value || '*';\n}\n\nexport function buildPermissionKey(\n input: BasePermission,\n) {\n return `${formatKeySegment(input.realm_id)}/${formatKeySegment(input.client_id)}/${input.name}`;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { DecisionStrategy } from '@authup/kit';\nimport type { BasePolicy } from '../../policy';\nimport { normalizeRealmScope } from '../realm-scope';\nimport type {\n PermissionGrant,\n PermissionPolicyBinding,\n PermissionPolicyBindingAggregated,\n} from '../types';\nimport { buildPermissionKey } from './key';\n\ntype CompositePolicy = BasePolicy & {\n decision_strategy?: `${DecisionStrategy}`,\n children: BasePolicy[],\n};\n\n/**\n * One disjunction term per raw binding: the grant's realm reach (fail-closed `own` default)\n * paired with its policy — the raw single policy (its `id` preserved for junction propagation),\n * a composite over multiple policies (Layer-1 permission policies, combined under the\n * permission's decision_strategy), or `undefined` when the grant is unrestricted.\n */\nfunction buildGrant(binding: PermissionPolicyBinding): PermissionGrant {\n let policy: BasePolicy | undefined;\n if (binding.policies && binding.policies.length === 1) {\n policy = binding.policies[0];\n } else if (binding.policies && binding.policies.length > 1) {\n const composite: CompositePolicy = {\n type: 'composite',\n decision_strategy: binding.permission.decision_strategy || DecisionStrategy.UNANIMOUS,\n children: binding.policies,\n };\n policy = composite;\n }\n\n return {\n realm_scope: normalizeRealmScope(binding.realm_scope),\n policy,\n };\n}\n\n/**\n * Group raw permission-policy bindings by permission key into the actor's disjunction of\n * `(realm_scope, policy)` grants per permission — with NO lossy collapse. Every consumer\n * (the binding evaluator, isSuperset, junction propagation, the memory provider) evaluates the\n * grant disjunction directly, so each grant's realm reach stays paired with the policy that\n * gates it.\n */\nexport function aggregatePermissionPolicyBindings(\n input: PermissionPolicyBinding[],\n): PermissionPolicyBindingAggregated[] {\n const grouped: Record<string, PermissionPolicyBinding[]> = input\n .reduce((previous, current) => {\n const key = buildPermissionKey(current.permission);\n if (!previous[key]) {\n previous[key] = [];\n }\n\n previous[key].push(current);\n\n return previous;\n }, {} as Record<string, PermissionPolicyBinding[]>);\n\n const output: PermissionPolicyBindingAggregated[] = [];\n for (const key of Object.keys(grouped)) {\n const group = grouped[key]!;\n output.push({\n permission: group[0]!.permission,\n grants: group.map(buildGrant),\n });\n }\n\n return output;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { BasePermission } from '../types';\n\nexport function isPermissionPolicyBindingEqual(\n a: { permission: BasePermission },\n b: { permission: BasePermission },\n): boolean {\n if (a.permission.name !== b.permission.name) {\n return false;\n }\n\n if ((a.permission.realm_id ?? null) !== (b.permission.realm_id ?? null)) {\n return false;\n }\n\n if ((a.permission.client_id ?? null) !== (b.permission.client_id ?? null)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isEqual } from 'smob';\nimport type { BasePolicy } from '../../policy';\nimport { compareRealmScope } from '../realm-scope';\nimport type { PermissionGrant } from '../types';\n\n/**\n * Policy fields that do NOT affect evaluation — persisted identity, audit and label columns plus\n * the loaded `parent` / `realm` relation objects. They are stripped before the structural compare\n * in isPolicyEquivalent so two DISTINCT rows with identical configuration still match. Verified\n * against every built-in evaluator, which read only `type`, `invert`, `decision_strategy`,\n * `children` and the type-specific config (query / names / types / start / end / interval /\n * day_of_* / attribute_name* / scope). `parent` is additionally a circular back-reference and\n * `realm` a nested object with its own id, so leaving either in would break the deep compare.\n *\n * SECURITY INVARIANT: every key here MUST stay non-evaluation-affecting. Adding an\n * evaluation-relevant field would silently widen equivalence into an over-permit. New *config*\n * fields need NOT be added — they are compared by default, which is the fail-closed direction.\n */\nconst NON_SEMANTIC_POLICY_KEYS = new Set<string>([\n 'id',\n 'built_in',\n 'name',\n 'display_name',\n 'description',\n 'parent_id',\n 'parent',\n 'realm_id',\n 'realm',\n 'created_at',\n 'updated_at',\n]);\n\n/**\n * Project a policy node onto its evaluation-relevant configuration: drop the non-semantic keys\n * and recurse through `children` (the only field that carries nested policy nodes). Config values\n * (e.g. an `attributes` `query`) are left untouched, so a semantic `id` / `name` key *inside* a\n * query is never mistaken for the policy's own identity column.\n */\nfunction normalizePolicyForEquality(policy: BasePolicy): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(policy)) {\n if (NON_SEMANTIC_POLICY_KEYS.has(key)) {\n continue;\n }\n\n const value = (policy as Record<string, unknown>)[key];\n if (\n key === 'children' &&\n Array.isArray(value)\n ) {\n result[key] = value.map((child) => normalizePolicyForEquality(child as BasePolicy));\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Whether two restriction policies are provably the SAME policy for domination purposes — by\n * persisted identity OR by identical configuration, never by evaluated effect. Fast path: equal\n * primary-key `id` means the same persisted row (the `typeof … === 'string'` guards keep an\n * id-less / missing-id policy out of it — never `undefined === undefined`). Otherwise fall back to\n * a structural value-compare of the configuration (`normalizePolicyForEquality` strips the\n * non-semantic identity / audit / relation columns, `isEqual` deep-compares the rest), so two\n * distinct rows with identical config — the same predicate — still dominate. Comparing by\n * *effect* is undecidable (a policy is a predicate over PolicyData), so we accept ONLY provable\n * identity or provable structural equality; a genuinely different configuration is treated as\n * distinct (fail-closed) — isSuperset must never assume one restriction covers a different one.\n */\nfunction isPolicyEquivalent(parent: BasePolicy, child: BasePolicy): boolean {\n const parentId = (parent as { id?: unknown }).id;\n const childId = (child as { id?: unknown }).id;\n\n if (\n typeof parentId === 'string' &&\n typeof childId === 'string' &&\n parentId === childId\n ) {\n return true;\n }\n\n return isEqual(normalizePolicyForEquality(parent), normalizePolicyForEquality(child));\n}\n\n/**\n * Whether the actor's `parent` policy provably covers the target's `child` policy on a shared\n * permission. Conservative / fail-closed:\n * - an unrestricted parent (no policy) covers any child;\n * - a restricted parent NEVER covers an unrestricted child — it cannot confer the wider,\n * policy-free reach it does not itself hold;\n * - two restricted grants cover one another only when their policies are provably equivalent.\n * A DIFFERENT policy is NOT assumed to be a subset (#3159: the predecessor treated any two\n * policy-bound grants as mutually dominating, a latent over-permit across disjoint policy\n * scopes — e.g. an actor restricted to `department=X` conferring a `department=Y` grant).\n */\nfunction policyDominates(parent?: BasePolicy, child?: BasePolicy): boolean {\n if (!parent) {\n return true;\n }\n\n if (!child) {\n return false;\n }\n\n return isPolicyEquivalent(parent, child);\n}\n\n/**\n * Whether the actor's `parent` grant covers the target's `child` grant: it reaches at least as\n * far (ordered none < own < ownOrNull < any) AND its policy provably covers the child's\n * (see `policyDominates`). Used per grant by `isSuperset` over the aggregated disjunction —\n * every child grant must be dominated by SOME parent grant.\n */\nexport function grantDominates(parent: PermissionGrant, child: PermissionGrant): boolean {\n if (compareRealmScope(parent.realm_scope, child.realm_scope) < 0) {\n return false;\n }\n\n return policyDominates(parent.policy, child.policy);\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { aggregatePermissionPolicyBindings, buildPermissionKey } from '../helpers';\nimport type { PermissionPolicyBinding, PermissionPolicyBindingAggregated } from '../types';\nimport type { IPermissionProvider, PermissionGetOptions } from './types';\n\nexport class PermissionMemoryProvider implements IPermissionProvider {\n protected items : Record<string, PermissionPolicyBindingAggregated> = {};\n\n constructor(items: PermissionPolicyBinding[] = []) {\n this.setMany(items);\n }\n\n async findOne(\n options: PermissionGetOptions,\n ): Promise<PermissionPolicyBindingAggregated | null> {\n const key = buildPermissionKey({\n name: options.name,\n client_id: options.clientId,\n realm_id: options.realmId,\n });\n\n const entry = this.items[key];\n if (entry) {\n return entry;\n }\n\n return null;\n }\n\n setMany(input: PermissionPolicyBinding[]) {\n this.items = aggregatePermissionPolicyBindings(input)\n .reduce((prev, current) => {\n const key = buildPermissionKey(current.permission);\n prev[key] = current;\n return prev;\n }, {} as Record<string, PermissionPolicyBindingAggregated>);\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AuthupError, ErrorCode, markInstanceof } from '@authup/errors';\nimport type { PolicyIssue } from '../issue';\n\nexport const POLICY_ERROR_INSTANCE = Symbol.for('@authup/access/PolicyError');\n\nexport class PolicyError extends AuthupError {\n constructor(message?: string, code?: string | null) {\n super({\n message,\n code: code ?? undefined,\n });\n markInstanceof(this, POLICY_ERROR_INSTANCE);\n }\n\n addIssue(data: PolicyIssue) {\n this.issues.push(data);\n }\n\n addIssues(data: PolicyIssue[]) {\n this.issues.push(...data);\n }\n\n static evaluatorNotFound(type: string) {\n return new PolicyError(\n `No evaluator is registered to handle the policy: ${type}`,\n ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n );\n }\n\n static evaluatorNotProcessable() {\n return new PolicyError(\n 'The evaluator can not process the policy.',\n ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n );\n }\n\n static evaluatorContextInvalid() {\n return new PolicyError(\n 'The evaluator context is not valid.',\n ErrorCode.POLICY_EVALUATOR_CONTEXT_INVALID,\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode, hasInstanceof, isAuthupError } from '@authup/errors';\nimport { POLICY_ERROR_INSTANCE, type PolicyError } from './module';\n\nexport function isPolicyError(input: unknown): input is PolicyError {\n if (hasInstanceof(input, POLICY_ERROR_INSTANCE)) {\n return true;\n }\n\n if (!isAuthupError(input)) {\n return false;\n }\n\n return input.code === ErrorCode.POLICY_EVALUATOR_NOT_FOUND ||\n input.code === ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE ||\n input.code === ErrorCode.POLICY_EVALUATOR_CONTEXT_INVALID;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode } from '@authup/errors';\nimport { defineIssueItem } from 'validup';\nimport type {\n IPolicyEvaluator,\n PolicyEvaluationContext,\n PolicyEvaluationResult,\n PolicyEvaluators,\n} from '../evaluation';\nimport type { PolicyIssue } from '../issue';\nimport type { IPolicyEngine } from './types.ts';\nimport { PolicyError, isPolicyError } from '../error';\nimport type { BasePolicy } from '../types.ts';\n\n// Cross-realm-safe extraction of an error message from an unknown thrown\n// value. `instanceof Error` is unreliable across module boundaries (different\n// realms, dual-bundled packages), so we duck-type on the `message` shape.\nfunction errorMessage(value: unknown): string {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'message' in value &&\n typeof (value as { message: unknown }).message === 'string'\n ) {\n return (value as { message: string }).message;\n }\n return String(value);\n}\n\n/**\n * The policy engine is a component that interprets defined policies and makes decisions\n * on whether to allow or deny a particular access.\n */\nexport class PolicyEngine implements IPolicyEngine {\n protected evaluators : Record<string, IPolicyEvaluator>;\n\n constructor(evaluators: PolicyEvaluators = {}) {\n this.evaluators = evaluators;\n }\n\n public registerEvaluator(\n type: string,\n evaluator: IPolicyEvaluator,\n ) : void {\n this.evaluators[type] = evaluator;\n }\n\n public registerEvaluators(evaluators: PolicyEvaluators) {\n const keys = Object.keys(evaluators);\n for (const key of keys) {\n this.registerEvaluator(key, evaluators[key]!);\n }\n }\n\n /**\n * @param policy\n * @param ctx\n */\n async evaluate(policy: BasePolicy, ctx: PolicyEvaluationContext) : Promise<PolicyEvaluationResult> {\n // Infrastructure errors (no type, no evaluator, evaluator threw) MUST\n // fail closed regardless of `policy.invert`. Inverting an error path\n // would silently grant access on misconfiguration — with `invert: true`\n // an unregistered policy type would return success: true.\n if (!policy.type) {\n return {\n success: false,\n issues: [\n defineIssueItem({\n path: [],\n message: 'The policy can not be handled by any evaluator.',\n code: ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n }),\n ],\n };\n }\n // When a policy is filtered out via include/exclude, treat it as a\n // neutral pass — do NOT apply `invert`. Inversion only makes sense\n // for an actual evaluation outcome; skipping a policy because it's\n // outside the current context's scope is not an outcome.\n if (\n ctx.exclude &&\n ctx.exclude.length > 0 &&\n ctx.exclude.includes(policy.type)\n ) {\n return { success: true };\n }\n\n if (\n ctx.include &&\n ctx.include.length > 0 &&\n !ctx.include.includes(policy.type)\n ) {\n return { success: true };\n }\n\n const issues : PolicyIssue[] = [];\n\n const evaluator = this.evaluators[policy.type];\n if (!evaluator) {\n issues.push(defineIssueItem({\n path: [policy.type],\n message: `The policy ${policy.type} can not be handled by any evaluator.`,\n code: ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n }));\n\n return {\n success: false,\n issues,\n };\n }\n\n try {\n return await evaluator.evaluate(policy, {\n ...ctx,\n evaluators: {\n ...this.evaluators,\n ...(ctx.evaluators || {}),\n },\n });\n } catch (e) {\n issues.push(defineIssueItem({\n path: [policy.type],\n message: `The ${policy.type} evaluator threw: ${errorMessage(e)}`,\n code: ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n }));\n\n return {\n success: false,\n issues,\n };\n }\n }\n\n async evaluateOrFail(policy: BasePolicy, ctx: PolicyEvaluationContext) : Promise<void> {\n const issues : PolicyIssue[] = [];\n\n try {\n const outcome = await this.evaluate(policy, ctx);\n if (outcome.success) {\n return;\n }\n\n if (outcome.issues) {\n issues.push(...outcome.issues);\n }\n } catch (e) {\n if (isPolicyError(e)) {\n throw e;\n }\n\n // Surface non-PolicyError throws (DB failures, validator crashes, etc.)\n // as issues so the root cause is visible instead of being swallowed\n // behind a generic policy failure.\n issues.push(defineIssueItem({\n path: policy.type ? [policy.type] : [],\n message: errorMessage(e),\n code: ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n }));\n }\n\n const error = new PolicyError(`The policy ${policy.type} evaluation failed.`);\n error.addIssues(issues);\n\n throw error;\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport interface IPolicyData {\n set(key: string, value: unknown) : void;\n has(key: string): boolean;\n get<T = unknown>(key: string) : T;\n\n isValidated(key: string): boolean;\n setValidated(key: string) : void;\n\n clone() : IPolicyData\n}\n\nexport class PolicyData implements IPolicyData {\n protected data: Record<string, any>;\n\n protected validated : Set<string>;\n\n constructor(\n data: Record<string, any> = {},\n validated: Set<string> = new Set(),\n ) {\n this.data = data;\n this.validated = validated;\n }\n\n set<T = unknown>(key: string, value: T) : void {\n this.data[key] = value;\n this.validated.delete(key);\n }\n\n get<T = unknown>(key: string) : T {\n if (key in this.data) {\n return this.data[key];\n }\n\n throw new Error(`Policy data item ${key} does not exist.`);\n }\n\n has(key: string): boolean {\n return key in this.data;\n }\n\n setValidated(key: string) : void {\n this.validated.add(key);\n }\n\n isValidated(key: string) : boolean {\n return this.validated.has(key);\n }\n\n clone() {\n return new PolicyData({ ...this.data }, new Set(this.validated));\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyEvaluationContext, PolicyEvaluationContextInput } from './types.ts';\nimport { PolicyData } from '../../data.ts';\n\nexport function definePolicyEvaluationContext(\n input: PolicyEvaluationContextInput = {},\n) : PolicyEvaluationContext {\n return {\n evaluators: input.evaluators || {},\n path: input.path || [],\n data: input.data || new PolicyData(),\n include: input.include || [],\n exclude: input.exclude || [],\n };\n}\n","/*\n * Copyright (c) 2026-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum PolicyIssueSeverity {\n WARNING = 'warning',\n ERROR = 'error',\n}\n\nexport enum PolicyIssueCode {\n // Data/Input\n DATA_MISSING = 'DATA_MISSING',\n DATA_INVALID = 'DATA_INVALID',\n\n // Policy Spec / Config\n INVALID = 'INVALID',\n TYPE_UNKNOWN = 'TYPE_UNKNOWN',\n FIELD_MISSING = 'FIELD_MISSING',\n FIELD_INVALID = 'FIELD_INVALID',\n\n // Composite / Tree evaluation\n CHILD_INVALID = 'CHILD_INVALID',\n CHILD_EVALUATION_FAILED = 'CHILD_EVALUATION_FAILED',\n\n // Engine / Evaluator registry\n EVALUATION_DENIED = 'EVALUATION_DENIED',\n EVALUATOR_NOT_FOUND = 'EVALUATOR_NOT_FOUND',\n EVALUATOR_ERROR = 'EVALUATOR_ERROR',\n\n // Execution control\n SKIPPED_EXCLUDED = 'SKIPPED_EXCLUDED',\n SKIPPED_NOT_INCLUDED = 'SKIPPED_NOT_INCLUDED',\n\n // Internal / unexpected\n INTERNAL_ERROR = 'INTERNAL_ERROR',\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { defineIssueGroup, defineIssueItem } from 'validup';\nimport type { PolicyIssueGroup, PolicyIssueItem } from './types.ts';\n\nexport function definePolicyIssueItem(input: Omit<PolicyIssueItem, 'type'>) : PolicyIssueItem {\n return defineIssueItem(input);\n}\n\nexport function definePolicyIssueGroup(input: Omit<PolicyIssueGroup, 'type'>) : PolicyIssueGroup {\n return defineIssueGroup(input);\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\ntype InvertFn = (input: boolean) => boolean;\n\nexport function maybeInvertPolicyOutcome(\n outcome: boolean,\n invert?: boolean | InvertFn,\n) {\n if (typeof invert === 'undefined') {\n return outcome;\n }\n\n if (typeof invert === 'function') {\n return invert(outcome);\n }\n\n if (!invert) {\n return outcome;\n }\n\n return !outcome;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { AttributeNamesPolicy } from './types';\n\nexport class AttributeNamesPolicyValidator extends Container<AttributeNamesPolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'names',\n createValidator(\n z.array(\n z.string()\n .min(3)\n .max(128),\n ),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { AttributesPolicy } from './types';\n\nexport function defineAttributesPolicy<\n T extends Record<string, any> = Record<string, any>,\n>(\n data: AttributesPolicy<T>,\n) : AttributesPolicy<T> {\n return data;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum BuiltInPolicyType {\n /**\n * Bundles different policies.\n */\n COMPOSITE = 'composite',\n /**\n * Date Based Access Control (DBAC)\n */\n DATE = 'date',\n /**\n * Time Based Access Control (TBAC)\n */\n TIME = 'time',\n /**\n * Attribute Name Based Access Control (ANBAC)\n */\n ATTRIBUTE_NAMES = 'attributeNames',\n /**\n * Attribute Based Access Control (ABAC)\n */\n ATTRIBUTES = 'attributes',\n /**\n * Realm of Identity is for attribute realm.\n */\n REALM_MATCH = 'realmMatch',\n\n /**\n * Restriction based on identity (type, id, ...)\n */\n IDENTITY = 'identity',\n\n /**\n * Restriction based on a binding between identity <-> permission\n */\n PERMISSION_BINDING = 'permissionBinding',\n\n // Location (LBAC)\n // Device (DBAC)\n}\n\nexport const SystemPolicyName = {\n DEFAULT: 'system.default',\n IDENTITY: 'system.identity',\n PERMISSION_BINDING: 'system.permission-binding',\n REALM_MATCH: 'system.realm-match',\n CLIENT_NAMES_SELF_MANAGE: 'system.client-names-self-manage',\n ROBOT_NAMES_SELF_MANAGE: 'system.robot-names-self-manage',\n USER_NAMES_SELF_MANAGE: 'system.user-names-self-manage',\n} as const;\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { AttributesPolicy } from './types';\n\nexport class AttributesPolicyValidator<\n T extends Record<string, any> = Record<string, any>,\n> extends Container<AttributesPolicy<T>> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'query',\n createValidator(\n z.looseObject({}),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { guard } from '@ucast/mongo2js';\nimport { isObject } from '@authup/kit';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { BuiltInPolicyType } from '../constants.ts';\nimport { AttributesPolicyValidator } from './validator';\n\nexport class AttributesPolicyEvaluator<\n T extends Record<string, any> = Record<string, any>,\n> implements IPolicyEvaluator {\n protected validator : AttributesPolicyValidator<T>;\n\n constructor() {\n this.validator = new AttributesPolicyValidator<T>();\n }\n\n async accessData(ctx: PolicyEvaluationContext) : Promise<T | null> {\n if (!ctx.data.has(BuiltInPolicyType.ATTRIBUTES)) {\n return null;\n }\n\n if (ctx.data.isValidated(BuiltInPolicyType.ATTRIBUTES)) {\n return ctx.data.get<T>(BuiltInPolicyType.ATTRIBUTES);\n }\n\n // todo: run validator on attributes (isObject ...)\n const data = ctx.data.get<T>(BuiltInPolicyType.ATTRIBUTES);\n\n ctx.data.set(BuiltInPolicyType.ATTRIBUTES, data);\n ctx.data.setValidated(BuiltInPolicyType.ATTRIBUTES);\n\n return data;\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const data = await this.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n this.fixQuery(policy.query);\n\n const testIt = guard<T>(policy.query);\n\n return { success: maybeInvertPolicyOutcome(testIt(data as T), policy.invert) };\n }\n\n protected fixQuery(\n query: unknown | unknown[],\n ) {\n if (Array.isArray(query)) {\n for (const element of query) {\n this.fixQuery(element);\n }\n\n return;\n }\n\n if (isObject(query)) {\n const keys = Object.keys(query);\n for (const key of keys) {\n const value = query[key];\n\n if (isObject(value) || Array.isArray(value)) {\n this.fixQuery(value);\n continue;\n }\n\n if (\n key === '$regex' &&\n typeof value === 'string'\n ) {\n const fragments = value.match(/\\/(.*?)\\/([a-z]*)?$/i);\n if (fragments && fragments[1] !== undefined) {\n query[key] = new RegExp(fragments[1], fragments[2] || '');\n }\n }\n }\n }\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { flattenObject } from '@authup/kit';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport type { PolicyIssue } from '../../issue';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { AttributeNamesPolicyValidator } from './validator';\nimport { AttributesPolicyEvaluator } from '../attributes';\n\nexport class AttributeNamesPolicyEvaluator implements IPolicyEvaluator {\n protected validator : AttributeNamesPolicyValidator;\n\n protected attributesEvaluator : AttributesPolicyEvaluator;\n\n constructor() {\n this.validator = new AttributeNamesPolicyValidator();\n this.attributesEvaluator = new AttributesPolicyEvaluator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const data = await this.attributesEvaluator.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n // Nested paths are a deliberate feature: an attribute object like\n // `{user: {name: 'x'}}` flattens to `{'user.name': 'x'}` and is matched\n // against `names` entries with dotted notation. Allowlists/denylists\n // that need to govern nested fields must use the dotted-path form\n // (e.g. `'user.realm_id'`); a top-level entry like `'realm_id'` will\n // NOT catch a nested `user.realm_id` write — that's by design, the\n // policy is precise about which path it covers.\n const attributes = flattenObject(data);\n const keys = Object.keys(attributes);\n\n // `invert` is consumed per-key, NOT at the result level:\n // - allowlist (default): a key NOT in `names` is denied\n // - denylist (invert: true): a key IN `names` is denied\n // Result-level inversion would break the empty-input case (a request\n // with no validated attributes would flip success → fail), and would\n // produce nonsensical \"deny iff all keys are in the list\" semantics\n // for partial inputs.\n const issues : PolicyIssue[] = [];\n for (const key of keys) {\n const inList = policy.names.includes(key);\n const denied = policy.invert ? inList : !inList;\n if (denied) {\n issues.push(definePolicyIssueItem({\n code: PolicyIssueCode.EVALUATION_DENIED,\n message: policy.invert ?\n `The attribute ${key} is denied` :\n `The attribute ${key} is not included`,\n path: [...ctx.path, key],\n }));\n }\n }\n\n return {\n success: issues.length === 0,\n issues,\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport { DecisionStrategy } from '@authup/kit';\nimport type { CompositePolicy } from './types';\n\nexport class CompositePolicyValidator extends Container<CompositePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'decision_strategy',\n createValidator(\n z.enum(DecisionStrategy)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'children',\n createValidator(\n z.array(z.looseObject({ type: z.string().min(3) })),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { defineIssueGroup } from 'validup';\nimport { DecisionStrategy } from '@authup/kit';\nimport { PolicyEngine } from '../../engine';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport type { PolicyIssue } from '../../issue';\nimport { CompositePolicyValidator } from './validator';\n\nexport class CompositePolicyEvaluator implements IPolicyEvaluator {\n protected validator : CompositePolicyValidator;\n\n constructor() {\n this.validator = new CompositePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n let count = 0;\n\n const decision_strategy = policy.decision_strategy ??\n DecisionStrategy.UNANIMOUS;\n\n const engine = new PolicyEngine(ctx.evaluators);\n const issues : PolicyIssue[] = [];\n\n for (const childPolicy of policy.children) {\n const path = [\n ...(ctx.path || []),\n ...(childPolicy.type ? [childPolicy.type] : []),\n ];\n\n const outcome = await engine.evaluate(childPolicy, {\n ...ctx,\n path,\n });\n\n if (outcome.success) {\n if (decision_strategy === DecisionStrategy.AFFIRMATIVE) {\n return {\n success: maybeInvertPolicyOutcome(true, policy.invert),\n issues: [],\n };\n }\n\n count++;\n } else {\n if (outcome.issues) {\n issues.push(defineIssueGroup({\n message: `The evaluation of child policy ${childPolicy.type} failed`,\n issues: outcome.issues || [],\n path,\n }));\n }\n\n if (decision_strategy === DecisionStrategy.UNANIMOUS) {\n const success = maybeInvertPolicyOutcome(false, policy.invert);\n return {\n success,\n // When `invert` flips a child-failure into success,\n // suppress the issue list — surfacing failure issues\n // alongside `success: true` is misleading.\n issues: success ? [] : [\n defineIssueGroup({\n message: `The evaluation of composite policy failed (${DecisionStrategy.UNANIMOUS})`,\n issues,\n path: ctx.path,\n }),\n ],\n };\n }\n\n count--;\n }\n }\n\n if (count > 0) {\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n\n const success = maybeInvertPolicyOutcome(false, policy.invert);\n return {\n success,\n issues: success ? [] : [\n defineIssueGroup({\n message: `The evaluation of composite policy failed (${DecisionStrategy.CONSENSUS})`,\n issues: issues || [],\n path: ctx.path,\n }),\n ],\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyWithType } from '../../types';\nimport { BuiltInPolicyType } from '../constants';\nimport type { CompositePolicy } from './types';\n\nexport function isCompositePolicy(\n input: PolicyWithType,\n) : input is PolicyWithType<CompositePolicy> {\n return input.type === BuiltInPolicyType.COMPOSITE;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { DatePolicy } from './types';\n\nexport class DatePolicyValidator extends Container<DatePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount('start', createValidator(\n z.date()\n .or(z.iso.date())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('end', createValidator(\n z.date()\n .or(z.iso.date())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount('invert', createValidator(\n z.boolean()\n .or(z.undefined())\n .or(z.null())\n .optional(),\n ));\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants.ts';\nimport { DatePolicyValidator } from './validator';\n\nfunction normalizeDate(input: Date) {\n return new Date(input.getFullYear(), input.getMonth(), input.getDate());\n}\n\nfunction toDate(input: Date | string | number) : Date {\n if (typeof input === 'string') {\n return new Date(input);\n }\n\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n return input;\n}\n\nexport class DatePolicyEvaluator implements IPolicyEvaluator {\n protected validator : DatePolicyValidator;\n\n constructor() {\n this.validator = new DatePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n let now : Date;\n\n if (ctx.data.has(BuiltInPolicyType.DATE)) {\n if (ctx.data.isValidated(BuiltInPolicyType.DATE)) {\n now = ctx.data.get<Date>(BuiltInPolicyType.DATE);\n } else {\n // todo: run validator on attributes (isObject ...)\n now = normalizeDate(toDate(ctx.data.get(BuiltInPolicyType.DATE)));\n\n ctx.data.set(BuiltInPolicyType.DATE, now);\n ctx.data.setValidated(BuiltInPolicyType.DATE);\n }\n } else {\n now = normalizeDate(new Date());\n }\n\n if (policy.start) {\n const start = normalizeDate(toDate(policy.start));\n if (now < start) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.end) {\n const end = normalizeDate(toDate(policy.end));\n if (now > end) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\n\nimport type { IdentityPolicyData } from '../types.ts';\n\nexport class PolicyIdentityDataValidator extends Container<IdentityPolicyData> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'type',\n createValidator(\n z.string().min(3).max(128),\n ),\n );\n\n this.mount(\n 'id',\n createValidator(\n z.uuid(),\n ),\n );\n\n this.mount(\n 'clientId',\n createValidator(\n z.uuid()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'realmId',\n createValidator(\n z.uuid()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'realmName',\n createValidator(\n z.string().min(3).max(128)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { IdentityPolicy } from './types';\n\nexport class IdentityPolicyValidator extends Container<IdentityPolicy> {\n override initialize() {\n this.mount(\n 'types',\n createValidator(\n z.array(z.string())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PolicyIdentityDataValidator } from './data';\nimport type { IdentityPolicyData } from './types';\nimport { IdentityPolicyValidator } from './validator';\n\nexport class IdentityPolicyEvaluator implements IPolicyEvaluator {\n protected validator : IdentityPolicyValidator;\n\n protected dataValidator : PolicyIdentityDataValidator;\n\n constructor() {\n this.validator = new IdentityPolicyValidator();\n this.dataValidator = new PolicyIdentityDataValidator();\n }\n\n async accessData(ctx: PolicyEvaluationContext) : Promise<IdentityPolicyData | null> {\n if (!ctx.data.has('identity')) {\n return null;\n }\n\n if (ctx.data.isValidated('identity')) {\n return ctx.data.get<IdentityPolicyData>('identity');\n }\n\n const data = await this.dataValidator.run(ctx.data.get('identity'));\n\n ctx.data.set('identity', data);\n ctx.data.setValidated('identity');\n\n return data;\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const data = await this.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property identity is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n if (!policy.types || policy.types.length === 0) {\n // Empty types is a configuration shorthand for \"no type\n // restriction\" — every identity passes. Do NOT apply `invert`;\n // inverting an empty config would silently deny all identities,\n // which is almost never the user's intent.\n return { success: true };\n }\n\n const typeAllowed = policy.types.includes(data.type);\n if (typeAllowed) {\n return { success: maybeInvertPolicyOutcome(typeAllowed, policy.invert) };\n }\n\n return {\n success: maybeInvertPolicyOutcome(typeAllowed, policy.invert),\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.EVALUATION_DENIED,\n message: `The type ${data.type} is not covered by the policy configuration`,\n path: ctx.path,\n }),\n ],\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { Container } from 'validup';\nimport type { PermissionBindingPolicy } from './types';\n\nexport class PermissionBindingPolicyValidator extends Container<PermissionBindingPolicy> {\n override initialize() {\n\n }\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PermissionBindingPolicyValidator } from './validator';\n\nexport class PermissionBindingPolicyEvaluator implements IPolicyEvaluator {\n protected validator: PermissionBindingPolicyValidator;\n\n constructor() {\n this.validator = new PermissionBindingPolicyValidator();\n }\n\n async evaluate(value: Record<string, any>): Promise<PolicyEvaluationResult> {\n const policy = await this.validator.run(value);\n\n // todo: this must be changed when the permission-checker not only checks owned permissions.\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport { DecisionStrategy } from '@authup/kit';\nimport { RealmScope } from '../../../permission/realm-scope';\nimport type { RealmMatchPolicy } from './types';\n\nexport class RealmMatchPolicyValidator extends Container<RealmMatchPolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'decision_strategy',\n createValidator(\n z.enum(DecisionStrategy)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'attribute_name',\n createValidator(\n z.string()\n .min(3)\n .or(z.array(z.string().min(3)))\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n this.mount(\n 'attribute_name_strict',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n this.mount(\n 'attribute_null_match_all',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'scope',\n createValidator(\n z.enum(RealmScope)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { DecisionStrategy, hasOwnProperty } from '@authup/kit';\nimport { realmScopeMatches } from '../../../permission/realm-scope';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { AttributesPolicyEvaluator } from '../attributes';\nimport { BuiltInPolicyType } from '../constants';\nimport { IdentityPolicyEvaluator } from '../identity';\nimport { RealmMatchPolicyValidator } from './validator';\n\nexport class RealmMatchPolicyEvaluator implements IPolicyEvaluator {\n protected validator : RealmMatchPolicyValidator;\n\n protected identityEvaluator: IdentityPolicyEvaluator;\n\n protected attributesEvaluator : AttributesPolicyEvaluator;\n\n constructor() {\n this.validator = new RealmMatchPolicyValidator();\n this.identityEvaluator = new IdentityPolicyEvaluator();\n this.attributesEvaluator = new AttributesPolicyEvaluator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const identity = await this.identityEvaluator.accessData(ctx);\n if (!identity) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property identity is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n // SCOPE MODE: coarse, actor-relative realm reach (the realm_scope mechanism lives\n // here). The resource realm is supplied under the REALM_MATCH data key. Key-PRESENCE\n // is the discriminator: an ABSENT realm neutral-passes (gate check / realm-less\n // resource), while a present `null` (global resource) is matched (and `own` correctly\n // denies it). Runs BEFORE the attributes-required guard below, since junction / gate\n // inputs need not carry ATTRIBUTES.\n if (policy.scope) {\n if (!ctx.data || !ctx.data.has(BuiltInPolicyType.REALM_MATCH)) {\n // Non-evaluation (no resource realm) — neutral pass, no `invert`,\n // mirroring the attribute-mode non-evaluation pass below.\n return { success: true };\n }\n\n const resourceRealm = ctx.data.get<string | string[] | null>(BuiltInPolicyType.REALM_MATCH);\n return {\n success: maybeInvertPolicyOutcome(\n realmScopeMatches(\n policy.scope,\n resourceRealm ?? null,\n identity.realmId,\n identity.realmName,\n ),\n policy.invert,\n ),\n };\n }\n\n const attributes = await this.attributesEvaluator.accessData(ctx);\n if (!attributes) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n let keys : string[];\n if (policy.attribute_name) {\n if (Array.isArray(policy.attribute_name)) {\n keys = policy.attribute_name;\n } else {\n keys = [policy.attribute_name];\n }\n } else {\n keys = [\n 'realm_id',\n 'realm_name',\n 'realmId',\n 'realmName',\n ];\n\n policy.decision_strategy = DecisionStrategy.CONSENSUS;\n }\n\n const attribute_name_strict = policy.attribute_name_strict ?? true;\n if (!attribute_name_strict) {\n const resourceKeys = Object.keys(attributes);\n const keysToAdd : string[] = [];\n for (const resourceKey of resourceKeys) {\n let contains : boolean = false;\n\n for (const key of keys) {\n if (\n resourceKey !== key &&\n resourceKey.includes(key)\n ) {\n contains = true;\n break;\n }\n }\n\n if (contains) {\n keysToAdd.push(resourceKey);\n }\n }\n\n if (keysToAdd.length > 0) {\n keys.push(...keysToAdd);\n }\n }\n\n let count = 0;\n let evaluated = false;\n\n for (const key of keys) {\n if (!hasOwnProperty(attributes, key)) {\n continue;\n }\n\n evaluated = true;\n\n let outcome : boolean = false;\n\n const attributeValue = attributes[key];\n\n if (\n attributeValue === null &&\n policy.attribute_null_match_all\n ) {\n outcome = true;\n } else if (\n attributeValue === identity.realmId ||\n attributeValue === identity.realmName\n ) {\n outcome = true;\n }\n\n if (outcome) {\n if (policy.decision_strategy === DecisionStrategy.AFFIRMATIVE) {\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n\n count++;\n } else {\n if (policy.decision_strategy === DecisionStrategy.UNANIMOUS) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n\n count--;\n }\n }\n\n if (!evaluated) {\n // No realm key found in attributes — the policy's match logic\n // didn't run. This is a \"non-evaluation\", not an outcome; treat\n // as a neutral pass without applying `invert`. Inverting here\n // would conflate \"policy doesn't apply\" with \"policy denies\".\n return { success: true };\n }\n\n return { success: maybeInvertPolicyOutcome(count > 0, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum TimePolicyInterval {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { TimePolicyInterval } from './constants';\n\nexport function isIntervalForDayOfWeek(\n interval: string,\n) {\n return interval === TimePolicyInterval.WEEKLY ||\n interval === TimePolicyInterval.MONTHLY ||\n interval === TimePolicyInterval.YEARLY;\n}\n\nexport function isIntervalForDayOfMonth(\n interval: string,\n) {\n return interval === TimePolicyInterval.MONTHLY ||\n interval === TimePolicyInterval.YEARLY;\n}\n\nexport function isIntervalForDayOfYear(\n interval: string,\n) {\n return interval === TimePolicyInterval.YEARLY;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { TimePolicy } from './types';\nimport { TimePolicyInterval } from './constants';\n\nexport class TimePolicyValidator extends Container<TimePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount('day_of_week', createValidator(\n z.number()\n .min(0).max(6)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('day_of_month', createValidator(\n z.number()\n .min(1)\n .max(31)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('day_of_year', createValidator(\n z.number()\n .min(1)\n .max(365)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount('start', createValidator(\n z.date()\n .or(z.iso.datetime())\n .or(z.iso.time())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('end', createValidator(\n z.date()\n .or(z.iso.datetime())\n .or(z.iso.time())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount(\n 'interval',\n createValidator(\n z.enum(TimePolicyInterval)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.undefined())\n .or(z.null())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants';\nimport { isIntervalForDayOfMonth, isIntervalForDayOfWeek, isIntervalForDayOfYear } from './helpers';\nimport { TimePolicyValidator } from './validator';\n\nconst timeRegex = /^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$/;\n\nfunction normalizeDate(input: Date, dateRef?: Date) {\n const date = dateRef ? new Date(dateRef) : new Date();\n date.setHours(input.getHours(), input.getMinutes());\n\n return date;\n}\n\nfunction toDate(\n input: Date | string | number,\n dateRef?: Date,\n) : Date {\n if (typeof input === 'string') {\n if (timeRegex.test(input)) {\n const parts = input.split(':');\n\n const startHours = Number(parts[0]);\n const startMinutes = Number(parts[1]);\n const startSeconds = parts[2] !== undefined ? Number(parts[2]) : 0;\n\n if (\n Number.isFinite(startHours) &&\n Number.isFinite(startMinutes) &&\n Number.isFinite(startSeconds)\n ) {\n const date = dateRef ? new Date(dateRef) : new Date();\n date.setHours(startHours, startMinutes, startSeconds, 0);\n\n return date;\n }\n }\n\n return new Date(input);\n }\n\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n return input;\n}\n\nexport class TimePolicyEvaluator implements IPolicyEvaluator {\n protected validator : TimePolicyValidator;\n\n constructor() {\n this.validator = new TimePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n let now : Date;\n\n if (ctx.data.has(BuiltInPolicyType.TIME)) {\n if (ctx.data.isValidated(BuiltInPolicyType.TIME)) {\n now = ctx.data.get<Date>(BuiltInPolicyType.TIME);\n } else {\n // todo: run validator on attributes (isObject ...)\n now = toDate(ctx.data.get(BuiltInPolicyType.TIME));\n\n ctx.data.set(BuiltInPolicyType.TIME, now);\n ctx.data.setValidated(BuiltInPolicyType.TIME);\n }\n } else {\n now = new Date();\n }\n\n if (policy.start) {\n const start = normalizeDate(toDate(policy.start, now), now);\n if (now < start) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.end) {\n const end = normalizeDate(toDate(policy.end, now), now);\n if (now > end) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.interval) {\n if (\n isIntervalForDayOfWeek(policy.interval) &&\n policy.day_of_week\n ) {\n if (now.getDay() !== policy.day_of_week) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (\n isIntervalForDayOfMonth(policy.interval) &&\n policy.day_of_month\n ) {\n if (now.getDate() !== policy.day_of_month) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (\n isIntervalForDayOfYear(policy.interval) &&\n policy.day_of_year\n ) {\n const start = new Date(now.getFullYear(), 0, 0);\n const diff = (now.getTime() - start.getTime()) +\n ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);\n\n const oneDay = 1000 * 60 * 60 * 24;\n const dayOfYear = Math.floor(diff / oneDay);\n\n if (dayOfYear !== policy.day_of_year) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n }\n\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyWithType } from '../types';\nimport type { BuiltInPolicyTypeMap } from './types';\n\nexport function definePolicyWithType<\n K extends keyof BuiltInPolicyTypeMap,\n D extends BuiltInPolicyTypeMap<any>[K],\n>(\n type: K,\n data: D,\n) : PolicyWithType<D, K> {\n return {\n ...data,\n type,\n };\n}\n","/*\n * Copyright (c) 2026-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport {\n AttributeNamesPolicyEvaluator,\n AttributesPolicyEvaluator,\n BuiltInPolicyType,\n CompositePolicyEvaluator,\n DatePolicyEvaluator,\n IdentityPolicyEvaluator,\n PermissionBindingPolicyEvaluator,\n RealmMatchPolicyEvaluator,\n TimePolicyEvaluator,\n} from './built-in';\n\nexport const PolicyDefaultEvaluators = {\n [BuiltInPolicyType.COMPOSITE]: new CompositePolicyEvaluator(),\n [BuiltInPolicyType.ATTRIBUTES]: new AttributesPolicyEvaluator(),\n [BuiltInPolicyType.ATTRIBUTE_NAMES]: new AttributeNamesPolicyEvaluator(),\n [BuiltInPolicyType.DATE]: new DatePolicyEvaluator(),\n [BuiltInPolicyType.IDENTITY]: new IdentityPolicyEvaluator(),\n [BuiltInPolicyType.PERMISSION_BINDING]: new PermissionBindingPolicyEvaluator(),\n [BuiltInPolicyType.REALM_MATCH]: new RealmMatchPolicyEvaluator(),\n [BuiltInPolicyType.TIME]: new TimePolicyEvaluator(),\n} as const;\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { BuiltInPolicyType } from './built-in/constants';\nimport type { IdentityPolicyData } from './built-in/identity/types';\nimport { PolicyData } from './data';\n\n/**\n * Typed seed for a permission evaluation's {@link PolicyData} bag.\n *\n * The well-known context keys are value-typed, so construction is discoverable and a\n * wrong-typed value is a compile error. The trailing index signature keeps the bag **open** —\n * a third-party evaluator may supply its own key without any change to this published type\n * (the `access` evaluator set is deliberately extensible).\n */\nexport interface PolicyInput {\n [BuiltInPolicyType.IDENTITY]?: IdentityPolicyData;\n [BuiltInPolicyType.ATTRIBUTES]?: Record<string, any>;\n [BuiltInPolicyType.REALM_MATCH]?: string | string[] | null;\n [key: string]: any;\n}\n\n/**\n * Build a {@link PolicyData} bag from a typed {@link PolicyInput} seed. Well-known keys\n * (identity / attributes / realmMatch) are type-checked; unknown keys are accepted as-is.\n *\n * Prefer this over `new PolicyData({ ... })` at construction sites so the key vocabulary and\n * per-key value types live in one place.\n */\nexport function definePolicyData(input: PolicyInput = {}): PolicyData {\n return new PolicyData(input);\n}\n","/*\n * Copyright (c) 2021-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode } from '@authup/errors';\nimport type { Issue } from 'validup';\nimport { defineIssueItem } from 'validup';\nimport { DecisionStrategy } from '@authup/kit';\nimport type { BasePolicy, CompositePolicy, IPolicyEngine } from '../../policy';\nimport {\n BuiltInPolicyType,\n PolicyData,\n PolicyDefaultEvaluators,\n PolicyEngine,\n definePolicyEvaluationContext,\n definePolicyIssueGroup,\n} from '../../policy';\nimport { PermissionError } from '../error';\nimport type { IPermissionProvider } from '../provider';\n\nimport type { PermissionPolicyBindingAggregated } from '../types.ts';\nimport type { IPermissionEvaluator, PermissionEvaluationContext, PermissionEvaluatorOptions } from './types.ts';\n\nexport class PermissionEvaluator implements IPermissionEvaluator {\n protected provider : IPermissionProvider;\n\n protected policyEngine : IPolicyEngine;\n\n protected clientId?: string | null;\n\n protected realmId?: string | null;\n\n // ----------------------------------------------\n\n constructor(options: PermissionEvaluatorOptions) {\n this.provider = options.provider;\n\n this.clientId = options.clientId || null;\n this.realmId = options.realmId || null;\n\n if (options.policyEngine) {\n this.policyEngine = options.policyEngine;\n } else {\n this.policyEngine = new PolicyEngine(PolicyDefaultEvaluators);\n }\n }\n\n // ----------------------------------------------\n\n protected async findOne(\n input: string,\n overrides: {\n realmId?: string | null,\n clientId?: string | null\n } = {},\n ) : Promise<PermissionPolicyBindingAggregated | null> {\n return this.provider.findOne({\n name: input,\n clientId: overrides.clientId ?? this.clientId,\n realmId: overrides.realmId ?? this.realmId,\n });\n }\n\n // ----------------------------------------------\n\n async evaluate(ctx: PermissionEvaluationContext) : Promise<void> {\n if (!Array.isArray(ctx.name)) {\n await this.evaluate({\n ...ctx,\n name: [ctx.name],\n });\n return;\n }\n\n const { options = {} } = ctx;\n\n const decisionStrategy = options.decisionStrategy ??\n DecisionStrategy.UNANIMOUS;\n\n const issues : Issue[] = [];\n\n let count = 0;\n\n const dataBase = ctx.data || new PolicyData();\n\n for (const name of ctx.name) {\n const binding = await this.findOne(name, {\n realmId: ctx.realmId,\n clientId: ctx.clientId,\n });\n if (!binding) {\n issues.push(defineIssueItem({\n code: ErrorCode.PERMISSION_NOT_FOUND,\n message: `The ${name} permission could not be resolved`,\n path: [name],\n }));\n\n if (decisionStrategy === DecisionStrategy.UNANIMOUS) {\n const error = PermissionError.evaluationFailed(ctx.name);\n error.addIssues(issues);\n throw error;\n }\n\n continue;\n }\n\n // The actor's grants for this permission form a disjunction: a single policy-free\n // grant is unrestricted, otherwise the permission passes iff ANY grant's policy\n // passes (AFFIRMATIVE). Each grant's policy already carries its own decision_strategy\n // (a composite for multi-policy Layer-1 bindings, the raw policy for single).\n const grantPolicies = binding.grants\n .map((grant) => grant.policy)\n .filter((grantPolicy): grantPolicy is BasePolicy => !!grantPolicy);\n\n if (grantPolicies.length < binding.grants.length) {\n // some grant is policy-free => unrestricted\n if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return;\n }\n\n count++;\n\n continue;\n }\n\n const data = dataBase.clone();\n data.set(BuiltInPolicyType.PERMISSION_BINDING, binding);\n\n const compositePolicy : CompositePolicy = {\n type: BuiltInPolicyType.COMPOSITE,\n decision_strategy: DecisionStrategy.AFFIRMATIVE,\n children: grantPolicies,\n };\n\n const evaluationResult = await this.policyEngine.evaluate(\n compositePolicy,\n definePolicyEvaluationContext({\n include: options.policiesIncluded,\n exclude: options.policiesExcluded,\n data,\n }),\n );\n\n if (evaluationResult.success) {\n if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return;\n }\n\n count++;\n } else {\n issues.push(definePolicyIssueGroup({\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n issues: evaluationResult.issues || [],\n message: `The ${binding.permission.name} permissions policy evaluation failed`,\n path: [binding.permission.name],\n }));\n\n if (decisionStrategy === DecisionStrategy.UNANIMOUS) {\n const error = PermissionError.evaluationFailed(binding.permission.name);\n error.addIssues(issues);\n throw error;\n }\n\n count--;\n }\n }\n\n if (count > 0) {\n return;\n }\n\n if (issues.length === 0) {\n throw PermissionError.deniedAll(ctx.name);\n } else {\n const error = PermissionError.evaluationFailed(ctx.name);\n error.addIssues(issues);\n throw error;\n }\n }\n\n async evaluateOneOf(ctx: PermissionEvaluationContext) : Promise<void> {\n return this.evaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n },\n });\n }\n\n // ----------------------------------------------\n\n async preEvaluate(ctx: PermissionEvaluationContext) : Promise<void> {\n return this.evaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n policiesExcluded: [\n BuiltInPolicyType.ATTRIBUTES,\n BuiltInPolicyType.ATTRIBUTE_NAMES,\n BuiltInPolicyType.REALM_MATCH,\n ],\n },\n });\n }\n\n async preEvaluateOneOf(ctx: PermissionEvaluationContext) : Promise<void> {\n return this.preEvaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n },\n });\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAa,4BAA4B,OAAO,IAAI,gCAAgC;AAEpF,IAAa,kBAAb,MAAa,wBAAwB,YAAY;CAC7C,YAAY,UAA8B,CAAC,GAAG;EAC1C,MAAM;GACF,GAAG;GACH,SAAS,QAAQ,WAAW;GAC5B,MAAM,QAAQ,QAAQ,UAAU;EACpC,CAAC;EACD,eAAe,MAAM,yBAAyB;CAClD;CAEA,SAAS,MA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kD;EAClE,OAAO,KAAK,SAAS;GACjB,GAAG;GACH,SAAS;IACL,GAAI,IAAI,WAAW,CAAC;IACpB,kBAAkB,iBAAiB;GACvC;EACJ,CAAC;CACL;CAIA,MAAM,YAAY,KAAkD;EAChE,OAAO,KAAK,SAAS;GACjB,GAAG;GACH,SAAS;IACL,GAAI,IAAI,WAAW,CAAC;IACpB,kBAAkB;;;;IAIlB;GACJ;EACJ,CAAC;CACL;CAEA,MAAM,iBAAiB,KAAkD;EACrE,OAAO,KAAK,YAAY;GACpB,GAAG;GACH,SAAS;IACL,GAAI,IAAI,WAAW,CAAC;IACpB,kBAAkB,iBAAiB;GACvC;EACJ,CAAC;CACL;AACJ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["normalizeDate","toDate"],"sources":["../src/permission/error/module.ts","../src/permission/error/check.ts","../src/permission/realm-scope/constants.ts","../src/permission/realm-scope/helpers.ts","../src/permission/helpers/key.ts","../src/permission/helpers/aggregate.ts","../src/permission/helpers/equal.ts","../src/permission/helpers/grant.ts","../src/permission/provider/memory.ts","../src/policy/issue/constants.ts","../src/policy/issue/define.ts","../src/policy/error/module.ts","../src/policy/error/check.ts","../src/policy/engine/module.ts","../src/policy/data.ts","../src/policy/evaluation/context/define.ts","../src/policy/helpers/invert.ts","../src/policy/built-in/attribute-names/validator.ts","../src/policy/built-in/attributes/define.ts","../src/policy/built-in/constants.ts","../src/policy/built-in/attributes/validator.ts","../src/policy/built-in/attributes/evaluator.ts","../src/policy/built-in/attribute-names/evaluator.ts","../src/policy/built-in/composite/validator.ts","../src/policy/built-in/composite/evaluator.ts","../src/policy/built-in/composite/helper.ts","../src/policy/built-in/date/validator.ts","../src/policy/built-in/date/evaluator.ts","../src/policy/built-in/identity/data/validator.ts","../src/policy/built-in/identity/validator.ts","../src/policy/built-in/identity/evaluator.ts","../src/policy/built-in/permission-binding/validator.ts","../src/policy/built-in/permission-binding/module.ts","../src/policy/built-in/realm-match/validator.ts","../src/policy/built-in/realm-match/evaluator.ts","../src/policy/built-in/time/constants.ts","../src/policy/built-in/time/helpers.ts","../src/policy/built-in/time/validator.ts","../src/policy/built-in/time/evaluator.ts","../src/policy/built-in/define.ts","../src/policy/constants.ts","../src/policy/input.ts","../src/permission/evaluator/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { AuthupErrorOptions } from '@authup/errors';\nimport { AuthupError, ErrorCode, markInstanceof } from '@authup/errors';\nimport type { PolicyIssue } from '../../policy';\n\nexport const PERMISSION_ERROR_INSTANCE = Symbol.for('@authup/access/PermissionError');\n\nexport class PermissionError extends AuthupError {\n constructor(options: AuthupErrorOptions = {}) {\n super({\n ...options,\n message: options.message || 'A permission error occurred.',\n code: options.code || ErrorCode.PERMISSION_DENIED,\n });\n markInstanceof(this, PERMISSION_ERROR_INSTANCE);\n }\n\n addIssue(data: PolicyIssue) {\n this.issues.push(data);\n }\n\n addIssues(data: PolicyIssue[]) {\n this.issues.push(...data);\n }\n\n static notFound(name: string) {\n return new PermissionError({\n message: `The permission ${name} was not found.`,\n code: ErrorCode.PERMISSION_NOT_FOUND,\n });\n }\n\n static denied(name: string) {\n return new PermissionError({\n message: `The permission ${name} has not been granted.`,\n code: ErrorCode.PERMISSION_DENIED,\n });\n }\n\n static deniedAll(names: string[]) {\n return new PermissionError({\n message: `None of the permissions ${names.join(', ')} has been granted.`,\n code: ErrorCode.PERMISSION_DENIED,\n });\n }\n\n static evaluationFailed(name: string | string[]) {\n if (Array.isArray(name)) {\n return new PermissionError({\n message: `The evaluation of permissions ${name.join(', ')} failed`,\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n });\n }\n\n return new PermissionError({\n message: `The evaluation of permission ${name} failed`,\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode, hasInstanceof, isAuthupError } from '@authup/errors';\nimport { PERMISSION_ERROR_INSTANCE, type PermissionError } from './module';\n\nexport function isPermissionError(input: unknown): input is PermissionError {\n if (hasInstanceof(input, PERMISSION_ERROR_INSTANCE)) {\n return true;\n }\n\n if (!isAuthupError(input)) {\n return false;\n }\n\n return input.code === ErrorCode.PERMISSION_NOT_FOUND ||\n input.code === ErrorCode.PERMISSION_DENIED ||\n input.code === ErrorCode.PERMISSION_EVALUATION_FAILED;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Actor-relative realm reach of a permission grant.\n *\n * Total order (least -> most permissive): none < own < ownOrNull < any.\n * A missing/unknown column coerces to `own` (fail-closed); `none` is only ever an\n * explicit value (the grant reaches no realm at all).\n */\nexport enum RealmScope {\n /** No reach — the grant matches no resource realm. */\n NONE = 'none',\n /** Own realm only — resource realm must equal the actor's realm. */\n OWN = 'own',\n /** Own realm or null/global resources (realmId === null). */\n OWN_OR_NULL = 'ownOrNull',\n /** Any realm, including null/global. */\n ANY = 'any',\n}\n\n/** Numeric restrictiveness order — internal to the fold/compare helpers. */\nexport const REALM_SCOPE_ORDER: Record<`${RealmScope}`, number> = {\n [RealmScope.NONE]: 0,\n [RealmScope.OWN]: 1,\n [RealmScope.OWN_OR_NULL]: 2,\n [RealmScope.ANY]: 3,\n};\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { REALM_SCOPE_ORDER, RealmScope } from './constants';\n\n/**\n * Coerce an arbitrary value to a RealmScope, defaulting to `own` for missing /\n * null / unknown input (fail-closed). `none` is honoured only when explicit.\n */\nexport function normalizeRealmScope(value?: `${RealmScope}` | null): `${RealmScope}` {\n return value === RealmScope.ANY ||\n value === RealmScope.OWN_OR_NULL ||\n value === RealmScope.NONE ?\n value :\n RealmScope.OWN;\n}\n\n/**\n * Numeric comparison of two realm scopes by restrictiveness.\n * Negative when `a` is more restrictive than `b`, positive when less.\n */\nexport function compareRealmScope(\n a?: `${RealmScope}` | null,\n b?: `${RealmScope}` | null,\n): number {\n return REALM_SCOPE_ORDER[normalizeRealmScope(a)] - REALM_SCOPE_ORDER[normalizeRealmScope(b)];\n}\n\n/** Fold scopes to the MOST permissive (ordered max). Empty folds to `own`. */\nexport function maxRealmScope(values: Array<`${RealmScope}` | null | undefined>): `${RealmScope}` {\n let max: `${RealmScope}` = RealmScope.NONE;\n let seen = false;\n for (const value of values) {\n seen = true;\n const scope = normalizeRealmScope(value);\n if (REALM_SCOPE_ORDER[scope] > REALM_SCOPE_ORDER[max]) {\n max = scope;\n }\n }\n // Empty input is fail-closed `own` (not `none`).\n return seen ? max : RealmScope.OWN;\n}\n\n/** Fold scopes to the MORE restrictive (ordered min) — used to CAP a grant. Empty folds to `own`. */\nexport function minRealmScope(values: Array<`${RealmScope}` | null | undefined>): `${RealmScope}` {\n let min: `${RealmScope}` = RealmScope.ANY;\n let seen = false;\n for (const value of values) {\n seen = true;\n const scope = normalizeRealmScope(value);\n if (REALM_SCOPE_ORDER[scope] < REALM_SCOPE_ORDER[min]) {\n min = scope;\n }\n }\n return seen ? min : RealmScope.OWN;\n}\n\n/**\n * Whether `scope` reaches a single resource realm `resourceRealmId` for an actor whose\n * realm is `identityRealmId`/`identityRealmName`.\n *\n * - `any` -> always.\n * - `none` -> never.\n * - realm-less actor (no realmId and no realmName) -> never `own`/`ownOrNull`.\n * - resource realm `null` (global) -> only `ownOrNull`.\n * - concrete resource realm -> must equal the actor's own realm (by id or name).\n */\nfunction matchesSingle(\n normalized: `${RealmScope}`,\n resourceRealmId: string | null,\n identityRealmId: string | null,\n identityRealmName: string | null,\n): boolean {\n if (resourceRealmId === null) {\n return normalized === RealmScope.OWN_OR_NULL;\n }\n return resourceRealmId === identityRealmId || resourceRealmId === identityRealmName;\n}\n\n/**\n * Whether `scope` reaches the resource. The resource realm may be presented as a single\n * id, `null` (global), or an array of realm ids — the array form (a resource that spans\n * multiple realms) requires the scope to reach EVERY listed realm (unanimous, fail-closed),\n * so any app/entity can express its realm via one or many keys under the canonical contract.\n */\nexport function realmScopeMatches(\n scope: `${RealmScope}` | null | undefined,\n resourceRealmId: string | string[] | null | undefined,\n identityRealmId: string | null | undefined,\n identityRealmName?: string | null,\n): boolean {\n const normalized = normalizeRealmScope(scope);\n if (normalized === RealmScope.ANY) {\n return true;\n }\n if (normalized === RealmScope.NONE) {\n return false;\n }\n\n const realmId = identityRealmId ?? null;\n const realmName = identityRealmName ?? null;\n if (realmId === null && realmName === null) {\n return false;\n }\n\n if (Array.isArray(resourceRealmId)) {\n // Fail closed: an empty realm set is unreachable for a scoped actor (`any`\n // already returned above). `[].every()` would otherwise vacuously pass.\n if (resourceRealmId.length === 0) {\n return false;\n }\n return resourceRealmId.every((id) => matchesSingle(normalized, id ?? null, realmId, realmName));\n }\n\n return matchesSingle(normalized, resourceRealmId ?? null, realmId, realmName);\n}\n","/*\n * Copyright (c) 2025-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n\nimport type { BasePermission } from '../types.ts';\n\nfunction formatKeySegment(value?: string | null): string {\n return value || '*';\n}\n\nexport function buildPermissionKey(\n input: BasePermission,\n) {\n return `${formatKeySegment(input.realmId)}/${formatKeySegment(input.clientId)}/${input.name}`;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { DecisionStrategy } from '@authup/kit';\nimport type { BasePolicy } from '../../policy';\nimport { normalizeRealmScope } from '../realm-scope';\nimport type {\n PermissionGrant,\n PermissionPolicyBinding,\n PermissionPolicyBindingAggregated,\n} from '../types';\nimport { buildPermissionKey } from './key';\n\ntype CompositePolicy = BasePolicy & {\n decisionStrategy?: `${DecisionStrategy}`,\n children: BasePolicy[],\n};\n\n/**\n * One disjunction term per raw binding: the grant's realm reach (fail-closed `own` default)\n * paired with its policy — the raw single policy (its `id` preserved for junction propagation),\n * a composite over multiple policies (Layer-1 permission policies, combined under the\n * permission's decisionStrategy), or `undefined` when the grant is unrestricted.\n */\nfunction buildGrant(binding: PermissionPolicyBinding): PermissionGrant {\n let policy: BasePolicy | undefined;\n if (binding.policies && binding.policies.length === 1) {\n policy = binding.policies[0];\n } else if (binding.policies && binding.policies.length > 1) {\n const composite: CompositePolicy = {\n type: 'composite',\n decisionStrategy: binding.permission.decisionStrategy || DecisionStrategy.UNANIMOUS,\n children: binding.policies,\n };\n policy = composite;\n }\n\n return {\n realmScope: normalizeRealmScope(binding.realmScope),\n policy,\n };\n}\n\n/**\n * Group raw permission-policy bindings by permission key into the actor's disjunction of\n * `(realmScope, policy)` grants per permission — with NO lossy collapse. Every consumer\n * (the binding evaluator, isSuperset, junction propagation, the memory provider) evaluates the\n * grant disjunction directly, so each grant's realm reach stays paired with the policy that\n * gates it.\n */\nexport function aggregatePermissionPolicyBindings(\n input: PermissionPolicyBinding[],\n): PermissionPolicyBindingAggregated[] {\n const grouped: Record<string, PermissionPolicyBinding[]> = input\n .reduce((previous, current) => {\n const key = buildPermissionKey(current.permission);\n if (!previous[key]) {\n previous[key] = [];\n }\n\n previous[key].push(current);\n\n return previous;\n }, {} as Record<string, PermissionPolicyBinding[]>);\n\n const output: PermissionPolicyBindingAggregated[] = [];\n for (const key of Object.keys(grouped)) {\n const group = grouped[key]!;\n output.push({\n permission: group[0]!.permission,\n grants: group.map(buildGrant),\n });\n }\n\n return output;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { BasePermission } from '../types';\n\nexport function isPermissionPolicyBindingEqual(\n a: { permission: BasePermission },\n b: { permission: BasePermission },\n): boolean {\n if (a.permission.name !== b.permission.name) {\n return false;\n }\n\n if ((a.permission.realmId ?? null) !== (b.permission.realmId ?? null)) {\n return false;\n }\n\n if ((a.permission.clientId ?? null) !== (b.permission.clientId ?? null)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isEqual } from 'smob';\nimport type { BasePolicy } from '../../policy';\nimport { compareRealmScope } from '../realm-scope';\nimport type { PermissionGrant } from '../types';\n\n/**\n * Policy fields that do NOT affect evaluation — persisted identity, audit and label columns plus\n * the loaded `parent` / `realm` relation objects. They are stripped before the structural compare\n * in isPolicyEquivalent so two DISTINCT rows with identical configuration still match. Verified\n * against every built-in evaluator, which read only `type`, `invert`, `decisionStrategy`,\n * `children` and the type-specific config (query / names / types / start / end / interval /\n * dayOf* / attributeName* / scope). `parent` is additionally a circular back-reference and\n * `realm` a nested object with its own id, so leaving either in would break the deep compare.\n *\n * SECURITY INVARIANT: every key here MUST stay non-evaluation-affecting. Adding an\n * evaluation-relevant field would silently widen equivalence into an over-permit. New *config*\n * fields need NOT be added — they are compared by default, which is the fail-closed direction.\n */\nconst NON_SEMANTIC_POLICY_KEYS = new Set<string>([\n 'id',\n 'builtIn',\n 'name',\n 'displayName',\n 'description',\n 'parentId',\n 'parent',\n 'realmId',\n 'realm',\n 'createdAt',\n 'updatedAt',\n]);\n\n/**\n * Project a policy node onto its evaluation-relevant configuration: drop the non-semantic keys\n * and recurse through `children` (the only field that carries nested policy nodes). Config values\n * (e.g. an `attributes` `query`) are left untouched, so a semantic `id` / `name` key *inside* a\n * query is never mistaken for the policy's own identity column.\n */\nfunction normalizePolicyForEquality(policy: BasePolicy): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(policy)) {\n if (NON_SEMANTIC_POLICY_KEYS.has(key)) {\n continue;\n }\n\n const value = (policy as Record<string, unknown>)[key];\n if (\n key === 'children' &&\n Array.isArray(value)\n ) {\n result[key] = value.map((child) => normalizePolicyForEquality(child as BasePolicy));\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Whether two restriction policies are provably the SAME policy for domination purposes — by\n * persisted identity OR by identical configuration, never by evaluated effect. Fast path: equal\n * primary-key `id` means the same persisted row (the `typeof … === 'string'` guards keep an\n * id-less / missing-id policy out of it — never `undefined === undefined`). Otherwise fall back to\n * a structural value-compare of the configuration (`normalizePolicyForEquality` strips the\n * non-semantic identity / audit / relation columns, `isEqual` deep-compares the rest), so two\n * distinct rows with identical config — the same predicate — still dominate. Comparing by\n * *effect* is undecidable (a policy is a predicate over PolicyData), so we accept ONLY provable\n * identity or provable structural equality; a genuinely different configuration is treated as\n * distinct (fail-closed) — isSuperset must never assume one restriction covers a different one.\n */\nfunction isPolicyEquivalent(parent: BasePolicy, child: BasePolicy): boolean {\n const parentId = (parent as { id?: unknown }).id;\n const childId = (child as { id?: unknown }).id;\n\n if (\n typeof parentId === 'string' &&\n typeof childId === 'string' &&\n parentId === childId\n ) {\n return true;\n }\n\n return isEqual(normalizePolicyForEquality(parent), normalizePolicyForEquality(child));\n}\n\n/**\n * Whether the actor's `parent` policy provably covers the target's `child` policy on a shared\n * permission. Conservative / fail-closed:\n * - an unrestricted parent (no policy) covers any child;\n * - a restricted parent NEVER covers an unrestricted child — it cannot confer the wider,\n * policy-free reach it does not itself hold;\n * - two restricted grants cover one another only when their policies are provably equivalent.\n * A DIFFERENT policy is NOT assumed to be a subset (#3159: the predecessor treated any two\n * policy-bound grants as mutually dominating, a latent over-permit across disjoint policy\n * scopes — e.g. an actor restricted to `department=X` conferring a `department=Y` grant).\n */\nfunction policyDominates(parent?: BasePolicy, child?: BasePolicy): boolean {\n if (!parent) {\n return true;\n }\n\n if (!child) {\n return false;\n }\n\n return isPolicyEquivalent(parent, child);\n}\n\n/**\n * Whether the actor's `parent` grant covers the target's `child` grant: it reaches at least as\n * far (ordered none < own < ownOrNull < any) AND its policy provably covers the child's\n * (see `policyDominates`). Used per grant by `isSuperset` over the aggregated disjunction —\n * every child grant must be dominated by SOME parent grant.\n */\nexport function grantDominates(parent: PermissionGrant, child: PermissionGrant): boolean {\n if (compareRealmScope(parent.realmScope, child.realmScope) < 0) {\n return false;\n }\n\n return policyDominates(parent.policy, child.policy);\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { aggregatePermissionPolicyBindings, buildPermissionKey } from '../helpers';\nimport type { PermissionPolicyBinding, PermissionPolicyBindingAggregated } from '../types';\nimport type { IPermissionProvider, PermissionGetOptions } from './types';\n\nexport class PermissionMemoryProvider implements IPermissionProvider {\n protected items : Record<string, PermissionPolicyBindingAggregated> = {};\n\n constructor(items: PermissionPolicyBinding[] = []) {\n this.setMany(items);\n }\n\n async findOne(\n options: PermissionGetOptions,\n ): Promise<PermissionPolicyBindingAggregated | null> {\n const key = buildPermissionKey({\n name: options.name,\n clientId: options.clientId,\n realmId: options.realmId,\n });\n\n const entry = this.items[key];\n if (entry) {\n return entry;\n }\n\n return null;\n }\n\n setMany(input: PermissionPolicyBinding[]) {\n this.items = aggregatePermissionPolicyBindings(input)\n .reduce((prev, current) => {\n const key = buildPermissionKey(current.permission);\n prev[key] = current;\n return prev;\n }, {} as Record<string, PermissionPolicyBindingAggregated>);\n }\n}\n","/*\n * Copyright (c) 2026-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum PolicyIssueSeverity {\n WARNING = 'warning',\n ERROR = 'error',\n}\n\nexport enum PolicyIssueCode {\n // Data/Input\n DATA_MISSING = 'DATA_MISSING',\n DATA_INVALID = 'DATA_INVALID',\n\n // Policy Spec / Config\n INVALID = 'INVALID',\n TYPE_UNKNOWN = 'TYPE_UNKNOWN',\n FIELD_MISSING = 'FIELD_MISSING',\n FIELD_INVALID = 'FIELD_INVALID',\n\n // Composite / Tree evaluation\n CHILD_INVALID = 'CHILD_INVALID',\n CHILD_EVALUATION_FAILED = 'CHILD_EVALUATION_FAILED',\n\n // Engine / Evaluator registry\n EVALUATION_DENIED = 'EVALUATION_DENIED',\n EVALUATOR_NOT_FOUND = 'EVALUATOR_NOT_FOUND',\n EVALUATOR_ERROR = 'EVALUATOR_ERROR',\n\n // Execution control\n SKIPPED_EXCLUDED = 'SKIPPED_EXCLUDED',\n SKIPPED_NOT_INCLUDED = 'SKIPPED_NOT_INCLUDED',\n\n // Internal / unexpected\n INTERNAL_ERROR = 'INTERNAL_ERROR',\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { defineIssueGroup, defineIssueItem } from 'validup';\nimport type { PolicyIssueGroup, PolicyIssueItem } from './types.ts';\n\nexport function definePolicyIssueItem(input: Omit<PolicyIssueItem, 'type'>) : PolicyIssueItem {\n return defineIssueItem(input);\n}\n\nexport function definePolicyIssueGroup(input: Omit<PolicyIssueGroup, 'type'>) : PolicyIssueGroup {\n return defineIssueGroup(input);\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AuthupError, ErrorCode, markInstanceof } from '@authup/errors';\nimport type { PolicyIssue } from '../issue';\n\nexport const POLICY_ERROR_INSTANCE = Symbol.for('@authup/access/PolicyError');\n\nexport class PolicyError extends AuthupError {\n constructor(message?: string, code?: string | null) {\n super({\n message,\n code: code ?? undefined,\n });\n markInstanceof(this, POLICY_ERROR_INSTANCE);\n }\n\n addIssue(data: PolicyIssue) {\n this.issues.push(data);\n }\n\n addIssues(data: PolicyIssue[]) {\n this.issues.push(...data);\n }\n\n static evaluatorNotFound(type: string) {\n return new PolicyError(\n `No evaluator is registered to handle the policy: ${type}`,\n ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n );\n }\n\n static evaluatorNotProcessable() {\n return new PolicyError(\n 'The evaluator can not process the policy.',\n ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n );\n }\n\n static evaluatorContextInvalid() {\n return new PolicyError(\n 'The evaluator context is not valid.',\n ErrorCode.POLICY_EVALUATOR_CONTEXT_INVALID,\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode, hasInstanceof, isAuthupError } from '@authup/errors';\nimport { POLICY_ERROR_INSTANCE, type PolicyError } from './module';\n\nexport function isPolicyError(input: unknown): input is PolicyError {\n if (hasInstanceof(input, POLICY_ERROR_INSTANCE)) {\n return true;\n }\n\n if (!isAuthupError(input)) {\n return false;\n }\n\n return input.code === ErrorCode.POLICY_EVALUATOR_NOT_FOUND ||\n input.code === ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE ||\n input.code === ErrorCode.POLICY_EVALUATOR_CONTEXT_INVALID;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { ErrorCode } from '@authup/errors';\nimport { defineIssueItem } from 'validup';\nimport type {\n IPolicyEvaluator,\n PolicyEvaluationContext,\n PolicyEvaluationResult,\n PolicyEvaluators,\n} from '../evaluation';\nimport type { PolicyIssue } from '../issue';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../issue';\nimport type { IPolicyEngine } from './types.ts';\nimport { PolicyError, isPolicyError } from '../error';\nimport type { BasePolicy } from '../types.ts';\n\n// Cross-realm-safe extraction of an error message from an unknown thrown\n// value. `instanceof Error` is unreliable across module boundaries (different\n// realms, dual-bundled packages), so we duck-type on the `message` shape.\nfunction errorMessage(value: unknown): string {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'message' in value &&\n typeof (value as { message: unknown }).message === 'string'\n ) {\n return (value as { message: string }).message;\n }\n return String(value);\n}\n\n/**\n * The policy engine is a component that interprets defined policies and makes decisions\n * on whether to allow or deny a particular access.\n */\nexport class PolicyEngine implements IPolicyEngine {\n protected evaluators : Record<string, IPolicyEvaluator>;\n\n constructor(evaluators: PolicyEvaluators = {}) {\n this.evaluators = evaluators;\n }\n\n public registerEvaluator(\n type: string,\n evaluator: IPolicyEvaluator,\n ) : void {\n this.evaluators[type] = evaluator;\n }\n\n public registerEvaluators(evaluators: PolicyEvaluators) {\n const keys = Object.keys(evaluators);\n for (const key of keys) {\n this.registerEvaluator(key, evaluators[key]!);\n }\n }\n\n /**\n * @param policy\n * @param ctx\n */\n async evaluate(policy: BasePolicy, ctx: PolicyEvaluationContext) : Promise<PolicyEvaluationResult> {\n // Infrastructure errors (no type, no evaluator, evaluator threw) MUST\n // fail closed regardless of `policy.invert`. Inverting an error path\n // would silently grant access on misconfiguration — with `invert: true`\n // an unregistered policy type would return success: true.\n if (!policy.type) {\n return {\n success: false,\n issues: [\n defineIssueItem({\n path: [],\n message: 'The policy can not be handled by any evaluator.',\n code: ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n }),\n ],\n };\n }\n // When a policy is filtered out via include/exclude, treat it as a\n // neutral pass — do NOT apply `invert`. Inversion only makes sense\n // for an actual evaluation outcome; skipping a policy because it's\n // outside the current context's scope is not an outcome.\n if (\n ctx.exclude &&\n ctx.exclude.length > 0 &&\n ctx.exclude.includes(policy.type)\n ) {\n return { success: true };\n }\n\n if (\n ctx.include &&\n ctx.include.length > 0 &&\n !ctx.include.includes(policy.type)\n ) {\n return { success: true };\n }\n\n const issues : PolicyIssue[] = [];\n\n const evaluator = this.evaluators[policy.type];\n if (!evaluator) {\n issues.push(defineIssueItem({\n path: [policy.type],\n message: `The policy ${policy.type} can not be handled by any evaluator.`,\n code: ErrorCode.POLICY_EVALUATOR_NOT_FOUND,\n }));\n\n return {\n success: false,\n issues,\n };\n }\n\n // Data-availability gate: a policy whose declared data requirements are not\n // satisfied yet is PENDING — not true, not false. Like the include/exclude\n // neutral-pass, `invert` is never applied here (the evaluator is not invoked\n // at all): unknown stays unknown under negation. Wrapped in the same try as\n // the evaluation itself so a throwing `requires()` fails closed (structured\n // deny) instead of rejecting out of `evaluate()`.\n try {\n if (evaluator.requires) {\n const missing = evaluator.requires(policy)\n .filter((key) => !ctx.data || !ctx.data.has(key));\n\n if (missing.length > 0) {\n const result : PolicyEvaluationResult = {\n success: false,\n pending: true,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: `The data propert${missing.length > 1 ? 'ies' : 'y'} ${missing.join(', ')} ${missing.length > 1 ? 'are' : 'is'} missing`,\n path: ctx.path,\n }),\n ],\n };\n\n // Condition form of the pending leaf (WHERE pushdown), on request only.\n // A throwing / null toCondition simply leaves the result condition-less —\n // the consumer falls back to a per-row post-check (fail-safe).\n if (ctx.withConditions && evaluator.toCondition) {\n try {\n const condition = await evaluator.toCondition(policy, ctx);\n if (condition) {\n result.condition = condition;\n }\n } catch {\n // not expressible — stays a post-check\n }\n }\n\n return result;\n }\n }\n\n return await evaluator.evaluate(policy, {\n ...ctx,\n evaluators: {\n ...this.evaluators,\n ...(ctx.evaluators || {}),\n },\n });\n } catch (e) {\n issues.push(defineIssueItem({\n path: [policy.type],\n message: `The ${policy.type} evaluator threw: ${errorMessage(e)}`,\n code: ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n }));\n\n return {\n success: false,\n issues,\n };\n }\n }\n\n async evaluateOrFail(policy: BasePolicy, ctx: PolicyEvaluationContext) : Promise<void> {\n const issues : PolicyIssue[] = [];\n\n try {\n const outcome = await this.evaluate(policy, ctx);\n if (outcome.success) {\n return;\n }\n\n if (outcome.issues) {\n issues.push(...outcome.issues);\n }\n } catch (e) {\n if (isPolicyError(e)) {\n throw e;\n }\n\n // Surface non-PolicyError throws (DB failures, validator crashes, etc.)\n // as issues so the root cause is visible instead of being swallowed\n // behind a generic policy failure.\n issues.push(defineIssueItem({\n path: policy.type ? [policy.type] : [],\n message: errorMessage(e),\n code: ErrorCode.POLICY_EVALUATOR_NOT_PROCESSABLE,\n }));\n }\n\n const error = new PolicyError(`The policy ${policy.type} evaluation failed.`);\n error.addIssues(issues);\n\n throw error;\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport interface IPolicyData {\n set(key: string, value: unknown) : void;\n has(key: string): boolean;\n get<T = unknown>(key: string) : T;\n\n isValidated(key: string): boolean;\n setValidated(key: string) : void;\n\n clone() : IPolicyData\n}\n\nexport class PolicyData implements IPolicyData {\n protected data: Record<string, any>;\n\n protected validated : Set<string>;\n\n constructor(\n data: Record<string, any> = {},\n validated: Set<string> = new Set(),\n ) {\n this.data = data;\n this.validated = validated;\n }\n\n set<T = unknown>(key: string, value: T) : void {\n this.data[key] = value;\n this.validated.delete(key);\n }\n\n get<T = unknown>(key: string) : T {\n if (key in this.data) {\n return this.data[key];\n }\n\n throw new Error(`Policy data item ${key} does not exist.`);\n }\n\n has(key: string): boolean {\n return key in this.data;\n }\n\n setValidated(key: string) : void {\n this.validated.add(key);\n }\n\n isValidated(key: string) : boolean {\n return this.validated.has(key);\n }\n\n clone() {\n return new PolicyData({ ...this.data }, new Set(this.validated));\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyEvaluationContext, PolicyEvaluationContextInput } from './types.ts';\nimport { PolicyData } from '../../data.ts';\n\nexport function definePolicyEvaluationContext(\n input: PolicyEvaluationContextInput = {},\n) : PolicyEvaluationContext {\n return {\n evaluators: input.evaluators || {},\n path: input.path || [],\n data: input.data || new PolicyData(),\n include: input.include || [],\n exclude: input.exclude || [],\n withConditions: input.withConditions ?? false,\n };\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\ntype InvertFn = (input: boolean) => boolean;\n\nexport function maybeInvertPolicyOutcome(\n outcome: boolean,\n invert?: boolean | InvertFn,\n) {\n if (typeof invert === 'undefined') {\n return outcome;\n }\n\n if (typeof invert === 'function') {\n return invert(outcome);\n }\n\n if (!invert) {\n return outcome;\n }\n\n return !outcome;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { AttributeNamesPolicy } from './types';\n\nexport class AttributeNamesPolicyValidator extends Container<AttributeNamesPolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'names',\n createValidator(\n z.array(\n z.string()\n .min(3)\n .max(128),\n ),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { AttributesPolicy } from './types';\n\nexport function defineAttributesPolicy<\n T extends Record<string, any> = Record<string, any>,\n>(\n data: AttributesPolicy<T>,\n) : AttributesPolicy<T> {\n return data;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum BuiltInPolicyType {\n /**\n * Bundles different policies.\n */\n COMPOSITE = 'composite',\n /**\n * Date Based Access Control (DBAC)\n */\n DATE = 'date',\n /**\n * Time Based Access Control (TBAC)\n */\n TIME = 'time',\n /**\n * Attribute Name Based Access Control (ANBAC)\n */\n ATTRIBUTE_NAMES = 'attributeNames',\n /**\n * Attribute Based Access Control (ABAC)\n */\n ATTRIBUTES = 'attributes',\n /**\n * Realm of Identity is for attribute realm.\n */\n REALM_MATCH = 'realmMatch',\n\n /**\n * Restriction based on identity (type, id, ...)\n */\n IDENTITY = 'identity',\n\n /**\n * Restriction based on a binding between identity <-> permission\n */\n PERMISSION_BINDING = 'permissionBinding',\n\n // Location (LBAC)\n // Device (DBAC)\n}\n\nexport const SystemPolicyName = {\n DEFAULT: 'system.default',\n IDENTITY: 'system.identity',\n PERMISSION_BINDING: 'system.permission-binding',\n REALM_MATCH: 'system.realm-match',\n CLIENT_NAMES_SELF_MANAGE: 'system.client-names-self-manage',\n USER_NAMES_SELF_MANAGE: 'system.user-names-self-manage',\n} as const;\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { AttributesPolicy } from './types';\n\nexport class AttributesPolicyValidator<\n T extends Record<string, any> = Record<string, any>,\n> extends Container<AttributesPolicy<T>> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'query',\n createValidator(\n z.looseObject({}),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ICondition } from '@rapiq/core';\nimport { not } from '@rapiq/core';\nimport type { Predicate } from '@rapiq/memory';\nimport { compileFilters } from '@rapiq/memory';\nimport { MongoFiltersParser } from '@rapiq/parser-mongo';\nimport { isObject } from '@authup/kit';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { BuiltInPolicyType } from '../constants.ts';\nimport type { AttributesPolicy } from './types';\nimport { AttributesPolicyValidator } from './validator';\n\nexport class AttributesPolicyEvaluator<\n T extends Record<string, any> = Record<string, any>,\n> implements IPolicyEvaluator {\n protected validator : AttributesPolicyValidator<T>;\n\n protected parser : MongoFiltersParser;\n\n constructor() {\n this.validator = new AttributesPolicyValidator<T>();\n this.parser = new MongoFiltersParser();\n }\n\n requires() : string[] {\n return [BuiltInPolicyType.ATTRIBUTES];\n }\n\n async toCondition(value: Record<string, any>) : Promise<ICondition | null> {\n let policy : AttributesPolicy<T>;\n let condition : ICondition;\n\n try {\n policy = await this.validator.run(value);\n this.fixQuery(policy.query);\n condition = this.parser.parse(policy.query);\n } catch {\n return null;\n }\n\n // rapiq's not() is the exact null-inclusive complement (tada5hi/rapiq#812) —\n // identical to inverting the compiled predicate's verdict per row.\n return policy.invert ? not(condition) : condition;\n }\n\n async accessData(ctx: PolicyEvaluationContext) : Promise<T | null> {\n if (!ctx.data.has(BuiltInPolicyType.ATTRIBUTES)) {\n return null;\n }\n\n if (ctx.data.isValidated(BuiltInPolicyType.ATTRIBUTES)) {\n return ctx.data.get<T>(BuiltInPolicyType.ATTRIBUTES);\n }\n\n // todo: run validator on attributes (isObject ...)\n const data = ctx.data.get<T>(BuiltInPolicyType.ATTRIBUTES);\n\n ctx.data.set(BuiltInPolicyType.ATTRIBUTES, data);\n ctx.data.setValidated(BuiltInPolicyType.ATTRIBUTES);\n\n return data;\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n const policy = await this.validator.run(value);\n\n const data = await this.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n this.fixQuery(policy.query);\n\n let testIt : Predicate;\n\n try {\n const condition = this.parser.parse(policy.query);\n\n // string equality stays byte-exact (the semantics the previous\n // @ucast/mongo2js evaluator enforced)\n testIt = compileFilters(condition, { caseSensitive: true });\n } catch (e) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.FIELD_INVALID,\n message: e instanceof Error ?\n e.message :\n 'The query could not be parsed.',\n path: ctx.path,\n }),\n ],\n };\n }\n\n return { success: maybeInvertPolicyOutcome(testIt(data), policy.invert) };\n }\n\n protected fixQuery(\n query: unknown | unknown[],\n ) {\n if (Array.isArray(query)) {\n for (const element of query) {\n this.fixQuery(element);\n }\n\n return;\n }\n\n if (isObject(query)) {\n const keys = Object.keys(query);\n for (const key of keys) {\n const value = query[key];\n\n if (isObject(value) || Array.isArray(value)) {\n this.fixQuery(value);\n continue;\n }\n\n if (\n key === '$regex' &&\n typeof value === 'string'\n ) {\n const fragments = value.match(/\\/(.*?)\\/([a-z]*)?$/i);\n if (fragments && fragments[1] !== undefined) {\n query[key] = new RegExp(fragments[1], fragments[2] || '');\n }\n }\n }\n }\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { flattenObject } from '@authup/kit';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport type { PolicyIssue } from '../../issue';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { AttributeNamesPolicyValidator } from './validator';\nimport { AttributesPolicyEvaluator } from '../attributes';\nimport { BuiltInPolicyType } from '../constants';\n\nexport class AttributeNamesPolicyEvaluator implements IPolicyEvaluator {\n protected validator : AttributeNamesPolicyValidator;\n\n protected attributesEvaluator : AttributesPolicyEvaluator;\n\n constructor() {\n this.validator = new AttributeNamesPolicyValidator();\n this.attributesEvaluator = new AttributesPolicyEvaluator();\n }\n\n requires() : string[] {\n return [BuiltInPolicyType.ATTRIBUTES];\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const data = await this.attributesEvaluator.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n // Nested paths are a deliberate feature: an attribute object like\n // `{user: {name: 'x'}}` flattens to `{'user.name': 'x'}` and is matched\n // against `names` entries with dotted notation. Allowlists/denylists\n // that need to govern nested fields must use the dotted-path form\n // (e.g. `'user.realmId'`); a top-level entry like `'realmId'` will\n // NOT catch a nested `user.realmId` write — that's by design, the\n // policy is precise about which path it covers.\n const attributes = flattenObject(data);\n const keys = Object.keys(attributes);\n\n // `invert` is consumed per-key, NOT at the result level:\n // - allowlist (default): a key NOT in `names` is denied\n // - denylist (invert: true): a key IN `names` is denied\n // Result-level inversion would break the empty-input case (a request\n // with no validated attributes would flip success → fail), and would\n // produce nonsensical \"deny iff all keys are in the list\" semantics\n // for partial inputs.\n const issues : PolicyIssue[] = [];\n for (const key of keys) {\n const inList = policy.names.includes(key);\n const denied = policy.invert ? inList : !inList;\n if (denied) {\n issues.push(definePolicyIssueItem({\n code: PolicyIssueCode.EVALUATION_DENIED,\n message: policy.invert ?\n `The attribute ${key} is denied` :\n `The attribute ${key} is not included`,\n path: [...ctx.path, key],\n }));\n }\n }\n\n return {\n success: issues.length === 0,\n issues,\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport { DecisionStrategy } from '@authup/kit';\nimport type { CompositePolicy } from './types';\n\nexport class CompositePolicyValidator extends Container<CompositePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'decisionStrategy',\n createValidator(\n z.enum(DecisionStrategy)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'children',\n createValidator(\n z.array(z.looseObject({ type: z.string().min(3) })),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ICondition } from '@rapiq/core';\nimport { and, not, or } from '@rapiq/core';\nimport { defineIssueGroup } from 'validup';\nimport { DecisionStrategy } from '@authup/kit';\nimport { PolicyEngine } from '../../engine';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport type { PolicyIssue } from '../../issue';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { CompositePolicyValidator } from './validator';\n\nexport class CompositePolicyEvaluator implements IPolicyEvaluator {\n protected validator : CompositePolicyValidator;\n\n constructor() {\n this.validator = new CompositePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n // A composite policy with no children can never be satisfied — an empty\n // UNANIMOUS/CONSENSUS settles false and an empty AFFIRMATIVE settles\n // false — so a permission bound to one is permanently un-grantable.\n // Fail closed with an explicit diagnostic instead of settling `false`\n // with an empty issue list, which reads as an opaque \"stale\" permission\n // (#3304). Like the engine's unregistered-type handling, this\n // misconfiguration fails closed regardless of `invert`.\n if (policy.children.length === 0) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.INVALID,\n message: 'A composite policy must define at least one child policy.',\n path: ctx.path,\n }),\n ],\n };\n }\n\n let count = 0;\n let pending = 0;\n\n const decisionStrategy = policy.decisionStrategy ??\n DecisionStrategy.UNANIMOUS;\n\n const engine = new PolicyEngine(ctx.evaluators);\n const issues : PolicyIssue[] = [];\n const pendingIssues : PolicyIssue[] = [];\n const pendingConditions : ICondition[] = [];\n let pendingWithoutCondition = 0;\n\n for (const childPolicy of policy.children) {\n const path = [\n ...(ctx.path || []),\n ...(childPolicy.type ? [childPolicy.type] : []),\n ];\n\n const outcome = await engine.evaluate(childPolicy, {\n ...ctx,\n path,\n });\n\n // A pending child is UNKNOWN, not a failure: it neither counts nor\n // early-returns. Masking it to a settled value breaks under negation\n // (mask-then-negate ≠ negate-then-mask — issue #3286).\n if (outcome.pending) {\n pending++;\n\n if (outcome.condition) {\n pendingConditions.push(outcome.condition);\n } else {\n pendingWithoutCondition++;\n }\n\n if (outcome.issues && outcome.issues.length > 0) {\n pendingIssues.push(defineIssueGroup({\n message: `The evaluation of child policy ${childPolicy.type} is pending`,\n issues: outcome.issues,\n path,\n }));\n }\n\n continue;\n }\n\n if (outcome.success) {\n if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return {\n success: maybeInvertPolicyOutcome(true, policy.invert),\n issues: [],\n };\n }\n\n count++;\n } else {\n if (outcome.issues) {\n issues.push(defineIssueGroup({\n message: `The evaluation of child policy ${childPolicy.type} failed`,\n issues: outcome.issues || [],\n path,\n }));\n }\n\n if (decisionStrategy === DecisionStrategy.UNANIMOUS) {\n const success = maybeInvertPolicyOutcome(false, policy.invert);\n return {\n success,\n // When `invert` flips a child-failure into success,\n // suppress the issue list — surfacing failure issues\n // alongside `success: true` is misleading.\n issues: success ? [] : [\n defineIssueGroup({\n message: `The evaluation of composite policy failed (${DecisionStrategy.UNANIMOUS})`,\n issues,\n path: ctx.path,\n }),\n ],\n };\n }\n\n count--;\n }\n }\n\n // Settle the remainder: the composite settles despite pending children only\n // when no resolution of those children could change the outcome.\n let settled : boolean | null;\n switch (decisionStrategy) {\n case DecisionStrategy.AFFIRMATIVE: {\n // every settled child failed; any pending child could still succeed\n settled = pending > 0 ? null : false;\n break;\n }\n case DecisionStrategy.UNANIMOUS: {\n // every settled child succeeded; any pending child could still fail\n settled = pending > 0 ? null : count > 0;\n break;\n }\n default: {\n // CONSENSUS: final outcome is `count > 0`, each pending worth ±1\n if (count - pending > 0) {\n settled = true;\n } else if (count + pending <= 0) {\n settled = false;\n } else {\n settled = null;\n }\n }\n }\n\n if (settled === null) {\n // Unknown stays unknown — `invert` is deliberately NOT applied to the\n // pending SUCCESS. The condition form is composed structurally instead:\n // settled children are identity elements and drop out of the residual,\n // so AND residual = and(pending), OR residual = or(pending). Exact-only,\n // all-or-nothing per node: one pending child without a condition makes\n // the whole node non-expressible (an OR pushing a single disjunct would\n // wrongly EXCLUDE rows; a partial AND is a compiler-level optimization,\n // deliberately not done here). CONSENSUS thresholds over row-dependent\n // outcomes never lower. `invert` wraps the residual SYMBOLICALLY via\n // rapiq's null-inclusive-complement not() — negation applies to the\n // condition even though the pending success stays uninverted.\n let condition : ICondition | null = null;\n if (\n ctx.withConditions &&\n pendingWithoutCondition === 0 &&\n pendingConditions.length > 0 &&\n decisionStrategy !== DecisionStrategy.CONSENSUS\n ) {\n if (pendingConditions.length === 1) {\n const [first] = pendingConditions;\n condition = first ?? null;\n } else if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n condition = or(...pendingConditions);\n } else {\n condition = and(...pendingConditions);\n }\n\n if (condition && policy.invert) {\n condition = not(condition);\n }\n }\n\n return {\n success: false,\n pending: true,\n ...(condition ? { condition } : {}),\n issues: pendingIssues,\n };\n }\n\n if (settled) {\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n\n const success = maybeInvertPolicyOutcome(false, policy.invert);\n return {\n success,\n issues: success ? [] : [\n defineIssueGroup({\n message: `The evaluation of composite policy failed (${decisionStrategy})`,\n issues: issues || [],\n path: ctx.path,\n }),\n ],\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyWithType } from '../../types';\nimport { BuiltInPolicyType } from '../constants';\nimport type { CompositePolicy } from './types';\n\nexport function isCompositePolicy(\n input: PolicyWithType,\n) : input is PolicyWithType<CompositePolicy> {\n return input.type === BuiltInPolicyType.COMPOSITE;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { DatePolicy } from './types';\n\nexport class DatePolicyValidator extends Container<DatePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount('start', createValidator(\n z.date()\n .or(z.iso.date())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('end', createValidator(\n z.date()\n .or(z.iso.date())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount('invert', createValidator(\n z.boolean()\n .or(z.undefined())\n .or(z.null())\n .optional(),\n ));\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants.ts';\nimport { DatePolicyValidator } from './validator';\n\nfunction normalizeDate(input: Date) {\n return new Date(input.getFullYear(), input.getMonth(), input.getDate());\n}\n\nfunction toDate(input: Date | string | number) : Date {\n if (typeof input === 'string') {\n return new Date(input);\n }\n\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n return input;\n}\n\nexport class DatePolicyEvaluator implements IPolicyEvaluator {\n protected validator : DatePolicyValidator;\n\n constructor() {\n this.validator = new DatePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n let now : Date;\n\n if (ctx.data.has(BuiltInPolicyType.DATE)) {\n if (ctx.data.isValidated(BuiltInPolicyType.DATE)) {\n now = ctx.data.get<Date>(BuiltInPolicyType.DATE);\n } else {\n // todo: run validator on attributes (isObject ...)\n now = normalizeDate(toDate(ctx.data.get(BuiltInPolicyType.DATE)));\n\n ctx.data.set(BuiltInPolicyType.DATE, now);\n ctx.data.setValidated(BuiltInPolicyType.DATE);\n }\n } else {\n now = normalizeDate(new Date());\n }\n\n if (policy.start) {\n const start = normalizeDate(toDate(policy.start));\n if (now < start) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.end) {\n const end = normalizeDate(toDate(policy.end));\n if (now > end) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\n\nimport type { IdentityPolicyData } from '../types.ts';\n\nexport class PolicyIdentityDataValidator extends Container<IdentityPolicyData> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'type',\n createValidator(\n z.string().min(3).max(128),\n ),\n );\n\n this.mount(\n 'id',\n createValidator(\n z.uuid(),\n ),\n );\n\n this.mount(\n 'clientId',\n createValidator(\n z.uuid()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'realmId',\n createValidator(\n z.uuid()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'realmName',\n createValidator(\n z.string().min(3).max(128)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { IdentityPolicy } from './types';\n\nexport class IdentityPolicyValidator extends Container<IdentityPolicy> {\n override initialize() {\n this.mount(\n 'types',\n createValidator(\n z.array(z.string())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants';\nimport { PolicyIdentityDataValidator } from './data';\nimport type { IdentityPolicyData } from './types';\nimport { IdentityPolicyValidator } from './validator';\n\nexport class IdentityPolicyEvaluator implements IPolicyEvaluator {\n protected validator : IdentityPolicyValidator;\n\n protected dataValidator : PolicyIdentityDataValidator;\n\n constructor() {\n this.validator = new IdentityPolicyValidator();\n this.dataValidator = new PolicyIdentityDataValidator();\n }\n\n requires() : string[] {\n return [BuiltInPolicyType.IDENTITY];\n }\n\n async accessData(ctx: PolicyEvaluationContext) : Promise<IdentityPolicyData | null> {\n if (!ctx.data.has('identity')) {\n return null;\n }\n\n if (ctx.data.isValidated('identity')) {\n return ctx.data.get<IdentityPolicyData>('identity');\n }\n\n const data = await this.dataValidator.run(ctx.data.get('identity'));\n\n ctx.data.set('identity', data);\n ctx.data.setValidated('identity');\n\n return data;\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const data = await this.accessData(ctx);\n if (!data) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property identity is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n if (!policy.types || policy.types.length === 0) {\n // Empty types is a configuration shorthand for \"no type\n // restriction\" — every identity passes. Do NOT apply `invert`;\n // inverting an empty config would silently deny all identities,\n // which is almost never the user's intent.\n return { success: true };\n }\n\n const typeAllowed = policy.types.includes(data.type);\n if (typeAllowed) {\n return { success: maybeInvertPolicyOutcome(typeAllowed, policy.invert) };\n }\n\n return {\n success: maybeInvertPolicyOutcome(typeAllowed, policy.invert),\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.EVALUATION_DENIED,\n message: `The type ${data.type} is not covered by the policy configuration`,\n path: ctx.path,\n }),\n ],\n };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { Container } from 'validup';\nimport type { PermissionBindingPolicy } from './types';\n\nexport class PermissionBindingPolicyValidator extends Container<PermissionBindingPolicy> {\n override initialize() {\n\n }\n}\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants';\nimport { PermissionBindingPolicyValidator } from './validator';\n\nexport class PermissionBindingPolicyEvaluator implements IPolicyEvaluator {\n protected validator: PermissionBindingPolicyValidator;\n\n constructor() {\n this.validator = new PermissionBindingPolicyValidator();\n }\n\n requires() : string[] {\n // IDENTITY is deliberately NOT declared: a missing identity must stay a\n // settled deny (fail-closed), never a pending the pre-gate would permit.\n return [BuiltInPolicyType.PERMISSION_BINDING];\n }\n\n async evaluate(value: Record<string, any>): Promise<PolicyEvaluationResult> {\n const policy = await this.validator.run(value);\n\n // todo: this must be changed when the permission-checker not only checks owned permissions.\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport { DecisionStrategy } from '@authup/kit';\nimport { RealmScope } from '../../../permission/realm-scope';\nimport type { RealmMatchPolicy } from './types';\n\nexport class RealmMatchPolicyValidator extends Container<RealmMatchPolicy> {\n override initialize() {\n super.initialize();\n\n this.mount(\n 'decisionStrategy',\n createValidator(\n z.enum(DecisionStrategy)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'attributeName',\n createValidator(\n z.string()\n .min(3)\n .or(z.array(z.string().min(3)))\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n this.mount(\n 'attributeNameStrict',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n this.mount(\n 'attributeNullMatchAll',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'scope',\n createValidator(\n z.enum(RealmScope)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ICondition } from '@rapiq/core';\nimport {\n eq, \n inArray, \n nin, \n not, \n or,\n} from '@rapiq/core';\nimport { DecisionStrategy, hasOwnProperty } from '@authup/kit';\nimport { RealmScope, normalizeRealmScope, realmScopeMatches } from '../../../permission/realm-scope';\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { PolicyIssueCode, definePolicyIssueItem } from '../../issue';\nimport { AttributesPolicyEvaluator } from '../attributes';\nimport { BuiltInPolicyType } from '../constants';\nimport { IdentityPolicyEvaluator } from '../identity';\nimport { RealmMatchPolicyValidator } from './validator';\n\nexport class RealmMatchPolicyEvaluator implements IPolicyEvaluator {\n protected validator : RealmMatchPolicyValidator;\n\n protected identityEvaluator: IdentityPolicyEvaluator;\n\n protected attributesEvaluator : AttributesPolicyEvaluator;\n\n constructor() {\n this.validator = new RealmMatchPolicyValidator();\n this.identityEvaluator = new IdentityPolicyEvaluator();\n this.attributesEvaluator = new AttributesPolicyEvaluator();\n }\n\n requires(value: Record<string, any>) : string[] {\n // SCOPE MODE: the resource realm key (REALM_MATCH) is deliberately NOT\n // required — an absent key is the documented neutral-pass (gate checks /\n // realm-less resources), so requiring it would wrongly pend those runs.\n if (value.scope) {\n return [BuiltInPolicyType.IDENTITY];\n }\n\n return [BuiltInPolicyType.IDENTITY, BuiltInPolicyType.ATTRIBUTES];\n }\n\n /**\n * Condition form over the row's realm column, with the actor realm baked in\n * (mirrors `realmScopeMatches` / the attribute-mode match). Exactness holds for\n * row-shaped data where the referenced field exists (DB rows) — the object-bag\n * \"key absent → neutral-pass\" case has no SQL counterpart. Lowerable configs:\n * scope mode (field = single-string `attributeName`, default `realmId` — scope-mode\n * EVALUATION ignores `attributeName`, lowering reuses it as the column override),\n * and strict attribute mode with a single explicit `attributeName`. Everything\n * else (multi-key / default-key CONSENSUS, non-strict key expansion) is\n * row-shape-dependent and stays a post-check.\n */\n async toCondition(value: Record<string, any>, ctx: PolicyEvaluationContext) : Promise<ICondition | null> {\n let policy;\n try {\n policy = await this.validator.run(value);\n } catch {\n return null;\n }\n\n const identity = await this.identityEvaluator.accessData(ctx);\n if (!identity) {\n return null;\n }\n\n const realmId = identity.realmId ?? null;\n\n if (policy.scope) {\n const scope = normalizeRealmScope(policy.scope);\n const field = typeof policy.attributeName === 'string' ?\n policy.attributeName :\n 'realmId';\n\n let condition : ICondition;\n if (scope === RealmScope.ANY) {\n // constant-true: nin([]) matches everything (rapiq ConstantPlan)\n condition = nin(field, []);\n } else {\n // The lowered column (default `realmId`) holds realm IDs — the resource\n // realm is stamped from `entity.realmId`\n // (AbstractEntityService.resourceRealmMatch), so the WHERE match compares\n // that ID column against the actor's realm ID. The realm NAME is\n // deliberately NOT pushed here: it never appears in a realmId column and\n // would bind a non-uuid literal that postgres/mysql reject against a uuid\n // column (the sqlite-only test suite masks this, since sqlite is untyped).\n // Settled evaluation keeps the name-equality leniency for a name-stamped\n // resource SCALAR — which has no row-column counterpart, so parity holds\n // for realistic row-shaped data (see the exactness caveat above).\n const terms : ICondition[] = [];\n if (scope !== RealmScope.NONE && realmId !== null) {\n terms.push(eq(field, realmId));\n }\n if (scope === RealmScope.OWN_OR_NULL) {\n terms.push(eq(field, null));\n }\n\n if (terms.length === 0) {\n // no reach / realm-less actor with no null branch — constant-false\n condition = inArray(field, []);\n } else if (terms.length === 1) {\n condition = terms[0]!;\n } else {\n condition = or(...terms);\n }\n }\n\n return policy.invert ? not(condition) : condition;\n }\n\n if (\n typeof policy.attributeName !== 'string' ||\n (policy.attributeNameStrict ?? true) === false\n ) {\n return null;\n }\n\n // Mirrors the match loop's strict equality: `attributeValue === identity.realmId`\n // — an identity carrying an explicit `realmId: null` matches null-valued rows\n // (only an UNDEFINED identity value never matches a DB value, so it drops out).\n const key = policy.attributeName;\n const terms : ICondition[] = [];\n if (policy.attributeNullMatchAll) {\n terms.push(eq(key, null));\n }\n if (identity.realmId !== undefined) {\n terms.push(eq(key, identity.realmId));\n }\n if (identity.realmName !== undefined) {\n terms.push(eq(key, identity.realmName));\n }\n\n if (terms.length === 0) {\n return policy.invert ? nin(key, []) : inArray(key, []);\n }\n\n const condition = terms.length === 1 ? terms[0]! : or(...terms);\n return policy.invert ? not(condition) : condition;\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n const identity = await this.identityEvaluator.accessData(ctx);\n if (!identity) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property identity is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n // SCOPE MODE: coarse, actor-relative realm reach (the realmScope mechanism lives\n // here). The resource realm is supplied under the REALM_MATCH data key. Key-PRESENCE\n // is the discriminator: an ABSENT realm neutral-passes (gate check / realm-less\n // resource), while a present `null` (global resource) is matched (and `own` correctly\n // denies it). Runs BEFORE the attributes-required guard below, since junction / gate\n // inputs need not carry ATTRIBUTES.\n if (policy.scope) {\n if (!ctx.data || !ctx.data.has(BuiltInPolicyType.REALM_MATCH)) {\n // Non-evaluation (no resource realm) — neutral pass, no `invert`,\n // mirroring the attribute-mode non-evaluation pass below. For a\n // query-build caller (`withConditions`) the resource realm IS the\n // unknown row column, so the reach pends with its condition form\n // instead of neutral-passing.\n if (ctx.withConditions) {\n const condition = await this.toCondition(value, ctx);\n return {\n success: false,\n pending: true,\n ...(condition ? { condition } : {}),\n };\n }\n\n return { success: true };\n }\n\n const resourceRealm = ctx.data.get<string | string[] | null>(BuiltInPolicyType.REALM_MATCH);\n return {\n success: maybeInvertPolicyOutcome(\n realmScopeMatches(\n policy.scope,\n resourceRealm ?? null,\n identity.realmId,\n identity.realmName,\n ),\n policy.invert,\n ),\n };\n }\n\n const attributes = await this.attributesEvaluator.accessData(ctx);\n if (!attributes) {\n return {\n success: false,\n issues: [\n definePolicyIssueItem({\n code: PolicyIssueCode.DATA_MISSING,\n message: 'The data property attributes is missing',\n path: ctx.path,\n }),\n ],\n };\n }\n\n let keys : string[];\n if (policy.attributeName) {\n if (Array.isArray(policy.attributeName)) {\n keys = policy.attributeName;\n } else {\n keys = [policy.attributeName];\n }\n } else {\n keys = [\n 'realm_id',\n 'realm_name',\n 'realmId',\n 'realmName',\n ];\n\n policy.decisionStrategy = DecisionStrategy.CONSENSUS;\n }\n\n const attributeNameStrict = policy.attributeNameStrict ?? true;\n if (!attributeNameStrict) {\n const resourceKeys = Object.keys(attributes);\n const keysToAdd : string[] = [];\n for (const resourceKey of resourceKeys) {\n let contains : boolean = false;\n\n for (const key of keys) {\n if (\n resourceKey !== key &&\n resourceKey.includes(key)\n ) {\n contains = true;\n break;\n }\n }\n\n if (contains) {\n keysToAdd.push(resourceKey);\n }\n }\n\n if (keysToAdd.length > 0) {\n keys.push(...keysToAdd);\n }\n }\n\n let count = 0;\n let evaluated = false;\n\n for (const key of keys) {\n if (!hasOwnProperty(attributes, key)) {\n continue;\n }\n\n evaluated = true;\n\n let outcome : boolean = false;\n\n const attributeValue = attributes[key];\n\n if (\n attributeValue === null &&\n policy.attributeNullMatchAll\n ) {\n outcome = true;\n } else if (\n attributeValue === identity.realmId ||\n attributeValue === identity.realmName\n ) {\n outcome = true;\n }\n\n if (outcome) {\n if (policy.decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n\n count++;\n } else {\n if (policy.decisionStrategy === DecisionStrategy.UNANIMOUS) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n\n count--;\n }\n }\n\n if (!evaluated) {\n // No realm key found in attributes — the policy's match logic\n // didn't run. This is a \"non-evaluation\", not an outcome; treat\n // as a neutral pass without applying `invert`. Inverting here\n // would conflate \"policy doesn't apply\" with \"policy denies\".\n return { success: true };\n }\n\n return { success: maybeInvertPolicyOutcome(count > 0, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum TimePolicyInterval {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { TimePolicyInterval } from './constants';\n\nexport function isIntervalForDayOfWeek(\n interval: string,\n) {\n return interval === TimePolicyInterval.WEEKLY ||\n interval === TimePolicyInterval.MONTHLY ||\n interval === TimePolicyInterval.YEARLY;\n}\n\nexport function isIntervalForDayOfMonth(\n interval: string,\n) {\n return interval === TimePolicyInterval.MONTHLY ||\n interval === TimePolicyInterval.YEARLY;\n}\n\nexport function isIntervalForDayOfYear(\n interval: string,\n) {\n return interval === TimePolicyInterval.YEARLY;\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { createValidator } from '@validup/zod';\nimport { Container } from 'validup';\nimport { z } from 'zod';\nimport type { TimePolicy } from './types';\nimport { TimePolicyInterval } from './constants';\n\nexport class TimePolicyValidator extends Container<TimePolicy> {\n override initialize() {\n super.initialize();\n\n this.mount('dayOfWeek', createValidator(\n z.number()\n .min(0).max(6)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('dayOfMonth', createValidator(\n z.number()\n .min(1)\n .max(31)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('dayOfYear', createValidator(\n z.number()\n .min(1)\n .max(365)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount('start', createValidator(\n z.date()\n .or(z.iso.datetime())\n .or(z.iso.time())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n this.mount('end', createValidator(\n z.date()\n .or(z.iso.datetime())\n .or(z.iso.time())\n .or(z.number())\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ));\n\n this.mount(\n 'interval',\n createValidator(\n z.enum(TimePolicyInterval)\n .or(z.null())\n .or(z.undefined())\n .optional(),\n ),\n );\n\n this.mount(\n 'invert',\n createValidator(\n z.boolean()\n .or(z.undefined())\n .or(z.null())\n .optional(),\n ),\n );\n }\n}\n","/*\n * Copyright (c) 2024-2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { IPolicyEvaluator, PolicyEvaluationContext, PolicyEvaluationResult } from '../../evaluation';\nimport { maybeInvertPolicyOutcome } from '../../helpers';\nimport { BuiltInPolicyType } from '../constants';\nimport { isIntervalForDayOfMonth, isIntervalForDayOfWeek, isIntervalForDayOfYear } from './helpers';\nimport { TimePolicyValidator } from './validator';\n\nconst timeRegex = /^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$/;\n\nfunction normalizeDate(input: Date, dateRef?: Date) {\n const date = dateRef ? new Date(dateRef) : new Date();\n date.setHours(input.getHours(), input.getMinutes());\n\n return date;\n}\n\nfunction toDate(\n input: Date | string | number,\n dateRef?: Date,\n) : Date {\n if (typeof input === 'string') {\n if (timeRegex.test(input)) {\n const parts = input.split(':');\n\n const startHours = Number(parts[0]);\n const startMinutes = Number(parts[1]);\n const startSeconds = parts[2] !== undefined ? Number(parts[2]) : 0;\n\n if (\n Number.isFinite(startHours) &&\n Number.isFinite(startMinutes) &&\n Number.isFinite(startSeconds)\n ) {\n const date = dateRef ? new Date(dateRef) : new Date();\n date.setHours(startHours, startMinutes, startSeconds, 0);\n\n return date;\n }\n }\n\n return new Date(input);\n }\n\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n return input;\n}\n\nexport class TimePolicyEvaluator implements IPolicyEvaluator {\n protected validator : TimePolicyValidator;\n\n constructor() {\n this.validator = new TimePolicyValidator();\n }\n\n async evaluate(value: Record<string, any>, ctx: PolicyEvaluationContext): Promise<PolicyEvaluationResult> {\n // todo: catch errors + transform to issue(s)\n const policy = await this.validator.run(value);\n\n let now : Date;\n\n if (ctx.data.has(BuiltInPolicyType.TIME)) {\n if (ctx.data.isValidated(BuiltInPolicyType.TIME)) {\n now = ctx.data.get<Date>(BuiltInPolicyType.TIME);\n } else {\n // todo: run validator on attributes (isObject ...)\n now = toDate(ctx.data.get(BuiltInPolicyType.TIME));\n\n ctx.data.set(BuiltInPolicyType.TIME, now);\n ctx.data.setValidated(BuiltInPolicyType.TIME);\n }\n } else {\n now = new Date();\n }\n\n if (policy.start) {\n const start = normalizeDate(toDate(policy.start, now), now);\n if (now < start) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.end) {\n const end = normalizeDate(toDate(policy.end, now), now);\n if (now > end) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (policy.interval) {\n if (\n isIntervalForDayOfWeek(policy.interval) &&\n policy.dayOfWeek\n ) {\n if (now.getDay() !== policy.dayOfWeek) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (\n isIntervalForDayOfMonth(policy.interval) &&\n policy.dayOfMonth\n ) {\n if (now.getDate() !== policy.dayOfMonth) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n\n if (\n isIntervalForDayOfYear(policy.interval) &&\n policy.dayOfYear\n ) {\n const start = new Date(now.getFullYear(), 0, 0);\n const diff = (now.getTime() - start.getTime()) +\n ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);\n\n const oneDay = 1000 * 60 * 60 * 24;\n const dayOfYear = Math.floor(diff / oneDay);\n\n if (dayOfYear !== policy.dayOfYear) {\n return { success: maybeInvertPolicyOutcome(false, policy.invert) };\n }\n }\n }\n\n return { success: maybeInvertPolicyOutcome(true, policy.invert) };\n }\n}\n","/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { PolicyWithType } from '../types';\nimport type { BuiltInPolicyTypeMap } from './types';\n\nexport function definePolicyWithType<\n K extends keyof BuiltInPolicyTypeMap,\n D extends BuiltInPolicyTypeMap<any>[K],\n>(\n type: K,\n data: D,\n) : PolicyWithType<D, K> {\n return {\n ...data,\n type,\n };\n}\n","/*\n * Copyright (c) 2026-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport {\n AttributeNamesPolicyEvaluator,\n AttributesPolicyEvaluator,\n BuiltInPolicyType,\n CompositePolicyEvaluator,\n DatePolicyEvaluator,\n IdentityPolicyEvaluator,\n PermissionBindingPolicyEvaluator,\n RealmMatchPolicyEvaluator,\n TimePolicyEvaluator,\n} from './built-in';\n\nexport const PolicyDefaultEvaluators = {\n [BuiltInPolicyType.COMPOSITE]: new CompositePolicyEvaluator(),\n [BuiltInPolicyType.ATTRIBUTES]: new AttributesPolicyEvaluator(),\n [BuiltInPolicyType.ATTRIBUTE_NAMES]: new AttributeNamesPolicyEvaluator(),\n [BuiltInPolicyType.DATE]: new DatePolicyEvaluator(),\n [BuiltInPolicyType.IDENTITY]: new IdentityPolicyEvaluator(),\n [BuiltInPolicyType.PERMISSION_BINDING]: new PermissionBindingPolicyEvaluator(),\n [BuiltInPolicyType.REALM_MATCH]: new RealmMatchPolicyEvaluator(),\n [BuiltInPolicyType.TIME]: new TimePolicyEvaluator(),\n} as const;\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { BuiltInPolicyType } from './built-in/constants';\nimport type { IdentityPolicyData } from './built-in/identity/types';\nimport { PolicyData } from './data';\n\n/**\n * Typed seed for a permission evaluation's {@link PolicyData} bag.\n *\n * The well-known context keys are value-typed, so construction is discoverable and a\n * wrong-typed value is a compile error. The trailing index signature keeps the bag **open** —\n * a third-party evaluator may supply its own key without any change to this published type\n * (the `access` evaluator set is deliberately extensible).\n */\nexport interface PolicyInput {\n [BuiltInPolicyType.IDENTITY]?: IdentityPolicyData;\n [BuiltInPolicyType.ATTRIBUTES]?: Record<string, any>;\n [BuiltInPolicyType.REALM_MATCH]?: string | string[] | null;\n [key: string]: any;\n}\n\n/**\n * Build a {@link PolicyData} bag from a typed {@link PolicyInput} seed. Well-known keys\n * (identity / attributes / realmMatch) are type-checked; unknown keys are accepted as-is.\n *\n * Prefer this over `new PolicyData({ ... })` at construction sites so the key vocabulary and\n * per-key value types live in one place.\n */\nexport function definePolicyData(input: PolicyInput = {}): PolicyData {\n return new PolicyData(input);\n}\n","/*\n * Copyright (c) 2021-2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ICondition } from '@rapiq/core';\nimport { or } from '@rapiq/core';\nimport { ErrorCode } from '@authup/errors';\nimport type { Issue } from 'validup';\nimport { defineIssueItem } from 'validup';\nimport { DecisionStrategy } from '@authup/kit';\nimport type { BasePolicy, CompositePolicy, IPolicyEngine } from '../../policy';\nimport {\n BuiltInPolicyType,\n PolicyData,\n PolicyDefaultEvaluators,\n PolicyEngine,\n definePolicyEvaluationContext,\n definePolicyIssueGroup,\n} from '../../policy';\nimport { PermissionError } from '../error';\nimport type { IPermissionProvider } from '../provider';\n\nimport type { PermissionPolicyBindingAggregated } from '../types.ts';\nimport type {\n IPermissionEvaluator,\n PermissionCompileContext,\n PermissionCompileResult,\n PermissionEvaluationContext,\n PermissionEvaluatorOptions,\n} from './types.ts';\n\nexport class PermissionEvaluator implements IPermissionEvaluator {\n protected provider : IPermissionProvider;\n\n protected policyEngine : IPolicyEngine;\n\n protected clientId?: string | null;\n\n protected realmId?: string | null;\n\n // ----------------------------------------------\n\n constructor(options: PermissionEvaluatorOptions) {\n this.provider = options.provider;\n\n this.clientId = options.clientId || null;\n this.realmId = options.realmId || null;\n\n if (options.policyEngine) {\n this.policyEngine = options.policyEngine;\n } else {\n this.policyEngine = new PolicyEngine(PolicyDefaultEvaluators);\n }\n }\n\n // ----------------------------------------------\n\n protected async findOne(\n input: string,\n overrides: {\n realmId?: string | null,\n clientId?: string | null\n } = {},\n ) : Promise<PermissionPolicyBindingAggregated | null> {\n return this.provider.findOne({\n name: input,\n clientId: overrides.clientId ?? this.clientId,\n realmId: overrides.realmId ?? this.realmId,\n });\n }\n\n // ----------------------------------------------\n\n async evaluate(ctx: PermissionEvaluationContext) : Promise<void> {\n if (!Array.isArray(ctx.name)) {\n await this.evaluate({\n ...ctx,\n name: [ctx.name],\n });\n return;\n }\n\n const { options = {} } = ctx;\n\n const decisionStrategy = options.decisionStrategy ??\n DecisionStrategy.UNANIMOUS;\n\n const issues : Issue[] = [];\n\n let count = 0;\n\n const dataBase = ctx.data || new PolicyData();\n\n for (const name of ctx.name) {\n const binding = await this.findOne(name, {\n realmId: ctx.realmId,\n clientId: ctx.clientId,\n });\n if (!binding) {\n issues.push(defineIssueItem({\n code: ErrorCode.PERMISSION_NOT_FOUND,\n message: `The ${name} permission could not be resolved`,\n path: [name],\n }));\n\n if (decisionStrategy === DecisionStrategy.UNANIMOUS) {\n const error = PermissionError.evaluationFailed(ctx.name);\n error.addIssues(issues);\n throw error;\n }\n\n continue;\n }\n\n // The actor's grants for this permission form a disjunction: a single policy-free\n // grant is unrestricted, otherwise the permission passes iff ANY grant's policy\n // passes (AFFIRMATIVE). Each grant's policy already carries its own decisionStrategy\n // (a composite for multi-policy Layer-1 bindings, the raw policy for single).\n const grantPolicies = binding.grants\n .map((grant) => grant.policy)\n .filter((grantPolicy): grantPolicy is BasePolicy => !!grantPolicy);\n\n if (grantPolicies.length < binding.grants.length) {\n // some grant is policy-free => unrestricted\n if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return;\n }\n\n count++;\n\n continue;\n }\n\n const data = dataBase.clone();\n data.set(BuiltInPolicyType.PERMISSION_BINDING, binding);\n\n const compositePolicy : CompositePolicy = {\n type: BuiltInPolicyType.COMPOSITE,\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n children: grantPolicies,\n };\n\n const evaluationResult = await this.policyEngine.evaluate(\n compositePolicy,\n definePolicyEvaluationContext({\n include: options.policiesIncluded,\n exclude: options.policiesExcluded,\n data,\n }),\n );\n\n // A pending evaluation (missing data keys) is settled by the caller's\n // phase: the full evaluate denies (fail-closed default), the pre-gate\n // permits — the enriched-bag evaluate is the backstop.\n const passed = evaluationResult.success || (\n options.pendingPolicies === 'permit' &&\n !!evaluationResult.pending\n );\n\n if (passed) {\n if (decisionStrategy === DecisionStrategy.AFFIRMATIVE) {\n return;\n }\n\n count++;\n } else {\n issues.push(definePolicyIssueGroup({\n code: ErrorCode.PERMISSION_EVALUATION_FAILED,\n issues: evaluationResult.issues || [],\n message: `The ${binding.permission.name} permissions policy evaluation failed`,\n path: [binding.permission.name],\n }));\n\n if (decisionStrategy === DecisionStrategy.UNANIMOUS) {\n const error = PermissionError.evaluationFailed(binding.permission.name);\n error.addIssues(issues);\n throw error;\n }\n\n count--;\n }\n }\n\n if (count > 0) {\n return;\n }\n\n if (issues.length === 0) {\n throw PermissionError.deniedAll(ctx.name);\n } else {\n const error = PermissionError.evaluationFailed(ctx.name);\n error.addIssues(issues);\n throw error;\n }\n }\n\n async evaluateOneOf(ctx: PermissionEvaluationContext) : Promise<void> {\n return this.evaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n },\n });\n }\n\n // ----------------------------------------------\n\n async preEvaluate(ctx: PermissionEvaluationContext) : Promise<void> {\n // The pre-gate is DERIVED from data availability (issue #3286): policies whose\n // required data keys are absent from the bag stay pending and are permitted —\n // only a tree that settles false with the current bag denies. This replaces the\n // former hand-maintained type exclusion list (ATTRIBUTES / ATTRIBUTE_NAMES /\n // REALM_MATCH), whose mask-to-true encoding broke under `invert`.\n return this.evaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n pendingPolicies: 'permit',\n },\n });\n }\n\n async preEvaluateOneOf(ctx: PermissionEvaluationContext) : Promise<void> {\n return this.preEvaluate({\n ...ctx,\n options: {\n ...(ctx.options || {}),\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n },\n });\n }\n\n // ----------------------------------------------\n\n /**\n * Compile the permission's policy trees against the knowns bag into a\n * {@link PermissionCompileResult} — the query-build counterpart of\n * {@link evaluate} (issue #3286 phase 3). Runs the SAME evaluation walk with\n * `withConditions` enabled: policies that settle with the knowns settle here,\n * pending subtrees contribute their exact condition form. Multiple names are\n * a disjunction (any-of), so a single non-expressible name degrades the whole\n * compilation to `post` — pushing only some disjuncts would wrongly exclude\n * rows another name would admit.\n */\n async compile(ctx: PermissionCompileContext) : Promise<PermissionCompileResult> {\n const names = Array.isArray(ctx.name) ? ctx.name : [ctx.name];\n\n const dataBase = ctx.data || new PolicyData();\n\n const conditions : ICondition[] = [];\n let post = false;\n\n for (const name of names) {\n const binding = await this.findOne(name, {\n realmId: ctx.realmId,\n clientId: ctx.clientId,\n });\n if (!binding) {\n // unresolvable permission — a settled-false disjunct, drops out\n continue;\n }\n\n const grantPolicies = binding.grants\n .map((grant) => grant.policy)\n .filter((grantPolicy): grantPolicy is BasePolicy => !!grantPolicy);\n\n if (grantPolicies.length < binding.grants.length) {\n // some grant is policy-free => unrestricted\n return { verdict: 'allow' };\n }\n\n const data = dataBase.clone();\n data.set(BuiltInPolicyType.PERMISSION_BINDING, binding);\n\n const compositePolicy : CompositePolicy = {\n type: BuiltInPolicyType.COMPOSITE,\n decisionStrategy: DecisionStrategy.AFFIRMATIVE,\n children: grantPolicies,\n };\n\n const evaluationResult = await this.policyEngine.evaluate(\n compositePolicy,\n definePolicyEvaluationContext({\n data,\n withConditions: true,\n }),\n );\n\n if (evaluationResult.success) {\n return { verdict: 'allow' };\n }\n\n if (evaluationResult.pending) {\n if (evaluationResult.condition) {\n conditions.push(evaluationResult.condition);\n } else {\n post = true;\n }\n }\n // settled false — the disjunct drops out\n }\n\n if (post) {\n return { verdict: 'post' };\n }\n\n if (conditions.length === 0) {\n return { verdict: 'deny' };\n }\n\n if (conditions.length === 1) {\n const [condition] = conditions;\n return { verdict: 'conditional', condition: condition! };\n }\n\n return { verdict: 'conditional', condition: or(...conditions) };\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,4BAA4B,OAAO,IAAI,gCAAgC;AAEpF,IAAa,kBAAb,MAAa,wBAAwB,YAAY;CAC7C,YAAY,UAA8B,CAAC,GAAG;EAC1C,MAAM;GACF,GAAG;GACH,SAAS,QA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