@mayurajs/authz-cedar 0.0.0-stage → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Mayura
2
+ Copyright 2026 The Mayura Authors
3
+
4
+ This product includes software developed by the Mayura contributors.
5
+
6
+ Third-party dependencies retain their own copyright and license terms. Exact
7
+ resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
8
+ artifact and dependency qualification procedures.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/authz-cedar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Local native Cedar authorization through Mayura's core policy, enforcement and audit contract. The host supplies
4
+ an initialized evaluator; this extension has no SDK/WASM loader, environment credentials or infrastructure dependency.
5
+
6
+ See [the integration guide](../../docs/integrations/authz-cedar.md) for setup, scoped identity mapping, policy/schema
7
+ configuration, trusted attributes, bounds, server wiring and lifecycle ownership.
8
+
9
+ ## Native engine bridge
10
+
11
+ Install and pin `@cedar-policy/cedar-wasm` in the host application and use its runtime-appropriate entry point.
12
+ For example, after initializing that module, wrap its exported `isAuthorized` function:
13
+
14
+ ```ts
15
+ import type { CedarAuthorizationEvaluator } from '@mayurajs/authz-cedar';
16
+ // isAuthorized is the initialized native cedar-wasm export owned by the host.
17
+ const evaluate: CedarAuthorizationEvaluator = (call, { signal }) => {
18
+ if (signal.aborted) throw new Error('Cancelled');
19
+ // JSON conversion supplies native mutable FFI values from the adapter's bounded readonly API.
20
+ return isAuthorized(JSON.parse(JSON.stringify(call)));
21
+ };
22
+ ```
23
+
24
+ Preserve the complete native result. Do not replace diagnostics with a boolean or omit errors accompanying an allow.
25
+ The adapter supports the stateless native FFI, named static policies, Cedar schema source and literal attributes;
26
+ entity hierarchies, extension values, template links and Amazon Verified Permissions are not included in this slice.
27
+ Use a host worker when hard CPU/memory termination is needed; synchronous WASM cannot be preempted by JS timers.
28
+
29
+ ## Primary references
30
+
31
+ Reviewed 2026-10-20; no real engine invocation or validation has been performed in this development slice.
32
+
33
+ - [Official Cedar stateless authorization FFI](https://github.com/cedar-policy/cedar/blob/main/cedar-policy/src/ffi/is_authorized.rs)
34
+ - [Official policy set, schema and entity FFI representations](https://github.com/cedar-policy/cedar/blob/main/cedar-policy/src/ffi/utils.rs)
35
+ - [Official Cedar WASM export](https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/src/lib.rs)
36
+ - [Cedar authorization semantics and error handling](https://docs.cedarpolicy.com/auth/authorization.html)
37
+
38
+ Offline regression tests are authored. Tests and all validation remain deferred.
@@ -0,0 +1,87 @@
1
+ import { type AuthorizationPolicy, type AuthorizationRequest, type AuthorizationResourceKind, type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';
2
+ /** Native Cedar UID object. Identifiers are never interpolated into policy source. */
3
+ export interface CedarEntityUid {
4
+ readonly type: string;
5
+ readonly id: string;
6
+ }
7
+ /** Bounded Cedar literal subset: no null, floating point, entity escapes or extension constructors. */
8
+ export type CedarAttributeValue = string | boolean | number | readonly CedarAttributeValue[] | {
9
+ readonly [key: string]: CedarAttributeValue;
10
+ };
11
+ export interface CedarAuthorizationAttributes {
12
+ readonly principal: Readonly<Record<string, CedarAttributeValue>>;
13
+ readonly resource: Readonly<Record<string, CedarAttributeValue>>;
14
+ readonly context: Readonly<Record<string, CedarAttributeValue>>;
15
+ }
16
+ export interface CedarAuthorizationMapping {
17
+ readonly kind: AuthorizationResourceKind;
18
+ readonly action: string;
19
+ readonly resourceType: string;
20
+ readonly actionId: string;
21
+ }
22
+ /** Native stateless cedar-wasm isAuthorized input, restricted to static policies and literal attributes. */
23
+ export interface CedarAuthorizationCall {
24
+ readonly principal: CedarEntityUid;
25
+ readonly action: CedarEntityUid;
26
+ readonly resource: CedarEntityUid;
27
+ readonly context: Readonly<Record<string, CedarAttributeValue>>;
28
+ readonly schema: string;
29
+ readonly validateRequest: true;
30
+ readonly policies: {
31
+ readonly staticPolicies: Readonly<Record<string, string>>;
32
+ };
33
+ readonly entities: readonly {
34
+ readonly uid: CedarEntityUid;
35
+ readonly attrs: Readonly<Record<string, CedarAttributeValue>>;
36
+ readonly parents: readonly CedarEntityUid[];
37
+ }[];
38
+ }
39
+ /** Inject native isAuthorized, or a worker wrapper preserving its complete success/failure diagnostics. */
40
+ export type CedarAuthorizationEvaluator = (call: CedarAuthorizationCall, context: {
41
+ readonly signal: AbortSignal;
42
+ }) => unknown | Promise<unknown>;
43
+ export interface CedarAuthorizationPolicyOptions {
44
+ /** Host-pinned policy/data revision and exact evaluator implementation version. Both enter the fingerprint. */
45
+ readonly version: string;
46
+ readonly engineVersion: string;
47
+ readonly namespace: string;
48
+ readonly principalType: string;
49
+ readonly actionType: string;
50
+ readonly mappings: readonly CedarAuthorizationMapping[];
51
+ /** Named native static policy sources, and a native Cedar schema source. Neither is caller-controlled. */
52
+ readonly policies: Readonly<Record<string, string>>;
53
+ readonly schema: string;
54
+ readonly evaluate: CedarAuthorizationEvaluator;
55
+ /** Trusted, read-only attribute source. No entity graph, request identity or policy overrides are accepted. */
56
+ readonly attributes?: (request: AuthorizationRequest, context: {
57
+ readonly signal: AbortSignal;
58
+ }) => CedarAuthorizationAttributes | Promise<CedarAuthorizationAttributes>;
59
+ /** authz:cedar admits host callbacks; core enforcement/audit require their own grants. */
60
+ readonly permissions?: Permissions;
61
+ /** Whole attribute/evaluation deadline, default 1,000 ms; 1–30,000 ms. Synchronous engines cannot be preempted. */
62
+ readonly timeoutMs?: number;
63
+ /** Unsettled operations, default 32; 1–256. Ignored cancellation retains the slot until settlement. */
64
+ readonly maxConcurrent?: number;
65
+ }
66
+ export interface CedarAuthorizationPolicy extends AuthorizationPolicy {
67
+ /** Pure identity helper for provisioning/debugging. Unmapped requests return null; invalid scope throws. */
68
+ identities(request: AuthorizationRequest): {
69
+ readonly principal: CedarEntityUid;
70
+ readonly action: CedarEntityUid;
71
+ readonly resource: CedarEntityUid;
72
+ } | null;
73
+ /** Cancels checks and refuses new work; never disposes the caller-owned evaluator. */
74
+ close(): void;
75
+ }
76
+ export interface CedarAuthorizerOptions extends CedarAuthorizationPolicyOptions {
77
+ readonly audit?: AuthorizerOptions['audit'];
78
+ readonly limits?: AuthorizerOptions['limits'];
79
+ }
80
+ /**
81
+ * Scoped, read-only Cedar policy through the core authorization contract. Native parse/evaluation errors deny,
82
+ * including error diagnostics accompanying an allow. No evaluator, credential, policy or schema is discovered.
83
+ */
84
+ export declare function createCedarAuthorizationPolicy(options: CedarAuthorizationPolicyOptions): CedarAuthorizationPolicy;
85
+ /** Core enforcement and audit own the single final receipt; evaluator lifetime remains with its host. */
86
+ export declare function createCedarAuthorizer(options: CedarAuthorizerOptions): Authorizer;
87
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACqD,KAAK,mBAAmB,EAAE,KAAK,oBAAoB,EAC7G,KAAK,yBAAyB,EAAE,KAAK,UAAU,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,QAAQ,CAAC;AAG5G,sFAAsF;AACtF,MAAM,WAAW,cAAc;IAAG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAC9E,uGAAuG;AACvG,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,mBAAmB,EAAE,GAAG;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAAA;CAAE,CAAC;AAC/I,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,CAAC,SAAS,EAAE,QA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,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAA;KAAE,GAAG,IAAI,CAAC;IAC7J,sFAAsF;IACtF,KAAK,IAAI,IAAI,CAAC;CACf;AACD,MAAM,WAAW,sBAAuB,SAAQ,+BAA+B;IAC7E,QAAQ,CAAC,KAAK,CAAC,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,iBAAiB,CAAC,QAAQ,CAAC,CAAC;CAC5F;AA+BD;;;GAGG;AACH,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,+BAA+B,GAAG,wBAAwB,CA8FjH;AACD,yGAAyG;AACzG,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,UAAU,CAOjF"}
package/dist/index.js ADDED
@@ -0,0 +1,223 @@
1
+ import { AUTHORIZATION_RESOURCE_KINDS, authorizationRequest, createAuthorizer, freezeJson, jsonValue, MayuraError } from 'mayura';
2
+ import { sha256Hex, utf8ByteLength } from 'mayura/core/host';
3
+ const identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
4
+ const entityType = /^[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*$/u;
5
+ const actionName = /^[a-z][a-z0-9_.:-]{0,127}$/u;
6
+ const bindingKey = (kind, action) => JSON.stringify([kind, action]);
7
+ function invalid() { throw new MayuraError('INVALID_CONFIG', 'Cedar authorization requires pinned policy/schema/engine revisions, exact scoped mappings and bounded callbacks.'); }
8
+ function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
9
+ function bound(value, fallback, max) {
10
+ const result = value ?? fallback;
11
+ if (!Number.isSafeInteger(result) || result < 1 || result > max)
12
+ return invalid();
13
+ return result;
14
+ }
15
+ function canonical(value) {
16
+ if (value === null || typeof value !== 'object')
17
+ return JSON.stringify(value);
18
+ if (Array.isArray(value))
19
+ return `[${value.map(canonical).join(',')}]`;
20
+ const data = value;
21
+ return `{${Object.keys(data).sort().map(key => `${JSON.stringify(key)}:${canonical(data[key])}`).join(',')}}`;
22
+ }
23
+ function capture(raw) {
24
+ const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });
25
+ if (!record(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject')
26
+ throw new MayuraError('INVALID_INPUT', 'Invalid scoped authorization request.');
27
+ const data = snapshot;
28
+ return authorizationRequest(data.subject, data.action, data.resource);
29
+ }
30
+ /** Literal-only attributes deliberately exclude implicit/explicit entity references and extension constructors. */
31
+ function attributes(raw) {
32
+ const data = jsonValue(raw, { maxBytes: 16_384, maxDepth: 8, maxNodes: 2048 });
33
+ const literal = (value) => typeof value === 'string' || typeof value === 'boolean'
34
+ || (typeof value === 'number' && Number.isSafeInteger(value)) || (Array.isArray(value) ? value.every(literal)
35
+ : record(value) && Object.entries(value).every(([key, entry]) => /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(key) && literal(entry)));
36
+ if (!record(data) || Object.keys(data).sort().join(',') !== 'context,principal,resource'
37
+ || !['principal', 'resource', 'context'].every(name => record(data[name]) && literal(data[name])))
38
+ throw new Error('Invalid trusted Cedar attributes.');
39
+ return freezeJson(data);
40
+ }
41
+ /**
42
+ * Scoped, read-only Cedar policy through the core authorization contract. Native parse/evaluation errors deny,
43
+ * including error diagnostics accompanying an allow. No evaluator, credential, policy or schema is discovered.
44
+ */
45
+ export function createCedarAuthorizationPolicy(options) {
46
+ let version;
47
+ let namespace;
48
+ let principalType;
49
+ let actionType;
50
+ let schema;
51
+ let policies;
52
+ let mappings;
53
+ let evaluate;
54
+ let load;
55
+ let admitted;
56
+ let timeoutMs;
57
+ let maxConcurrent;
58
+ try {
59
+ if (!options || [options.version, options.engineVersion, options.namespace].some(value => typeof value !== 'string' || !identifier.test(value))
60
+ || [options.principalType, options.actionType].some(value => typeof value !== 'string' || value.length > 128 || !entityType.test(value))
61
+ || options.principalType === options.actionType || typeof options.evaluate !== 'function'
62
+ || (options.attributes !== undefined && typeof options.attributes !== 'function')
63
+ || typeof options.schema !== 'string' || !options.schema.trim() || utf8ByteLength(options.schema) > 65_536)
64
+ return invalid();
65
+ const sources = jsonValue(options.policies, { maxBytes: 262_144, maxDepth: 1, maxNodes: 257 });
66
+ if (!record(sources) || !Object.keys(sources).length || Object.keys(sources).length > 256
67
+ || !Object.entries(sources).every(([id, source]) => identifier.test(id) && typeof source === 'string' && !!source.trim()))
68
+ return invalid();
69
+ policies = freezeJson(sources);
70
+ const captured = jsonValue(options.mappings, { maxBytes: 65_536, maxDepth: 2, maxNodes: 2561 });
71
+ if (!Array.isArray(captured) || !captured.length || captured.length > 512)
72
+ return invalid();
73
+ const mapped = new Map();
74
+ for (const raw of captured) {
75
+ if (!record(raw) || Object.keys(raw).sort().join(',') !== 'action,actionId,kind,resourceType'
76
+ || !AUTHORIZATION_RESOURCE_KINDS.includes(raw['kind'])
77
+ || typeof raw['action'] !== 'string' || !actionName.test(raw['action']) || typeof raw['actionId'] !== 'string' || !identifier.test(raw['actionId'])
78
+ || typeof raw['resourceType'] !== 'string' || raw['resourceType'].length > 128 || !entityType.test(raw['resourceType'])
79
+ || raw['resourceType'] === options.actionType)
80
+ return invalid();
81
+ const binding = freezeJson(raw);
82
+ const key = bindingKey(binding.kind, binding.action);
83
+ if (mapped.has(key))
84
+ return invalid();
85
+ mapped.set(key, binding);
86
+ }
87
+ const grants = jsonValue(options.permissions?.allow ?? [], { maxBytes: 1_048_576, maxDepth: 1, maxNodes: 4097 });
88
+ if (!Array.isArray(grants) || grants.length > 4096 || grants.some(grant => typeof grant !== 'string' || !grant.length || grant.length > 256))
89
+ return invalid();
90
+ admitted = grants.includes('authz:cedar');
91
+ namespace = options.namespace;
92
+ principalType = options.principalType;
93
+ actionType = options.actionType;
94
+ schema = options.schema;
95
+ mappings = mapped;
96
+ evaluate = options.evaluate;
97
+ load = options.attributes;
98
+ timeoutMs = bound(options.timeoutMs, 1000, 30_000);
99
+ maxConcurrent = bound(options.maxConcurrent, 32, 256);
100
+ version = `cedar:${sha256Hex(canonical({ protocol: 'mayura.cedar.v1', revision: options.version, engineVersion: options.engineVersion,
101
+ namespace, principalType, actionType, schema, policies, mappings: [...mapped.values()].sort((a, b) => bindingKey(a.kind, a.action) < bindingKey(b.kind, b.action) ? -1 : 1) }))}`;
102
+ }
103
+ catch {
104
+ return invalid();
105
+ }
106
+ let closed = false;
107
+ const active = new Set();
108
+ const deny = (reason) => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });
109
+ const identities = raw => {
110
+ const request = capture(raw);
111
+ const scope = request.subject;
112
+ if (scope.principalId !== request.resource.scope.principalId || scope.projectId !== request.resource.scope.projectId)
113
+ throw new MayuraError('INVALID_INPUT', 'The authorization resource does not belong to the verified scope.');
114
+ const mapping = mappings.get(bindingKey(request.resource.kind, request.action));
115
+ if (!mapping)
116
+ return null;
117
+ const identity = (domain, extra) => sha256Hex(JSON.stringify([domain, namespace, scope.projectId, scope.principalId, ...extra]));
118
+ return Object.freeze({ principal: Object.freeze({ type: principalType, id: identity('mayura.cedar.subject.v1', []) }),
119
+ action: Object.freeze({ type: actionType, id: mapping.actionId }),
120
+ resource: Object.freeze({ type: mapping.resourceType, id: identity('mayura.cedar.resource.v1', [request.resource.kind, request.resource.id]) }) });
121
+ };
122
+ const normalize = (raw) => {
123
+ const answer = jsonValue(raw, { maxBytes: 16_384, maxDepth: 12, maxNodes: 2048 });
124
+ if (!record(answer) || answer['type'] !== 'success' || Object.keys(answer).sort().join(',') !== 'response,type,warnings'
125
+ || !Array.isArray(answer['warnings']) || !record(answer['response']))
126
+ return deny('unavailable');
127
+ const response = answer['response'];
128
+ const diagnostics = response['diagnostics'];
129
+ if (Object.keys(response).sort().join(',') !== 'decision,diagnostics' || !record(diagnostics)
130
+ || Object.keys(diagnostics).sort().join(',') !== 'errors,reason' || !Array.isArray(diagnostics['errors']) || diagnostics['errors'].length
131
+ || !Array.isArray(diagnostics['reason']) || diagnostics['reason'].some(id => typeof id !== 'string' || !Object.hasOwn(policies, id))
132
+ || new Set(diagnostics['reason']).size !== diagnostics['reason'].length)
133
+ return deny('unavailable');
134
+ if (response['decision'] === 'deny')
135
+ return deny(diagnostics['reason'].length ? 'explicit_deny' : 'no_match');
136
+ if (response['decision'] !== 'allow' || !diagnostics['reason'].length)
137
+ return deny('unavailable');
138
+ return Object.freeze({ effect: 'allow', reason: 'allowed', policyVersion: version, ruleId: diagnostics['reason'].length === 1 ? diagnostics['reason'][0] : null });
139
+ };
140
+ const authorize = async (raw, context) => {
141
+ let request;
142
+ try {
143
+ request = capture(raw);
144
+ if (!(context?.signal instanceof AbortSignal))
145
+ return deny('invalid_request');
146
+ }
147
+ catch {
148
+ return deny('invalid_request');
149
+ }
150
+ if (closed || context.signal.aborted)
151
+ return deny('cancelled');
152
+ if (request.subject.principalId !== request.resource.scope.principalId || request.subject.projectId !== request.resource.scope.projectId)
153
+ return deny('scope_mismatch');
154
+ if (!admitted)
155
+ return deny('permission_denied');
156
+ const ids = identities(request);
157
+ if (!ids)
158
+ return deny('no_match');
159
+ if (active.size >= maxConcurrent)
160
+ return deny('limit_exceeded');
161
+ const control = new AbortController();
162
+ active.add(control);
163
+ const deadline = Date.now() + timeoutMs;
164
+ let expired = false;
165
+ return new Promise(resolve => {
166
+ let settled = false;
167
+ let timer;
168
+ const finish = (decision) => {
169
+ if (settled)
170
+ return;
171
+ settled = true;
172
+ if (timer !== undefined)
173
+ clearTimeout(timer);
174
+ context.signal.removeEventListener('abort', abort);
175
+ control.signal.removeEventListener('abort', stopped);
176
+ resolve(decision);
177
+ };
178
+ const abort = () => control.abort();
179
+ const stopped = () => finish(deny(expired ? 'unavailable' : 'cancelled'));
180
+ const stoppedOrExpired = () => { if (!control.signal.aborted && Date.now() >= deadline) {
181
+ expired = true;
182
+ control.abort();
183
+ } return control.signal.aborted || closed; };
184
+ control.signal.addEventListener('abort', stopped, { once: true });
185
+ context.signal.addEventListener('abort', abort, { once: true });
186
+ timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs);
187
+ if (context.signal.aborted || closed)
188
+ control.abort();
189
+ // Capacity remains owned by this task even if its observable decision has already timed out.
190
+ void Promise.resolve().then(async () => {
191
+ if (stoppedOrExpired())
192
+ return deny(expired ? 'unavailable' : 'cancelled');
193
+ const data = attributes(load ? await load(request, { signal: control.signal }) : { principal: {}, resource: {}, context: {} });
194
+ if (stoppedOrExpired())
195
+ return deny(expired ? 'unavailable' : 'cancelled');
196
+ const call = { ...ids, context: data.context, schema, validateRequest: true, policies: { staticPolicies: policies },
197
+ entities: [{ uid: ids.principal, attrs: data.principal, parents: [] }, { uid: ids.resource, attrs: data.resource, parents: [] }] };
198
+ // A fresh mutable copy supports wasm-bindgen conversion without exposing the pinned configuration.
199
+ const result = await evaluate(jsonValue(call, { maxBytes: 360_448, maxDepth: 12, maxNodes: 4096 }), { signal: control.signal });
200
+ if (stoppedOrExpired())
201
+ return deny(expired ? 'unavailable' : 'cancelled');
202
+ return normalize(result);
203
+ }).then(result => { active.delete(control); finish(stoppedOrExpired() ? deny(expired ? 'unavailable' : 'cancelled') : result); }, () => { active.delete(control); stoppedOrExpired(); finish(deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable')); });
204
+ });
205
+ };
206
+ return Object.freeze({ version, identities, authorize, close() { if (closed)
207
+ return; closed = true; for (const control of active)
208
+ control.abort(); } });
209
+ }
210
+ /** Core enforcement and audit own the single final receipt; evaluator lifetime remains with its host. */
211
+ export function createCedarAuthorizer(options) {
212
+ const policy = createCedarAuthorizationPolicy(options);
213
+ try {
214
+ const authorizer = createAuthorizer({ policy, ...(options.permissions === undefined ? {} : { permissions: options.permissions }),
215
+ ...(options.audit === undefined ? {} : { audit: options.audit }), ...(options.limits === undefined ? {} : { limits: options.limits }) });
216
+ return Object.freeze({ ...authorizer, close() { authorizer.close(); policy.close(); } });
217
+ }
218
+ catch (error) {
219
+ policy.close();
220
+ throw error;
221
+ }
222
+ }
223
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAEpB,MAAM,QAAQ,CAAC;AAC5G,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAmD7D,MAAM,UAAU,GAAG,uCAAuC,CAAC;AAC3D,MAAM,UAAU,GAAG,wDAAwD,CAAC;AAC5E,MAAM,UAAU,GAAG,6BAA6B,CAAC;AACjD,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;AACpF,SAAS,OAAO,KAAY,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,kHAAkH,CAAC,CAAC,CAAC,CAAC;AAC1L,SAAS,MAAM,CAAC,KAAc,IAAsC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAClJ,SAAS,KAAK,CAAC,KAAyB,EAAE,QAAgB,EAAE,GAAW;IACrE,MAAM,MAAM,GAAG,KAAK,IAAI,QAAQ,CAAC;IAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,GAAG,GAAG;QAAE,OAAO,OAAO,EAAE,CAAC;IAAC,OAAO,MAAM,CAAC;AACrI,CAAC;AACD,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,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SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;QAC3I,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,KAAK,KAAK,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC3F,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAAC,MAAM,KAAK,CAAC;IAAC,CAAC;AAClD,CAAC","sourcesContent":["import { AUTHORIZATION_RESOURCE_KINDS, authorizationRequest, createAuthorizer, freezeJson, jsonValue, MayuraError,\n type AuthorizationDecision, type AuthorizationDenyReason, type AuthorizationPolicy, type AuthorizationRequest,\n type AuthorizationResourceKind, type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';\nimport { sha256Hex, utf8ByteLength } from 'mayura/core/host';\n\n/** Native Cedar UID object. Identifiers are never interpolated into policy source. */\nexport interface CedarEntityUid { readonly type: string; readonly id: string }\n/** Bounded Cedar literal subset: no null, floating point, entity escapes or extension constructors. */\nexport type CedarAttributeValue = string | boolean | number | readonly CedarAttributeValue[] | { readonly [key: string]: CedarAttributeValue };\nexport interface CedarAuthorizationAttributes {\n readonly principal: Readonly<Record<string, CedarAttributeValue>>;\n readonly resource: Readonly<Record<string, CedarAttributeValue>>;\n readonly context: Readonly<Record<string, CedarAttributeValue>>;\n}\nexport interface CedarAuthorizationMapping {\n readonly kind: AuthorizationResourceKind; readonly action: string;\n readonly resourceType: string; readonly actionId: string;\n}\n/** Native stateless cedar-wasm isAuthorized input, restricted to static policies and literal attributes. */\nexport interface CedarAuthorizationCall {\n readonly principal: CedarEntityUid; readonly action: CedarEntityUid; readonly resource: CedarEntityUid;\n readonly context: Readonly<Record<string, CedarAttributeValue>>;\n readonly schema: string; readonly validateRequest: true;\n readonly policies: { readonly staticPolicies: Readonly<Record<string, string>> };\n readonly entities: readonly { readonly uid: CedarEntityUid; readonly attrs: Readonly<Record<string, CedarAttributeValue>>; readonly parents: readonly CedarEntityUid[] }[];\n}\n/** Inject native isAuthorized, or a worker wrapper preserving its complete success/failure diagnostics. */\nexport type CedarAuthorizationEvaluator = (call: CedarAuthorizationCall, context: { readonly signal: AbortSignal }) => unknown | Promise<unknown>;\nexport interface CedarAuthorizationPolicyOptions {\n /** Host-pinned policy/data revision and exact evaluator implementation version. Both enter the fingerprint. */\n readonly version: string; readonly engineVersion: string;\n readonly namespace: string; readonly principalType: string; readonly actionType: string;\n readonly mappings: readonly CedarAuthorizationMapping[];\n /** Named native static policy sources, and a native Cedar schema source. Neither is caller-controlled. */\n readonly policies: Readonly<Record<string, string>>; readonly schema: string;\n readonly evaluate: CedarAuthorizationEvaluator;\n /** Trusted, read-only attribute source. No entity graph, request identity or policy overrides are accepted. */\n readonly attributes?: (request: AuthorizationRequest, context: { readonly signal: AbortSignal }) => CedarAuthorizationAttributes | Promise<CedarAuthorizationAttributes>;\n /** authz:cedar admits host callbacks; core enforcement/audit require their own grants. */\n readonly permissions?: Permissions;\n /** Whole attribute/evaluation deadline, default 1,000 ms; 1–30,000 ms. Synchronous engines cannot be preempted. */\n readonly timeoutMs?: number;\n /** Unsettled operations, default 32; 1–256. Ignored cancellation retains the slot until settlement. */\n readonly maxConcurrent?: number;\n}\nexport interface CedarAuthorizationPolicy extends AuthorizationPolicy {\n /** Pure identity helper for provisioning/debugging. Unmapped requests return null; invalid scope throws. */\n identities(request: AuthorizationRequest): { readonly principal: CedarEntityUid; readonly action: CedarEntityUid; readonly resource: CedarEntityUid } | null;\n /** Cancels checks and refuses new work; never disposes the caller-owned evaluator. */\n close(): void;\n}\nexport interface CedarAuthorizerOptions extends CedarAuthorizationPolicyOptions {\n readonly audit?: AuthorizerOptions['audit']; readonly limits?: AuthorizerOptions['limits'];\n}\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;\nconst entityType = /^[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*$/u;\nconst actionName = /^[a-z][a-z0-9_.:-]{0,127}$/u;\nconst bindingKey = (kind: string, action: string) => JSON.stringify([kind, action]);\nfunction invalid(): never { throw new MayuraError('INVALID_CONFIG', 'Cedar authorization requires pinned policy/schema/engine revisions, exact scoped mappings and bounded callbacks.'); }\nfunction record(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === 'object' && !Array.isArray(value); }\nfunction bound(value: number | undefined, fallback: number, max: number): number {\n const result = value ?? fallback; if (!Number.isSafeInteger(result) || result < 1 || result > max) return invalid(); return result;\n}\nfunction canonical(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n const data = value as Record<string, unknown>;\n return `{${Object.keys(data).sort().map(key => `${JSON.stringify(key)}:${canonical(data[key])}`).join(',')}}`;\n}\nfunction capture(raw: AuthorizationRequest): AuthorizationRequest {\n const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });\n if (!record(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject') throw new MayuraError('INVALID_INPUT', 'Invalid scoped authorization request.');\n const data = snapshot as unknown as AuthorizationRequest; return authorizationRequest(data.subject, data.action, data.resource);\n}\n/** Literal-only attributes deliberately exclude implicit/explicit entity references and extension constructors. */\nfunction attributes(raw: unknown): CedarAuthorizationAttributes {\n const data = jsonValue(raw, { maxBytes: 16_384, maxDepth: 8, maxNodes: 2048 });\n const literal = (value: unknown): boolean => typeof value === 'string' || typeof value === 'boolean'\n || (typeof value === 'number' && Number.isSafeInteger(value)) || (Array.isArray(value) ? value.every(literal)\n : record(value) && Object.entries(value).every(([key, entry]) => /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(key) && literal(entry)));\n if (!record(data) || Object.keys(data).sort().join(',') !== 'context,principal,resource'\n || !['principal', 'resource', 'context'].every(name => record(data[name]) && literal(data[name]))) throw new Error('Invalid trusted Cedar attributes.');\n return freezeJson(data) as unknown as CedarAuthorizationAttributes;\n}\n/**\n * Scoped, read-only Cedar policy through the core authorization contract. Native parse/evaluation errors deny,\n * including error diagnostics accompanying an allow. No evaluator, credential, policy or schema is discovered.\n */\nexport function createCedarAuthorizationPolicy(options: CedarAuthorizationPolicyOptions): CedarAuthorizationPolicy {\n let version: string; let namespace: string; let principalType: string; let actionType: string; let schema: string;\n let policies: Readonly<Record<string, string>>; let mappings: ReadonlyMap<string, CedarAuthorizationMapping>;\n let evaluate: CedarAuthorizationEvaluator; let load: CedarAuthorizationPolicyOptions['attributes'];\n let admitted: boolean; let timeoutMs: number; let maxConcurrent: number;\n try {\n if (!options || [options.version, options.engineVersion, options.namespace].some(value => typeof value !== 'string' || !identifier.test(value))\n || [options.principalType, options.actionType].some(value => typeof value !== 'string' || value.length > 128 || !entityType.test(value))\n || options.principalType === options.actionType || typeof options.evaluate !== 'function'\n || (options.attributes !== undefined && typeof options.attributes !== 'function')\n || typeof options.schema !== 'string' || !options.schema.trim() || utf8ByteLength(options.schema) > 65_536) return invalid();\n const sources = jsonValue(options.policies, { maxBytes: 262_144, maxDepth: 1, maxNodes: 257 });\n if (!record(sources) || !Object.keys(sources).length || Object.keys(sources).length > 256\n || !Object.entries(sources).every(([id, source]) => identifier.test(id) && typeof source === 'string' && !!source.trim())) return invalid();\n policies = freezeJson(sources) as Readonly<Record<string, string>>;\n const captured = jsonValue(options.mappings, { maxBytes: 65_536, maxDepth: 2, maxNodes: 2561 });\n if (!Array.isArray(captured) || !captured.length || captured.length > 512) return invalid();\n const mapped = new Map<string, CedarAuthorizationMapping>();\n for (const raw of captured) {\n if (!record(raw) || Object.keys(raw).sort().join(',') !== 'action,actionId,kind,resourceType'\n || !AUTHORIZATION_RESOURCE_KINDS.includes(raw['kind'] as AuthorizationResourceKind)\n || typeof raw['action'] !== 'string' || !actionName.test(raw['action']) || typeof raw['actionId'] !== 'string' || !identifier.test(raw['actionId'])\n || typeof raw['resourceType'] !== 'string' || raw['resourceType'].length > 128 || !entityType.test(raw['resourceType'])\n || raw['resourceType'] === options.actionType) return invalid();\n const binding = freezeJson(raw) as unknown as CedarAuthorizationMapping; const key = bindingKey(binding.kind, binding.action);\n if (mapped.has(key)) return invalid(); mapped.set(key, binding);\n }\n const grants = jsonValue(options.permissions?.allow ?? [], { maxBytes: 1_048_576, maxDepth: 1, maxNodes: 4097 });\n if (!Array.isArray(grants) || grants.length > 4096 || grants.some(grant => typeof grant !== 'string' || !grant.length || grant.length > 256)) return invalid();\n admitted = grants.includes('authz:cedar'); namespace = options.namespace; principalType = options.principalType; actionType = options.actionType;\n schema = options.schema; mappings = mapped; evaluate = options.evaluate; load = options.attributes;\n timeoutMs = bound(options.timeoutMs, 1000, 30_000); maxConcurrent = bound(options.maxConcurrent, 32, 256);\n version = `cedar:${sha256Hex(canonical({ protocol: 'mayura.cedar.v1', revision: options.version, engineVersion: options.engineVersion,\n namespace, principalType, actionType, schema, policies, mappings: [...mapped.values()].sort((a, b) => bindingKey(a.kind, a.action) < bindingKey(b.kind, b.action) ? -1 : 1) }))}`;\n } catch { return invalid(); }\n let closed = false; const active = new Set<AbortController>();\n const deny = (reason: AuthorizationDenyReason): AuthorizationDecision => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });\n const identities: CedarAuthorizationPolicy['identities'] = raw => {\n const request = capture(raw); const scope = request.subject;\n if (scope.principalId !== request.resource.scope.principalId || scope.projectId !== request.resource.scope.projectId) throw new MayuraError('INVALID_INPUT', 'The authorization resource does not belong to the verified scope.');\n const mapping = mappings.get(bindingKey(request.resource.kind, request.action)); if (!mapping) return null;\n const identity = (domain: string, extra: readonly string[]) => sha256Hex(JSON.stringify([domain, namespace, scope.projectId, scope.principalId, ...extra]));\n return Object.freeze({ principal: Object.freeze({ type: principalType, id: identity('mayura.cedar.subject.v1', []) }),\n action: Object.freeze({ type: actionType, id: mapping.actionId }),\n resource: Object.freeze({ type: mapping.resourceType, id: identity('mayura.cedar.resource.v1', [request.resource.kind, request.resource.id]) }) });\n };\n const normalize = (raw: unknown): AuthorizationDecision => {\n const answer = jsonValue(raw, { maxBytes: 16_384, maxDepth: 12, maxNodes: 2048 });\n if (!record(answer) || answer['type'] !== 'success' || Object.keys(answer).sort().join(',') !== 'response,type,warnings'\n || !Array.isArray(answer['warnings']) || !record(answer['response'])) return deny('unavailable');\n const response = answer['response']; const diagnostics = response['diagnostics'];\n if (Object.keys(response).sort().join(',') !== 'decision,diagnostics' || !record(diagnostics)\n || Object.keys(diagnostics).sort().join(',') !== 'errors,reason' || !Array.isArray(diagnostics['errors']) || diagnostics['errors'].length\n || !Array.isArray(diagnostics['reason']) || diagnostics['reason'].some(id => typeof id !== 'string' || !Object.hasOwn(policies, id))\n || new Set(diagnostics['reason']).size !== diagnostics['reason'].length) return deny('unavailable');\n if (response['decision'] === 'deny') return deny(diagnostics['reason'].length ? 'explicit_deny' : 'no_match');\n if (response['decision'] !== 'allow' || !diagnostics['reason'].length) return deny('unavailable');\n return Object.freeze({ effect: 'allow', reason: 'allowed', policyVersion: version, ruleId: diagnostics['reason'].length === 1 ? diagnostics['reason'][0] as string : null });\n };\n const authorize: AuthorizationPolicy['authorize'] = async (raw, context) => {\n let request: AuthorizationRequest;\n try { request = capture(raw); if (!(context?.signal instanceof AbortSignal)) return deny('invalid_request'); } catch { return deny('invalid_request'); }\n if (closed || context.signal.aborted) return deny('cancelled');\n if (request.subject.principalId !== request.resource.scope.principalId || request.subject.projectId !== request.resource.scope.projectId) return deny('scope_mismatch');\n if (!admitted) return deny('permission_denied');\n const ids = identities(request); if (!ids) return deny('no_match');\n if (active.size >= maxConcurrent) return deny('limit_exceeded');\n const control = new AbortController(); active.add(control); const deadline = Date.now() + timeoutMs; let expired = false;\n return new Promise<AuthorizationDecision>(resolve => {\n let settled = false; let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = (decision: AuthorizationDecision) => { if (settled) return; settled = true; if (timer !== undefined) clearTimeout(timer);\n context.signal.removeEventListener('abort', abort); control.signal.removeEventListener('abort', stopped); resolve(decision); };\n const abort = () => control.abort();\n const stopped = () => finish(deny(expired ? 'unavailable' : 'cancelled'));\n const stoppedOrExpired = () => { if (!control.signal.aborted && Date.now() >= deadline) { expired = true; control.abort(); } return control.signal.aborted || closed; };\n control.signal.addEventListener('abort', stopped, { once: true }); context.signal.addEventListener('abort', abort, { once: true });\n timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs);\n if (context.signal.aborted || closed) control.abort();\n // Capacity remains owned by this task even if its observable decision has already timed out.\n void Promise.resolve().then(async () => {\n if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');\n const data = attributes(load ? await load(request, { signal: control.signal }) : { principal: {}, resource: {}, context: {} });\n if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');\n const call: CedarAuthorizationCall = { ...ids, context: data.context, schema, validateRequest: true, policies: { staticPolicies: policies },\n entities: [{ uid: ids.principal, attrs: data.principal, parents: [] }, { uid: ids.resource, attrs: data.resource, parents: [] }] };\n // A fresh mutable copy supports wasm-bindgen conversion without exposing the pinned configuration.\n const result = await evaluate(jsonValue(call, { maxBytes: 360_448, maxDepth: 12, maxNodes: 4096 }) as unknown as CedarAuthorizationCall, { signal: control.signal });\n if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');\n return normalize(result);\n }).then(result => { active.delete(control); finish(stoppedOrExpired() ? deny(expired ? 'unavailable' : 'cancelled') : result); },\n () => { active.delete(control); stoppedOrExpired(); finish(deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable')); });\n });\n };\n return Object.freeze({ version, identities, authorize, close() { if (closed) return; closed = true; for (const control of active) control.abort(); } });\n}\n/** Core enforcement and audit own the single final receipt; evaluator lifetime remains with its host. */\nexport function createCedarAuthorizer(options: CedarAuthorizerOptions): Authorizer {\n const policy = createCedarAuthorizationPolicy(options);\n try {\n const authorizer = createAuthorizer({ policy, ...(options.permissions === undefined ? {} : { permissions: options.permissions }),\n ...(options.audit === undefined ? {} : { audit: options.audit }), ...(options.limits === undefined ? {} : { limits: options.limits }) });\n return Object.freeze({ ...authorizer, close() { authorizer.close(); policy.close(); } });\n } catch (error) { policy.close(); throw error; }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@mayurajs/authz-cedar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0-rc.1",
4
+ "description": "Scoped local Cedar authorization with pinned policies, trusted attributes and core audit integration.",
5
+ "author": {
6
+ "name": "Aryabh",
7
+ "email": "dev@rokad.co"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/KartikeyAI/mayura.git",
13
+ "directory": "extensions/authz-cedar"
14
+ },
15
+ "homepage": "https://github.com/KartikeyAI/mayura#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/KartikeyAI/mayura/issues"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=22.12.0 <23 || >=24.14.1 <25"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src/**/*.ts",
33
+ "README.md",
34
+ "LICENSE",
35
+ "NOTICE"
36
+ ],
37
+ "dependencies": {},
38
+ "peerDependencies": {
39
+ "mayura": "^1.2.0-rc.1"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,192 @@
1
+ import { AUTHORIZATION_RESOURCE_KINDS, authorizationRequest, createAuthorizer, freezeJson, jsonValue, MayuraError,
2
+ type AuthorizationDecision, type AuthorizationDenyReason, type AuthorizationPolicy, type AuthorizationRequest,
3
+ type AuthorizationResourceKind, type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';
4
+ import { sha256Hex, utf8ByteLength } from 'mayura/core/host';
5
+
6
+ /** Native Cedar UID object. Identifiers are never interpolated into policy source. */
7
+ export interface CedarEntityUid { readonly type: string; readonly id: string }
8
+ /** Bounded Cedar literal subset: no null, floating point, entity escapes or extension constructors. */
9
+ export type CedarAttributeValue = string | boolean | number | readonly CedarAttributeValue[] | { readonly [key: string]: CedarAttributeValue };
10
+ export interface CedarAuthorizationAttributes {
11
+ readonly principal: Readonly<Record<string, CedarAttributeValue>>;
12
+ readonly resource: Readonly<Record<string, CedarAttributeValue>>;
13
+ readonly context: Readonly<Record<string, CedarAttributeValue>>;
14
+ }
15
+ export interface CedarAuthorizationMapping {
16
+ readonly kind: AuthorizationResourceKind; readonly action: string;
17
+ readonly resourceType: string; readonly actionId: string;
18
+ }
19
+ /** Native stateless cedar-wasm isAuthorized input, restricted to static policies and literal attributes. */
20
+ export interface CedarAuthorizationCall {
21
+ readonly principal: CedarEntityUid; readonly action: CedarEntityUid; readonly resource: CedarEntityUid;
22
+ readonly context: Readonly<Record<string, CedarAttributeValue>>;
23
+ readonly schema: string; readonly validateRequest: true;
24
+ readonly policies: { readonly staticPolicies: Readonly<Record<string, string>> };
25
+ readonly entities: readonly { readonly uid: CedarEntityUid; readonly attrs: Readonly<Record<string, CedarAttributeValue>>; readonly parents: readonly CedarEntityUid[] }[];
26
+ }
27
+ /** Inject native isAuthorized, or a worker wrapper preserving its complete success/failure diagnostics. */
28
+ export type CedarAuthorizationEvaluator = (call: CedarAuthorizationCall, context: { readonly signal: AbortSignal }) => unknown | Promise<unknown>;
29
+ export interface CedarAuthorizationPolicyOptions {
30
+ /** Host-pinned policy/data revision and exact evaluator implementation version. Both enter the fingerprint. */
31
+ readonly version: string; readonly engineVersion: string;
32
+ readonly namespace: string; readonly principalType: string; readonly actionType: string;
33
+ readonly mappings: readonly CedarAuthorizationMapping[];
34
+ /** Named native static policy sources, and a native Cedar schema source. Neither is caller-controlled. */
35
+ readonly policies: Readonly<Record<string, string>>; readonly schema: string;
36
+ readonly evaluate: CedarAuthorizationEvaluator;
37
+ /** Trusted, read-only attribute source. No entity graph, request identity or policy overrides are accepted. */
38
+ readonly attributes?: (request: AuthorizationRequest, context: { readonly signal: AbortSignal }) => CedarAuthorizationAttributes | Promise<CedarAuthorizationAttributes>;
39
+ /** authz:cedar admits host callbacks; core enforcement/audit require their own grants. */
40
+ readonly permissions?: Permissions;
41
+ /** Whole attribute/evaluation deadline, default 1,000 ms; 1–30,000 ms. Synchronous engines cannot be preempted. */
42
+ readonly timeoutMs?: number;
43
+ /** Unsettled operations, default 32; 1–256. Ignored cancellation retains the slot until settlement. */
44
+ readonly maxConcurrent?: number;
45
+ }
46
+ export interface CedarAuthorizationPolicy extends AuthorizationPolicy {
47
+ /** Pure identity helper for provisioning/debugging. Unmapped requests return null; invalid scope throws. */
48
+ identities(request: AuthorizationRequest): { readonly principal: CedarEntityUid; readonly action: CedarEntityUid; readonly resource: CedarEntityUid } | null;
49
+ /** Cancels checks and refuses new work; never disposes the caller-owned evaluator. */
50
+ close(): void;
51
+ }
52
+ export interface CedarAuthorizerOptions extends CedarAuthorizationPolicyOptions {
53
+ readonly audit?: AuthorizerOptions['audit']; readonly limits?: AuthorizerOptions['limits'];
54
+ }
55
+ const identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
56
+ const entityType = /^[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*$/u;
57
+ const actionName = /^[a-z][a-z0-9_.:-]{0,127}$/u;
58
+ const bindingKey = (kind: string, action: string) => JSON.stringify([kind, action]);
59
+ function invalid(): never { throw new MayuraError('INVALID_CONFIG', 'Cedar authorization requires pinned policy/schema/engine revisions, exact scoped mappings and bounded callbacks.'); }
60
+ function record(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === 'object' && !Array.isArray(value); }
61
+ function bound(value: number | undefined, fallback: number, max: number): number {
62
+ const result = value ?? fallback; if (!Number.isSafeInteger(result) || result < 1 || result > max) return invalid(); return result;
63
+ }
64
+ function canonical(value: unknown): string {
65
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
66
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
67
+ const data = value as Record<string, unknown>;
68
+ return `{${Object.keys(data).sort().map(key => `${JSON.stringify(key)}:${canonical(data[key])}`).join(',')}}`;
69
+ }
70
+ function capture(raw: AuthorizationRequest): AuthorizationRequest {
71
+ const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });
72
+ if (!record(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject') throw new MayuraError('INVALID_INPUT', 'Invalid scoped authorization request.');
73
+ const data = snapshot as unknown as AuthorizationRequest; return authorizationRequest(data.subject, data.action, data.resource);
74
+ }
75
+ /** Literal-only attributes deliberately exclude implicit/explicit entity references and extension constructors. */
76
+ function attributes(raw: unknown): CedarAuthorizationAttributes {
77
+ const data = jsonValue(raw, { maxBytes: 16_384, maxDepth: 8, maxNodes: 2048 });
78
+ const literal = (value: unknown): boolean => typeof value === 'string' || typeof value === 'boolean'
79
+ || (typeof value === 'number' && Number.isSafeInteger(value)) || (Array.isArray(value) ? value.every(literal)
80
+ : record(value) && Object.entries(value).every(([key, entry]) => /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(key) && literal(entry)));
81
+ if (!record(data) || Object.keys(data).sort().join(',') !== 'context,principal,resource'
82
+ || !['principal', 'resource', 'context'].every(name => record(data[name]) && literal(data[name]))) throw new Error('Invalid trusted Cedar attributes.');
83
+ return freezeJson(data) as unknown as CedarAuthorizationAttributes;
84
+ }
85
+ /**
86
+ * Scoped, read-only Cedar policy through the core authorization contract. Native parse/evaluation errors deny,
87
+ * including error diagnostics accompanying an allow. No evaluator, credential, policy or schema is discovered.
88
+ */
89
+ export function createCedarAuthorizationPolicy(options: CedarAuthorizationPolicyOptions): CedarAuthorizationPolicy {
90
+ let version: string; let namespace: string; let principalType: string; let actionType: string; let schema: string;
91
+ let policies: Readonly<Record<string, string>>; let mappings: ReadonlyMap<string, CedarAuthorizationMapping>;
92
+ let evaluate: CedarAuthorizationEvaluator; let load: CedarAuthorizationPolicyOptions['attributes'];
93
+ let admitted: boolean; let timeoutMs: number; let maxConcurrent: number;
94
+ try {
95
+ if (!options || [options.version, options.engineVersion, options.namespace].some(value => typeof value !== 'string' || !identifier.test(value))
96
+ || [options.principalType, options.actionType].some(value => typeof value !== 'string' || value.length > 128 || !entityType.test(value))
97
+ || options.principalType === options.actionType || typeof options.evaluate !== 'function'
98
+ || (options.attributes !== undefined && typeof options.attributes !== 'function')
99
+ || typeof options.schema !== 'string' || !options.schema.trim() || utf8ByteLength(options.schema) > 65_536) return invalid();
100
+ const sources = jsonValue(options.policies, { maxBytes: 262_144, maxDepth: 1, maxNodes: 257 });
101
+ if (!record(sources) || !Object.keys(sources).length || Object.keys(sources).length > 256
102
+ || !Object.entries(sources).every(([id, source]) => identifier.test(id) && typeof source === 'string' && !!source.trim())) return invalid();
103
+ policies = freezeJson(sources) as Readonly<Record<string, string>>;
104
+ const captured = jsonValue(options.mappings, { maxBytes: 65_536, maxDepth: 2, maxNodes: 2561 });
105
+ if (!Array.isArray(captured) || !captured.length || captured.length > 512) return invalid();
106
+ const mapped = new Map<string, CedarAuthorizationMapping>();
107
+ for (const raw of captured) {
108
+ if (!record(raw) || Object.keys(raw).sort().join(',') !== 'action,actionId,kind,resourceType'
109
+ || !AUTHORIZATION_RESOURCE_KINDS.includes(raw['kind'] as AuthorizationResourceKind)
110
+ || typeof raw['action'] !== 'string' || !actionName.test(raw['action']) || typeof raw['actionId'] !== 'string' || !identifier.test(raw['actionId'])
111
+ || typeof raw['resourceType'] !== 'string' || raw['resourceType'].length > 128 || !entityType.test(raw['resourceType'])
112
+ || raw['resourceType'] === options.actionType) return invalid();
113
+ const binding = freezeJson(raw) as unknown as CedarAuthorizationMapping; const key = bindingKey(binding.kind, binding.action);
114
+ if (mapped.has(key)) return invalid(); mapped.set(key, binding);
115
+ }
116
+ const grants = jsonValue(options.permissions?.allow ?? [], { maxBytes: 1_048_576, maxDepth: 1, maxNodes: 4097 });
117
+ if (!Array.isArray(grants) || grants.length > 4096 || grants.some(grant => typeof grant !== 'string' || !grant.length || grant.length > 256)) return invalid();
118
+ admitted = grants.includes('authz:cedar'); namespace = options.namespace; principalType = options.principalType; actionType = options.actionType;
119
+ schema = options.schema; mappings = mapped; evaluate = options.evaluate; load = options.attributes;
120
+ timeoutMs = bound(options.timeoutMs, 1000, 30_000); maxConcurrent = bound(options.maxConcurrent, 32, 256);
121
+ version = `cedar:${sha256Hex(canonical({ protocol: 'mayura.cedar.v1', revision: options.version, engineVersion: options.engineVersion,
122
+ namespace, principalType, actionType, schema, policies, mappings: [...mapped.values()].sort((a, b) => bindingKey(a.kind, a.action) < bindingKey(b.kind, b.action) ? -1 : 1) }))}`;
123
+ } catch { return invalid(); }
124
+ let closed = false; const active = new Set<AbortController>();
125
+ const deny = (reason: AuthorizationDenyReason): AuthorizationDecision => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });
126
+ const identities: CedarAuthorizationPolicy['identities'] = raw => {
127
+ const request = capture(raw); const scope = request.subject;
128
+ if (scope.principalId !== request.resource.scope.principalId || scope.projectId !== request.resource.scope.projectId) throw new MayuraError('INVALID_INPUT', 'The authorization resource does not belong to the verified scope.');
129
+ const mapping = mappings.get(bindingKey(request.resource.kind, request.action)); if (!mapping) return null;
130
+ const identity = (domain: string, extra: readonly string[]) => sha256Hex(JSON.stringify([domain, namespace, scope.projectId, scope.principalId, ...extra]));
131
+ return Object.freeze({ principal: Object.freeze({ type: principalType, id: identity('mayura.cedar.subject.v1', []) }),
132
+ action: Object.freeze({ type: actionType, id: mapping.actionId }),
133
+ resource: Object.freeze({ type: mapping.resourceType, id: identity('mayura.cedar.resource.v1', [request.resource.kind, request.resource.id]) }) });
134
+ };
135
+ const normalize = (raw: unknown): AuthorizationDecision => {
136
+ const answer = jsonValue(raw, { maxBytes: 16_384, maxDepth: 12, maxNodes: 2048 });
137
+ if (!record(answer) || answer['type'] !== 'success' || Object.keys(answer).sort().join(',') !== 'response,type,warnings'
138
+ || !Array.isArray(answer['warnings']) || !record(answer['response'])) return deny('unavailable');
139
+ const response = answer['response']; const diagnostics = response['diagnostics'];
140
+ if (Object.keys(response).sort().join(',') !== 'decision,diagnostics' || !record(diagnostics)
141
+ || Object.keys(diagnostics).sort().join(',') !== 'errors,reason' || !Array.isArray(diagnostics['errors']) || diagnostics['errors'].length
142
+ || !Array.isArray(diagnostics['reason']) || diagnostics['reason'].some(id => typeof id !== 'string' || !Object.hasOwn(policies, id))
143
+ || new Set(diagnostics['reason']).size !== diagnostics['reason'].length) return deny('unavailable');
144
+ if (response['decision'] === 'deny') return deny(diagnostics['reason'].length ? 'explicit_deny' : 'no_match');
145
+ if (response['decision'] !== 'allow' || !diagnostics['reason'].length) return deny('unavailable');
146
+ return Object.freeze({ effect: 'allow', reason: 'allowed', policyVersion: version, ruleId: diagnostics['reason'].length === 1 ? diagnostics['reason'][0] as string : null });
147
+ };
148
+ const authorize: AuthorizationPolicy['authorize'] = async (raw, context) => {
149
+ let request: AuthorizationRequest;
150
+ try { request = capture(raw); if (!(context?.signal instanceof AbortSignal)) return deny('invalid_request'); } catch { return deny('invalid_request'); }
151
+ if (closed || context.signal.aborted) return deny('cancelled');
152
+ if (request.subject.principalId !== request.resource.scope.principalId || request.subject.projectId !== request.resource.scope.projectId) return deny('scope_mismatch');
153
+ if (!admitted) return deny('permission_denied');
154
+ const ids = identities(request); if (!ids) return deny('no_match');
155
+ if (active.size >= maxConcurrent) return deny('limit_exceeded');
156
+ const control = new AbortController(); active.add(control); const deadline = Date.now() + timeoutMs; let expired = false;
157
+ return new Promise<AuthorizationDecision>(resolve => {
158
+ let settled = false; let timer: ReturnType<typeof setTimeout> | undefined;
159
+ const finish = (decision: AuthorizationDecision) => { if (settled) return; settled = true; if (timer !== undefined) clearTimeout(timer);
160
+ context.signal.removeEventListener('abort', abort); control.signal.removeEventListener('abort', stopped); resolve(decision); };
161
+ const abort = () => control.abort();
162
+ const stopped = () => finish(deny(expired ? 'unavailable' : 'cancelled'));
163
+ const stoppedOrExpired = () => { if (!control.signal.aborted && Date.now() >= deadline) { expired = true; control.abort(); } return control.signal.aborted || closed; };
164
+ control.signal.addEventListener('abort', stopped, { once: true }); context.signal.addEventListener('abort', abort, { once: true });
165
+ timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs);
166
+ if (context.signal.aborted || closed) control.abort();
167
+ // Capacity remains owned by this task even if its observable decision has already timed out.
168
+ void Promise.resolve().then(async () => {
169
+ if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');
170
+ const data = attributes(load ? await load(request, { signal: control.signal }) : { principal: {}, resource: {}, context: {} });
171
+ if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');
172
+ const call: CedarAuthorizationCall = { ...ids, context: data.context, schema, validateRequest: true, policies: { staticPolicies: policies },
173
+ entities: [{ uid: ids.principal, attrs: data.principal, parents: [] }, { uid: ids.resource, attrs: data.resource, parents: [] }] };
174
+ // A fresh mutable copy supports wasm-bindgen conversion without exposing the pinned configuration.
175
+ const result = await evaluate(jsonValue(call, { maxBytes: 360_448, maxDepth: 12, maxNodes: 4096 }) as unknown as CedarAuthorizationCall, { signal: control.signal });
176
+ if (stoppedOrExpired()) return deny(expired ? 'unavailable' : 'cancelled');
177
+ return normalize(result);
178
+ }).then(result => { active.delete(control); finish(stoppedOrExpired() ? deny(expired ? 'unavailable' : 'cancelled') : result); },
179
+ () => { active.delete(control); stoppedOrExpired(); finish(deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable')); });
180
+ });
181
+ };
182
+ return Object.freeze({ version, identities, authorize, close() { if (closed) return; closed = true; for (const control of active) control.abort(); } });
183
+ }
184
+ /** Core enforcement and audit own the single final receipt; evaluator lifetime remains with its host. */
185
+ export function createCedarAuthorizer(options: CedarAuthorizerOptions): Authorizer {
186
+ const policy = createCedarAuthorizationPolicy(options);
187
+ try {
188
+ const authorizer = createAuthorizer({ policy, ...(options.permissions === undefined ? {} : { permissions: options.permissions }),
189
+ ...(options.audit === undefined ? {} : { audit: options.audit }), ...(options.limits === undefined ? {} : { limits: options.limits }) });
190
+ return Object.freeze({ ...authorizer, close() { authorizer.close(); policy.close(); } });
191
+ } catch (error) { policy.close(); throw error; }
192
+ }