@mayurajs/authz-http 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 +201 -0
- package/NOTICE +8 -0
- package/README.md +26 -2
- package/dist/index.d.ts +53 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +244 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +189 -0
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,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@mayurajs/authz-http`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An optional HTTP authorization policy adapter for Mayura's core contract. Implements the explicit
|
|
4
|
+
`mayura.authorization.v1` protocol with pinned policy revisions, per-request correlation, strict bounded JSON,
|
|
5
|
+
HTTPS transport, explicit `authz:http` permission and fail-closed receipts. No vendor SDK, automatic retries,
|
|
6
|
+
redirects, cookies, implicit credentials, decision cache or network activity on construction.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { createHttpAuthorizer } from '@mayurajs/authz-http';
|
|
10
|
+
|
|
11
|
+
const authorizer = createHttpAuthorizer({
|
|
12
|
+
endpoint: 'https://policy.example/check', version: 'shop-v3',
|
|
13
|
+
permissions: { allow: ['authz:http', 'authz:evaluate'] },
|
|
14
|
+
timeoutMs: 750, limits: { timeoutMs: 1000 },
|
|
15
|
+
});
|
|
16
|
+
const scope = { principalId: 'alice', projectId: 'shop' };
|
|
17
|
+
try { await authorizer.require(scope, 'read', { kind: 'thread', id: 'chat', scope }); }
|
|
18
|
+
finally { await authorizer.flushAudit(); authorizer.close(); }
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Optional `audit` settings and `authz:audit` forward to the core authorizer. Audit/OTel consumers receive one final core
|
|
22
|
+
receipt, never credentials, raw provider payloads or exception text. `createHttpAuthorizationPolicy` instead returns a
|
|
23
|
+
plain core-compatible policy with an explicit `close()`; pass it to `createAuthorizer` or the scoped server and close
|
|
24
|
+
it separately when finished. Each check makes a fresh request; configure host rate limits for your service's cost.
|
|
25
|
+
|
|
26
|
+
The full protocol, transport bounds, service authentication and server/audit wiring are documented in
|
|
27
|
+
[HTTP authorization policies](../../docs/integrations/authz-http.md).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type AuthorizationDecision, type AuthorizationPolicy, type AuthorizationRequest, type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';
|
|
2
|
+
/** Versioned Mayura policy-decision protocol; this is not an OPA, Cedar, OpenFGA or other vendor wire format. */
|
|
3
|
+
export declare const HTTP_AUTHORIZATION_PROTOCOL: 'mayura.authorization.v1';
|
|
4
|
+
/** Exact POST envelope sent to the configured decision service. */
|
|
5
|
+
export interface HttpAuthorizationRequest {
|
|
6
|
+
readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;
|
|
7
|
+
readonly requestId: string;
|
|
8
|
+
readonly policyVersion: string;
|
|
9
|
+
readonly request: AuthorizationRequest;
|
|
10
|
+
}
|
|
11
|
+
/** Exact HTTP 200 envelope required from the decision service. */
|
|
12
|
+
export interface HttpAuthorizationResponse {
|
|
13
|
+
readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;
|
|
14
|
+
readonly requestId: string;
|
|
15
|
+
readonly decision: AuthorizationDecision;
|
|
16
|
+
}
|
|
17
|
+
export interface HttpAuthorizationPolicyOptions {
|
|
18
|
+
/** Exact trusted policy endpoint. HTTPS only, except explicitly enabled literal-loopback development URLs. */
|
|
19
|
+
readonly endpoint: string;
|
|
20
|
+
/** Pinned remote policy revision. Every decision must echo it exactly. */
|
|
21
|
+
readonly version: string;
|
|
22
|
+
/** Explicit authz:http admission. No remote request is made without it. */
|
|
23
|
+
readonly permissions?: Permissions;
|
|
24
|
+
/** Explicit fixed service credentials/headers. Never taken from a browser request or the environment. */
|
|
25
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
26
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
27
|
+
readonly allowInsecureLoopback?: boolean;
|
|
28
|
+
/** Per-check transport deadline, default 1,000 ms; 1–30,000 ms. */
|
|
29
|
+
readonly timeoutMs?: number;
|
|
30
|
+
/** Outstanding transport tasks, default 32; 1–256. Ignored aborts retain capacity until actual settlement. */
|
|
31
|
+
readonly maxConcurrent?: number;
|
|
32
|
+
/** UTF-8 request bytes, default 8,192; 1,024–16,384. */
|
|
33
|
+
readonly maxRequestBytes?: number;
|
|
34
|
+
/** Decoded response bytes, default 2,048; 256–16,384. */
|
|
35
|
+
readonly maxResponseBytes?: number;
|
|
36
|
+
}
|
|
37
|
+
export interface HttpAuthorizationPolicy extends AuthorizationPolicy {
|
|
38
|
+
/** Abort admitted transport work and refuse future evaluation. No request cache is retained. */
|
|
39
|
+
close(): void;
|
|
40
|
+
}
|
|
41
|
+
export interface HttpAuthorizerOptions extends HttpAuthorizationPolicyOptions {
|
|
42
|
+
readonly audit?: AuthorizerOptions['audit'];
|
|
43
|
+
/** Core evaluation limits, separate from HTTP transport limits. */
|
|
44
|
+
readonly limits?: AuthorizerOptions['limits'];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Remote policy through the core contract. Only a correlated, pinned, strictly validated decision may allow. All
|
|
48
|
+
* transport/parse/status failures deny without provider diagnostics. No retries, redirects, cookies or implicit cache.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createHttpAuthorizationPolicy(options: HttpAuthorizationPolicyOptions): HttpAuthorizationPolicy;
|
|
51
|
+
/** Core enforcement and audit own the single decision receipt; closing also aborts the owned remote policy. */
|
|
52
|
+
export declare function createHttpAuthorizer(options: HttpAuthorizerOptions): Authorizer;
|
|
53
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,qBAAqB,EAAgC,KAAK,mBAAmB,EAAE,KAAK,oBAAoB,EAC7G,KAAK,UAAU,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE5E,iHAAiH;AACjH,eAAO,MAAM,2BAA2B,EAAG,yBAAkC,CAAC;AAC9E,mEAAmE;AACnE,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAAQ,EAAE,OAAO,2BAA2B,CAAC;IACtD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC;CACxC;AACD,kEAAkE;AAClE,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,QAAQ,EAAE,OAAO,2BAA2B,CAAC;IACtD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;CAC1C;AACD,MAAM,WAAW,8BAA8B;IAC7C,8GAA8G;IAC9G,QA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|
2
|
+
/** Versioned Mayura policy-decision protocol; this is not an OPA, Cedar, OpenFGA or other vendor wire format. */
|
|
3
|
+
export const HTTP_AUTHORIZATION_PROTOCOL = 'mayura.authorization.v1';
|
|
4
|
+
const identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
|
|
5
|
+
const denyReasons = ['no_match', 'explicit_deny', 'scope_mismatch', 'permission_denied', 'invalid_request', 'unavailable', 'cancelled', 'limit_exceeded'];
|
|
6
|
+
function invalid() { throw new MayuraError('INVALID_CONFIG', 'HTTP authorization requires an explicit endpoint, policy version and bounded transport settings.'); }
|
|
7
|
+
function bound(value, fallback, min, max) {
|
|
8
|
+
const result = value ?? fallback;
|
|
9
|
+
if (!Number.isSafeInteger(result) || result < min || result > max)
|
|
10
|
+
return invalid();
|
|
11
|
+
return result;
|
|
12
|
+
}
|
|
13
|
+
function endpoint(value, insecure) {
|
|
14
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
15
|
+
return invalid();
|
|
16
|
+
const url = new URL(value);
|
|
17
|
+
if (url.username || url.password || url.search || url.hash || !url.hostname
|
|
18
|
+
|| (url.protocol !== 'https:' && !(insecure && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname))))
|
|
19
|
+
return invalid();
|
|
20
|
+
return url.href;
|
|
21
|
+
}
|
|
22
|
+
/** Copy bounded fixed headers. Transport/security headers cannot override the adapter's request isolation. */
|
|
23
|
+
function headers(input) {
|
|
24
|
+
const value = jsonValue(input ?? {}, { maxBytes: 8192, maxDepth: 1, maxNodes: 33 });
|
|
25
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 16)
|
|
26
|
+
return invalid();
|
|
27
|
+
const result = new Headers({ 'content-type': 'application/json', accept: 'application/json' });
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
30
|
+
const name = key.toLowerCase();
|
|
31
|
+
if (!/^[a-z0-9!#$%&'*+.^_`|~-]{1,128}$/.test(name) || seen.has(name) || /^(?:sec-|proxy-)/.test(name)
|
|
32
|
+
|| ['host', 'cookie', 'set-cookie', 'connection', 'content-length', 'content-type', 'accept', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'origin', 'referer', 'user-agent', 'accept-encoding'].includes(name)
|
|
33
|
+
|| typeof entry !== 'string' || !entry.length || /[^\x20-\x7e]/.test(entry))
|
|
34
|
+
return invalid();
|
|
35
|
+
seen.add(name);
|
|
36
|
+
result.set(name, entry);
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
function frame(text, requestId, version) {
|
|
41
|
+
const raw = jsonValue(JSON.parse(text), { maxBytes: 16_384, maxDepth: 3, maxNodes: 24 });
|
|
42
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).sort().join(',') !== 'decision,protocol,requestId'
|
|
43
|
+
|| raw['protocol'] !== HTTP_AUTHORIZATION_PROTOCOL || raw['requestId'] !== requestId)
|
|
44
|
+
return null;
|
|
45
|
+
const decision = raw['decision'];
|
|
46
|
+
if (!decision || typeof decision !== 'object' || Array.isArray(decision) || Object.keys(decision).sort().join(',') !== 'effect,policyVersion,reason,ruleId'
|
|
47
|
+
|| decision['policyVersion'] !== version || (decision['ruleId'] !== null && (typeof decision['ruleId'] !== 'string' || !identifier.test(decision['ruleId'])))
|
|
48
|
+
|| typeof decision['reason'] !== 'string'
|
|
49
|
+
|| (decision['effect'] === 'allow' ? decision['reason'] !== 'allowed' : decision['effect'] !== 'deny' || !denyReasons.includes(decision['reason'])))
|
|
50
|
+
return null;
|
|
51
|
+
return Object.freeze({ effect: decision['effect'], reason: decision['reason'], policyVersion: version, ruleId: decision['ruleId'] });
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Remote policy through the core contract. Only a correlated, pinned, strictly validated decision may allow. All
|
|
55
|
+
* transport/parse/status failures deny without provider diagnostics. No retries, redirects, cookies or implicit cache.
|
|
56
|
+
*/
|
|
57
|
+
export function createHttpAuthorizationPolicy(options) {
|
|
58
|
+
let destination;
|
|
59
|
+
let fixedHeaders;
|
|
60
|
+
let transport;
|
|
61
|
+
let version;
|
|
62
|
+
let timeoutMs;
|
|
63
|
+
let maxConcurrent;
|
|
64
|
+
let maxRequestBytes;
|
|
65
|
+
let maxResponseBytes;
|
|
66
|
+
let admitted;
|
|
67
|
+
try {
|
|
68
|
+
if (!options || typeof options.version !== 'string' || !identifier.test(options.version)
|
|
69
|
+
|| (options.allowInsecureLoopback !== undefined && typeof options.allowInsecureLoopback !== 'boolean'))
|
|
70
|
+
return invalid();
|
|
71
|
+
destination = endpoint(options.endpoint, options.allowInsecureLoopback === true);
|
|
72
|
+
fixedHeaders = headers(options.headers);
|
|
73
|
+
version = options.version;
|
|
74
|
+
transport = options.fetch ?? globalThis.fetch;
|
|
75
|
+
if (typeof transport !== 'function')
|
|
76
|
+
return invalid();
|
|
77
|
+
const grants = options.permissions?.allow ?? [];
|
|
78
|
+
if (!Array.isArray(grants) || grants.length > 4096 || grants.some(grant => typeof grant !== 'string' || !grant.length || grant.length > 256))
|
|
79
|
+
return invalid();
|
|
80
|
+
admitted = grants.includes('authz:http');
|
|
81
|
+
timeoutMs = bound(options.timeoutMs, 1000, 1, 30_000);
|
|
82
|
+
maxConcurrent = bound(options.maxConcurrent, 32, 1, 256);
|
|
83
|
+
maxRequestBytes = bound(options.maxRequestBytes, 8192, 1024, 16_384);
|
|
84
|
+
maxResponseBytes = bound(options.maxResponseBytes, 2048, 256, 16_384);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return invalid();
|
|
88
|
+
}
|
|
89
|
+
const active = new Set();
|
|
90
|
+
let closed = false;
|
|
91
|
+
const deny = (reason) => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });
|
|
92
|
+
const authorize = async (raw, context) => {
|
|
93
|
+
let request;
|
|
94
|
+
try {
|
|
95
|
+
// Exact root shape as well as nested validation: never serialize arbitrary caller fields.
|
|
96
|
+
const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });
|
|
97
|
+
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject')
|
|
98
|
+
return deny('invalid_request');
|
|
99
|
+
const data = snapshot;
|
|
100
|
+
request = authorizationRequest(data.subject, data.action, data.resource);
|
|
101
|
+
if (!(context?.signal instanceof AbortSignal))
|
|
102
|
+
return deny('invalid_request');
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return deny('invalid_request');
|
|
106
|
+
}
|
|
107
|
+
if (closed || context.signal.aborted)
|
|
108
|
+
return deny('cancelled');
|
|
109
|
+
if (request.subject.principalId !== request.resource.scope.principalId || request.subject.projectId !== request.resource.scope.projectId)
|
|
110
|
+
return deny('scope_mismatch');
|
|
111
|
+
if (!admitted)
|
|
112
|
+
return deny('permission_denied');
|
|
113
|
+
if (active.size >= maxConcurrent)
|
|
114
|
+
return deny('limit_exceeded');
|
|
115
|
+
const requestId = crypto.randomUUID();
|
|
116
|
+
const envelope = { protocol: HTTP_AUTHORIZATION_PROTOCOL, requestId, policyVersion: version, request };
|
|
117
|
+
const payload = JSON.stringify(envelope);
|
|
118
|
+
if (new TextEncoder().encode(payload).byteLength > maxRequestBytes)
|
|
119
|
+
return deny('limit_exceeded');
|
|
120
|
+
const control = new AbortController();
|
|
121
|
+
const deadline = Date.now() + timeoutMs;
|
|
122
|
+
active.add(control);
|
|
123
|
+
return await new Promise(resolve => {
|
|
124
|
+
let finished = false;
|
|
125
|
+
let expired = false;
|
|
126
|
+
let timer;
|
|
127
|
+
const finish = (decision) => {
|
|
128
|
+
if (finished)
|
|
129
|
+
return;
|
|
130
|
+
finished = true;
|
|
131
|
+
clearTimeout(timer);
|
|
132
|
+
context.signal.removeEventListener('abort', relay);
|
|
133
|
+
control.signal.removeEventListener('abort', aborted);
|
|
134
|
+
resolve(decision);
|
|
135
|
+
};
|
|
136
|
+
const relay = () => control.abort();
|
|
137
|
+
const aborted = () => finish(deny(expired ? 'unavailable' : 'cancelled'));
|
|
138
|
+
control.signal.addEventListener('abort', aborted, { once: true });
|
|
139
|
+
context.signal.addEventListener('abort', relay, { once: true });
|
|
140
|
+
timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs);
|
|
141
|
+
if (context.signal.aborted)
|
|
142
|
+
relay();
|
|
143
|
+
// The task is deliberately not raced internally: ignored fetch/read cancellation retains the transport slot.
|
|
144
|
+
const work = async () => {
|
|
145
|
+
if (control.signal.aborted)
|
|
146
|
+
return deny(expired ? 'unavailable' : 'cancelled');
|
|
147
|
+
let response;
|
|
148
|
+
let reader;
|
|
149
|
+
let cancellation;
|
|
150
|
+
const cancelBody = () => {
|
|
151
|
+
if (cancellation)
|
|
152
|
+
return cancellation;
|
|
153
|
+
try {
|
|
154
|
+
if (reader)
|
|
155
|
+
cancellation = reader.cancel().catch(() => { });
|
|
156
|
+
else if (response?.body)
|
|
157
|
+
cancellation = response.body.cancel().catch(() => { });
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
cancellation = Promise.resolve();
|
|
161
|
+
}
|
|
162
|
+
return cancellation;
|
|
163
|
+
};
|
|
164
|
+
const stopBody = () => { void cancelBody(); };
|
|
165
|
+
control.signal.addEventListener('abort', stopBody, { once: true });
|
|
166
|
+
try {
|
|
167
|
+
response = await transport(destination, { method: 'POST', headers: new Headers(fixedHeaders), body: payload,
|
|
168
|
+
signal: control.signal, redirect: 'error', credentials: 'omit', cache: 'no-store', referrerPolicy: 'no-referrer' });
|
|
169
|
+
if (control.signal.aborted || closed)
|
|
170
|
+
return deny(expired ? 'unavailable' : 'cancelled');
|
|
171
|
+
if (response.status !== 200 || response.redirected || (response.url && response.url !== destination)
|
|
172
|
+
|| !/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '') || !response.body)
|
|
173
|
+
return deny('unavailable');
|
|
174
|
+
const length = response.headers.get('content-length');
|
|
175
|
+
if (length !== null && (!/^[0-9]{1,9}$/.test(length) || Number(length) > maxResponseBytes))
|
|
176
|
+
return deny('unavailable');
|
|
177
|
+
reader = response.body.getReader();
|
|
178
|
+
const chunks = [];
|
|
179
|
+
let size = 0;
|
|
180
|
+
for (;;) {
|
|
181
|
+
if (control.signal.aborted)
|
|
182
|
+
return deny(expired ? 'unavailable' : 'cancelled');
|
|
183
|
+
const item = await reader.read();
|
|
184
|
+
if (item.done)
|
|
185
|
+
break;
|
|
186
|
+
size += item.value.byteLength;
|
|
187
|
+
if (size > maxResponseBytes)
|
|
188
|
+
return deny('unavailable');
|
|
189
|
+
if (item.value.byteLength)
|
|
190
|
+
chunks.push(new Uint8Array(item.value));
|
|
191
|
+
}
|
|
192
|
+
const bytes = new Uint8Array(size);
|
|
193
|
+
let offset = 0;
|
|
194
|
+
for (const chunk of chunks) {
|
|
195
|
+
bytes.set(chunk, offset);
|
|
196
|
+
offset += chunk.byteLength;
|
|
197
|
+
}
|
|
198
|
+
const decision = frame(new TextDecoder('utf-8', { fatal: true }).decode(bytes), requestId, version);
|
|
199
|
+
if (Date.now() >= deadline && !control.signal.aborted) {
|
|
200
|
+
expired = true;
|
|
201
|
+
control.abort();
|
|
202
|
+
}
|
|
203
|
+
return control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : decision ?? deny('unavailable');
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable');
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
control.signal.removeEventListener('abort', stopBody);
|
|
210
|
+
await cancelBody();
|
|
211
|
+
if (reader)
|
|
212
|
+
reader.releaseLock();
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
void Promise.resolve().then(work).then(result => {
|
|
216
|
+
active.delete(control);
|
|
217
|
+
// Cleanup and trusted transport callbacks can consume wall time while timers are unable to run.
|
|
218
|
+
if (Date.now() >= deadline && !control.signal.aborted) {
|
|
219
|
+
expired = true;
|
|
220
|
+
control.abort();
|
|
221
|
+
}
|
|
222
|
+
finish(control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : result);
|
|
223
|
+
}, () => { active.delete(control); finish(deny('unavailable')); });
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
return Object.freeze({ version, authorize, close() { if (closed)
|
|
227
|
+
return; closed = true; for (const control of active)
|
|
228
|
+
control.abort(); } });
|
|
229
|
+
}
|
|
230
|
+
/** Core enforcement and audit own the single decision receipt; closing also aborts the owned remote policy. */
|
|
231
|
+
export function createHttpAuthorizer(options) {
|
|
232
|
+
const policy = createHttpAuthorizationPolicy(options);
|
|
233
|
+
try {
|
|
234
|
+
const authorizer = createAuthorizer({ policy,
|
|
235
|
+
...(options.permissions === undefined ? {} : { permissions: options.permissions }),
|
|
236
|
+
...(options.audit === undefined ? {} : { audit: options.audit }), ...(options.limits === undefined ? {} : { limits: options.limits }) });
|
|
237
|
+
return Object.freeze({ ...authorizer, close() { authorizer.close(); policy.close(); } });
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
policy.close();
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,SAAS,EAAE,WAAW,EAEV,MAAM,QAAQ,CAAC;AAE5E,iHAAiH;AACjH,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAkC,CAAC;AA2C9E,MAAM,UAAU,GAAG,uCAAuC,CAAC;AAC3D,MAAM,WAAW,GAAsB,CAAC,UAAU,EAAE,eAAe,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,CAAC,CAAC;A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K,EAAE,CAAC;QAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAAC,MAAM,KAAK,CAAC;IAAC,CAAC;AAClD,CAAC","sourcesContent":["import { authorizationRequest, createAuthorizer, jsonValue, MayuraError,\n type AuthorizationDecision, type AuthorizationDenyReason, type AuthorizationPolicy, type AuthorizationRequest,\n type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';\n\n/** Versioned Mayura policy-decision protocol; this is not an OPA, Cedar, OpenFGA or other vendor wire format. */\nexport const HTTP_AUTHORIZATION_PROTOCOL = 'mayura.authorization.v1' as const;\n/** Exact POST envelope sent to the configured decision service. */\nexport interface HttpAuthorizationRequest {\n readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;\n readonly requestId: string;\n readonly policyVersion: string;\n readonly request: AuthorizationRequest;\n}\n/** Exact HTTP 200 envelope required from the decision service. */\nexport interface HttpAuthorizationResponse {\n readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;\n readonly requestId: string;\n readonly decision: AuthorizationDecision;\n}\nexport interface HttpAuthorizationPolicyOptions {\n /** Exact trusted policy endpoint. HTTPS only, except explicitly enabled literal-loopback development URLs. */\n readonly endpoint: string;\n /** Pinned remote policy revision. Every decision must echo it exactly. */\n readonly version: string;\n /** Explicit authz:http admission. No remote request is made without it. */\n readonly permissions?: Permissions;\n /** Explicit fixed service credentials/headers. Never taken from a browser request or the environment. */\n readonly headers?: Readonly<Record<string, string>>;\n readonly fetch?: typeof globalThis.fetch;\n readonly allowInsecureLoopback?: boolean;\n /** Per-check transport deadline, default 1,000 ms; 1–30,000 ms. */\n readonly timeoutMs?: number;\n /** Outstanding transport tasks, default 32; 1–256. Ignored aborts retain capacity until actual settlement. */\n readonly maxConcurrent?: number;\n /** UTF-8 request bytes, default 8,192; 1,024–16,384. */\n readonly maxRequestBytes?: number;\n /** Decoded response bytes, default 2,048; 256–16,384. */\n readonly maxResponseBytes?: number;\n}\nexport interface HttpAuthorizationPolicy extends AuthorizationPolicy {\n /** Abort admitted transport work and refuse future evaluation. No request cache is retained. */\n close(): void;\n}\nexport interface HttpAuthorizerOptions extends HttpAuthorizationPolicyOptions {\n readonly audit?: AuthorizerOptions['audit'];\n /** Core evaluation limits, separate from HTTP transport limits. */\n readonly limits?: AuthorizerOptions['limits'];\n}\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;\nconst denyReasons: readonly string[] = ['no_match', 'explicit_deny', 'scope_mismatch', 'permission_denied', 'invalid_request', 'unavailable', 'cancelled', 'limit_exceeded'];\nfunction invalid(): never { throw new MayuraError('INVALID_CONFIG', 'HTTP authorization requires an explicit endpoint, policy version and bounded transport settings.'); }\nfunction bound(value: number | undefined, fallback: number, min: number, max: number): number {\n const result = value ?? fallback; if (!Number.isSafeInteger(result) || result < min || result > max) return invalid(); return result;\n}\nfunction endpoint(value: string, insecure: boolean): string {\n if (typeof value !== 'string' || value.length > 2048) return invalid();\n const url = new URL(value);\n if (url.username || url.password || url.search || url.hash || !url.hostname\n || (url.protocol !== 'https:' && !(insecure && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)))) return invalid();\n return url.href;\n}\n/** Copy bounded fixed headers. Transport/security headers cannot override the adapter's request isolation. */\nfunction headers(input: HttpAuthorizationPolicyOptions['headers']): Headers {\n const value = jsonValue(input ?? {}, { maxBytes: 8192, maxDepth: 1, maxNodes: 33 });\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 16) return invalid();\n const result = new Headers({ 'content-type': 'application/json', accept: 'application/json' });\n const seen = new Set<string>();\n for (const [key, entry] of Object.entries(value)) {\n const name = key.toLowerCase();\n if (!/^[a-z0-9!#$%&'*+.^_`|~-]{1,128}$/.test(name) || seen.has(name) || /^(?:sec-|proxy-)/.test(name)\n || ['host', 'cookie', 'set-cookie', 'connection', 'content-length', 'content-type', 'accept', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'origin', 'referer', 'user-agent', 'accept-encoding'].includes(name)\n || typeof entry !== 'string' || !entry.length || /[^\\x20-\\x7e]/.test(entry)) return invalid();\n seen.add(name); result.set(name, entry);\n }\n return result;\n}\nfunction frame(text: string, requestId: string, version: string): AuthorizationDecision | null {\n const raw = jsonValue(JSON.parse(text), { maxBytes: 16_384, maxDepth: 3, maxNodes: 24 });\n if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).sort().join(',') !== 'decision,protocol,requestId'\n || raw['protocol'] !== HTTP_AUTHORIZATION_PROTOCOL || raw['requestId'] !== requestId) return null;\n const decision = raw['decision'];\n if (!decision || typeof decision !== 'object' || Array.isArray(decision) || Object.keys(decision).sort().join(',') !== 'effect,policyVersion,reason,ruleId'\n || decision['policyVersion'] !== version || (decision['ruleId'] !== null && (typeof decision['ruleId'] !== 'string' || !identifier.test(decision['ruleId'])))\n || typeof decision['reason'] !== 'string'\n || (decision['effect'] === 'allow' ? decision['reason'] !== 'allowed' : decision['effect'] !== 'deny' || !denyReasons.includes(decision['reason']))) return null;\n return Object.freeze({ effect: decision['effect'], reason: decision['reason'], policyVersion: version, ruleId: decision['ruleId'] }) as AuthorizationDecision;\n}\n/**\n * Remote policy through the core contract. Only a correlated, pinned, strictly validated decision may allow. All\n * transport/parse/status failures deny without provider diagnostics. No retries, redirects, cookies or implicit cache.\n */\nexport function createHttpAuthorizationPolicy(options: HttpAuthorizationPolicyOptions): HttpAuthorizationPolicy {\n let destination: string; let fixedHeaders: Headers; let transport: typeof globalThis.fetch; let version: string;\n let timeoutMs: number; let maxConcurrent: number; let maxRequestBytes: number; let maxResponseBytes: number; let admitted: boolean;\n try {\n if (!options || typeof options.version !== 'string' || !identifier.test(options.version)\n || (options.allowInsecureLoopback !== undefined && typeof options.allowInsecureLoopback !== 'boolean')) return invalid();\n destination = endpoint(options.endpoint, options.allowInsecureLoopback === true); fixedHeaders = headers(options.headers); version = options.version;\n transport = options.fetch ?? globalThis.fetch; if (typeof transport !== 'function') return invalid();\n const grants = options.permissions?.allow ?? [];\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:http');\n timeoutMs = bound(options.timeoutMs, 1000, 1, 30_000); maxConcurrent = bound(options.maxConcurrent, 32, 1, 256);\n maxRequestBytes = bound(options.maxRequestBytes, 8192, 1024, 16_384); maxResponseBytes = bound(options.maxResponseBytes, 2048, 256, 16_384);\n } catch { return invalid(); }\n const active = new Set<AbortController>(); let closed = false;\n const deny = (reason: AuthorizationDenyReason): AuthorizationDecision => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });\n const authorize: AuthorizationPolicy['authorize'] = async (raw, context) => {\n let request: AuthorizationRequest;\n try {\n // Exact root shape as well as nested validation: never serialize arbitrary caller fields.\n const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });\n if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject') return deny('invalid_request');\n const data = snapshot as unknown as AuthorizationRequest; request = authorizationRequest(data.subject, data.action, data.resource);\n if (!(context?.signal instanceof AbortSignal)) return deny('invalid_request');\n } 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 if (active.size >= maxConcurrent) return deny('limit_exceeded');\n const requestId = crypto.randomUUID();\n const envelope: HttpAuthorizationRequest = { protocol: HTTP_AUTHORIZATION_PROTOCOL, requestId, policyVersion: version, request };\n const payload = JSON.stringify(envelope);\n if (new TextEncoder().encode(payload).byteLength > maxRequestBytes) return deny('limit_exceeded');\n const control = new AbortController(); const deadline = Date.now() + timeoutMs; active.add(control);\n return await new Promise<AuthorizationDecision>(resolve => {\n let finished = false; let expired = false; let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = (decision: AuthorizationDecision) => {\n if (finished) return; finished = true; clearTimeout(timer);\n context.signal.removeEventListener('abort', relay); control.signal.removeEventListener('abort', aborted); resolve(decision);\n };\n const relay = () => control.abort(); const aborted = () => finish(deny(expired ? 'unavailable' : 'cancelled'));\n control.signal.addEventListener('abort', aborted, { once: true }); context.signal.addEventListener('abort', relay, { once: true });\n timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs); if (context.signal.aborted) relay();\n // The task is deliberately not raced internally: ignored fetch/read cancellation retains the transport slot.\n const work = async (): Promise<AuthorizationDecision> => {\n if (control.signal.aborted) return deny(expired ? 'unavailable' : 'cancelled');\n let response: Response | undefined; let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let cancellation: Promise<void> | undefined;\n const cancelBody = (): Promise<void> | undefined => {\n if (cancellation) return cancellation;\n try { if (reader) cancellation = reader.cancel().catch(() => {}); else if (response?.body) cancellation = response.body.cancel().catch(() => {}); }\n catch { cancellation = Promise.resolve(); }\n return cancellation;\n };\n const stopBody = () => { void cancelBody(); };\n control.signal.addEventListener('abort', stopBody, { once: true });\n try {\n response = await transport(destination, { method: 'POST', headers: new Headers(fixedHeaders), body: payload,\n signal: control.signal, redirect: 'error', credentials: 'omit', cache: 'no-store', referrerPolicy: 'no-referrer' });\n if (control.signal.aborted || closed) return deny(expired ? 'unavailable' : 'cancelled');\n if (response.status !== 200 || response.redirected || (response.url && response.url !== destination)\n || !/^application\\/json(?:\\s*;|$)/i.test(response.headers.get('content-type') ?? '') || !response.body) return deny('unavailable');\n const length = response.headers.get('content-length');\n if (length !== null && (!/^[0-9]{1,9}$/.test(length) || Number(length) > maxResponseBytes)) return deny('unavailable');\n reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0;\n for (;;) {\n if (control.signal.aborted) return deny(expired ? 'unavailable' : 'cancelled');\n const item = await reader.read(); if (item.done) break;\n size += item.value.byteLength; if (size > maxResponseBytes) return deny('unavailable'); if (item.value.byteLength) chunks.push(new Uint8Array(item.value));\n }\n const bytes = new Uint8Array(size); let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n const decision = frame(new TextDecoder('utf-8', { fatal: true }).decode(bytes), requestId, version);\n if (Date.now() >= deadline && !control.signal.aborted) { expired = true; control.abort(); }\n return control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : decision ?? deny('unavailable');\n } catch { return deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable'); }\n finally { control.signal.removeEventListener('abort', stopBody); await cancelBody(); if (reader) reader.releaseLock(); }\n };\n void Promise.resolve().then(work).then(result => {\n active.delete(control);\n // Cleanup and trusted transport callbacks can consume wall time while timers are unable to run.\n if (Date.now() >= deadline && !control.signal.aborted) { expired = true; control.abort(); }\n finish(control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : result);\n }, () => { active.delete(control); finish(deny('unavailable')); });\n });\n };\n return Object.freeze({ version, authorize, close() { if (closed) return; closed = true; for (const control of active) control.abort(); } });\n}\n/** Core enforcement and audit own the single decision receipt; closing also aborts the owned remote policy. */\nexport function createHttpAuthorizer(options: HttpAuthorizerOptions): Authorizer {\n const policy = createHttpAuthorizationPolicy(options);\n try {\n const authorizer = createAuthorizer({ policy,\n ...(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-http",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0-rc.1",
|
|
4
|
+
"description": "Bounded HTTP authorization policies with scoped fail-closed decisions 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-http"
|
|
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,189 @@
|
|
|
1
|
+
import { authorizationRequest, createAuthorizer, jsonValue, MayuraError,
|
|
2
|
+
type AuthorizationDecision, type AuthorizationDenyReason, type AuthorizationPolicy, type AuthorizationRequest,
|
|
3
|
+
type Authorizer, type AuthorizerOptions, type Permissions } from 'mayura';
|
|
4
|
+
|
|
5
|
+
/** Versioned Mayura policy-decision protocol; this is not an OPA, Cedar, OpenFGA or other vendor wire format. */
|
|
6
|
+
export const HTTP_AUTHORIZATION_PROTOCOL = 'mayura.authorization.v1' as const;
|
|
7
|
+
/** Exact POST envelope sent to the configured decision service. */
|
|
8
|
+
export interface HttpAuthorizationRequest {
|
|
9
|
+
readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;
|
|
10
|
+
readonly requestId: string;
|
|
11
|
+
readonly policyVersion: string;
|
|
12
|
+
readonly request: AuthorizationRequest;
|
|
13
|
+
}
|
|
14
|
+
/** Exact HTTP 200 envelope required from the decision service. */
|
|
15
|
+
export interface HttpAuthorizationResponse {
|
|
16
|
+
readonly protocol: typeof HTTP_AUTHORIZATION_PROTOCOL;
|
|
17
|
+
readonly requestId: string;
|
|
18
|
+
readonly decision: AuthorizationDecision;
|
|
19
|
+
}
|
|
20
|
+
export interface HttpAuthorizationPolicyOptions {
|
|
21
|
+
/** Exact trusted policy endpoint. HTTPS only, except explicitly enabled literal-loopback development URLs. */
|
|
22
|
+
readonly endpoint: string;
|
|
23
|
+
/** Pinned remote policy revision. Every decision must echo it exactly. */
|
|
24
|
+
readonly version: string;
|
|
25
|
+
/** Explicit authz:http admission. No remote request is made without it. */
|
|
26
|
+
readonly permissions?: Permissions;
|
|
27
|
+
/** Explicit fixed service credentials/headers. Never taken from a browser request or the environment. */
|
|
28
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
29
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
30
|
+
readonly allowInsecureLoopback?: boolean;
|
|
31
|
+
/** Per-check transport deadline, default 1,000 ms; 1–30,000 ms. */
|
|
32
|
+
readonly timeoutMs?: number;
|
|
33
|
+
/** Outstanding transport tasks, default 32; 1–256. Ignored aborts retain capacity until actual settlement. */
|
|
34
|
+
readonly maxConcurrent?: number;
|
|
35
|
+
/** UTF-8 request bytes, default 8,192; 1,024–16,384. */
|
|
36
|
+
readonly maxRequestBytes?: number;
|
|
37
|
+
/** Decoded response bytes, default 2,048; 256–16,384. */
|
|
38
|
+
readonly maxResponseBytes?: number;
|
|
39
|
+
}
|
|
40
|
+
export interface HttpAuthorizationPolicy extends AuthorizationPolicy {
|
|
41
|
+
/** Abort admitted transport work and refuse future evaluation. No request cache is retained. */
|
|
42
|
+
close(): void;
|
|
43
|
+
}
|
|
44
|
+
export interface HttpAuthorizerOptions extends HttpAuthorizationPolicyOptions {
|
|
45
|
+
readonly audit?: AuthorizerOptions['audit'];
|
|
46
|
+
/** Core evaluation limits, separate from HTTP transport limits. */
|
|
47
|
+
readonly limits?: AuthorizerOptions['limits'];
|
|
48
|
+
}
|
|
49
|
+
const identifier = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
|
|
50
|
+
const denyReasons: readonly string[] = ['no_match', 'explicit_deny', 'scope_mismatch', 'permission_denied', 'invalid_request', 'unavailable', 'cancelled', 'limit_exceeded'];
|
|
51
|
+
function invalid(): never { throw new MayuraError('INVALID_CONFIG', 'HTTP authorization requires an explicit endpoint, policy version and bounded transport settings.'); }
|
|
52
|
+
function bound(value: number | undefined, fallback: number, min: number, max: number): number {
|
|
53
|
+
const result = value ?? fallback; if (!Number.isSafeInteger(result) || result < min || result > max) return invalid(); return result;
|
|
54
|
+
}
|
|
55
|
+
function endpoint(value: string, insecure: boolean): string {
|
|
56
|
+
if (typeof value !== 'string' || value.length > 2048) return invalid();
|
|
57
|
+
const url = new URL(value);
|
|
58
|
+
if (url.username || url.password || url.search || url.hash || !url.hostname
|
|
59
|
+
|| (url.protocol !== 'https:' && !(insecure && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)))) return invalid();
|
|
60
|
+
return url.href;
|
|
61
|
+
}
|
|
62
|
+
/** Copy bounded fixed headers. Transport/security headers cannot override the adapter's request isolation. */
|
|
63
|
+
function headers(input: HttpAuthorizationPolicyOptions['headers']): Headers {
|
|
64
|
+
const value = jsonValue(input ?? {}, { maxBytes: 8192, maxDepth: 1, maxNodes: 33 });
|
|
65
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 16) return invalid();
|
|
66
|
+
const result = new Headers({ 'content-type': 'application/json', accept: 'application/json' });
|
|
67
|
+
const seen = new Set<string>();
|
|
68
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
69
|
+
const name = key.toLowerCase();
|
|
70
|
+
if (!/^[a-z0-9!#$%&'*+.^_`|~-]{1,128}$/.test(name) || seen.has(name) || /^(?:sec-|proxy-)/.test(name)
|
|
71
|
+
|| ['host', 'cookie', 'set-cookie', 'connection', 'content-length', 'content-type', 'accept', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'origin', 'referer', 'user-agent', 'accept-encoding'].includes(name)
|
|
72
|
+
|| typeof entry !== 'string' || !entry.length || /[^\x20-\x7e]/.test(entry)) return invalid();
|
|
73
|
+
seen.add(name); result.set(name, entry);
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
function frame(text: string, requestId: string, version: string): AuthorizationDecision | null {
|
|
78
|
+
const raw = jsonValue(JSON.parse(text), { maxBytes: 16_384, maxDepth: 3, maxNodes: 24 });
|
|
79
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).sort().join(',') !== 'decision,protocol,requestId'
|
|
80
|
+
|| raw['protocol'] !== HTTP_AUTHORIZATION_PROTOCOL || raw['requestId'] !== requestId) return null;
|
|
81
|
+
const decision = raw['decision'];
|
|
82
|
+
if (!decision || typeof decision !== 'object' || Array.isArray(decision) || Object.keys(decision).sort().join(',') !== 'effect,policyVersion,reason,ruleId'
|
|
83
|
+
|| decision['policyVersion'] !== version || (decision['ruleId'] !== null && (typeof decision['ruleId'] !== 'string' || !identifier.test(decision['ruleId'])))
|
|
84
|
+
|| typeof decision['reason'] !== 'string'
|
|
85
|
+
|| (decision['effect'] === 'allow' ? decision['reason'] !== 'allowed' : decision['effect'] !== 'deny' || !denyReasons.includes(decision['reason']))) return null;
|
|
86
|
+
return Object.freeze({ effect: decision['effect'], reason: decision['reason'], policyVersion: version, ruleId: decision['ruleId'] }) as AuthorizationDecision;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Remote policy through the core contract. Only a correlated, pinned, strictly validated decision may allow. All
|
|
90
|
+
* transport/parse/status failures deny without provider diagnostics. No retries, redirects, cookies or implicit cache.
|
|
91
|
+
*/
|
|
92
|
+
export function createHttpAuthorizationPolicy(options: HttpAuthorizationPolicyOptions): HttpAuthorizationPolicy {
|
|
93
|
+
let destination: string; let fixedHeaders: Headers; let transport: typeof globalThis.fetch; let version: string;
|
|
94
|
+
let timeoutMs: number; let maxConcurrent: number; let maxRequestBytes: number; let maxResponseBytes: number; let admitted: boolean;
|
|
95
|
+
try {
|
|
96
|
+
if (!options || typeof options.version !== 'string' || !identifier.test(options.version)
|
|
97
|
+
|| (options.allowInsecureLoopback !== undefined && typeof options.allowInsecureLoopback !== 'boolean')) return invalid();
|
|
98
|
+
destination = endpoint(options.endpoint, options.allowInsecureLoopback === true); fixedHeaders = headers(options.headers); version = options.version;
|
|
99
|
+
transport = options.fetch ?? globalThis.fetch; if (typeof transport !== 'function') return invalid();
|
|
100
|
+
const grants = options.permissions?.allow ?? [];
|
|
101
|
+
if (!Array.isArray(grants) || grants.length > 4096 || grants.some(grant => typeof grant !== 'string' || !grant.length || grant.length > 256)) return invalid();
|
|
102
|
+
admitted = grants.includes('authz:http');
|
|
103
|
+
timeoutMs = bound(options.timeoutMs, 1000, 1, 30_000); maxConcurrent = bound(options.maxConcurrent, 32, 1, 256);
|
|
104
|
+
maxRequestBytes = bound(options.maxRequestBytes, 8192, 1024, 16_384); maxResponseBytes = bound(options.maxResponseBytes, 2048, 256, 16_384);
|
|
105
|
+
} catch { return invalid(); }
|
|
106
|
+
const active = new Set<AbortController>(); let closed = false;
|
|
107
|
+
const deny = (reason: AuthorizationDenyReason): AuthorizationDecision => Object.freeze({ effect: 'deny', reason, policyVersion: version, ruleId: null });
|
|
108
|
+
const authorize: AuthorizationPolicy['authorize'] = async (raw, context) => {
|
|
109
|
+
let request: AuthorizationRequest;
|
|
110
|
+
try {
|
|
111
|
+
// Exact root shape as well as nested validation: never serialize arbitrary caller fields.
|
|
112
|
+
const snapshot = jsonValue(raw, { maxBytes: 4096, maxDepth: 4, maxNodes: 32 });
|
|
113
|
+
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) || Object.keys(snapshot).sort().join(',') !== 'action,resource,subject') return deny('invalid_request');
|
|
114
|
+
const data = snapshot as unknown as AuthorizationRequest; request = authorizationRequest(data.subject, data.action, data.resource);
|
|
115
|
+
if (!(context?.signal instanceof AbortSignal)) return deny('invalid_request');
|
|
116
|
+
} catch { return deny('invalid_request'); }
|
|
117
|
+
if (closed || context.signal.aborted) return deny('cancelled');
|
|
118
|
+
if (request.subject.principalId !== request.resource.scope.principalId || request.subject.projectId !== request.resource.scope.projectId) return deny('scope_mismatch');
|
|
119
|
+
if (!admitted) return deny('permission_denied');
|
|
120
|
+
if (active.size >= maxConcurrent) return deny('limit_exceeded');
|
|
121
|
+
const requestId = crypto.randomUUID();
|
|
122
|
+
const envelope: HttpAuthorizationRequest = { protocol: HTTP_AUTHORIZATION_PROTOCOL, requestId, policyVersion: version, request };
|
|
123
|
+
const payload = JSON.stringify(envelope);
|
|
124
|
+
if (new TextEncoder().encode(payload).byteLength > maxRequestBytes) return deny('limit_exceeded');
|
|
125
|
+
const control = new AbortController(); const deadline = Date.now() + timeoutMs; active.add(control);
|
|
126
|
+
return await new Promise<AuthorizationDecision>(resolve => {
|
|
127
|
+
let finished = false; let expired = false; let timer: ReturnType<typeof setTimeout> | undefined;
|
|
128
|
+
const finish = (decision: AuthorizationDecision) => {
|
|
129
|
+
if (finished) return; finished = true; clearTimeout(timer);
|
|
130
|
+
context.signal.removeEventListener('abort', relay); control.signal.removeEventListener('abort', aborted); resolve(decision);
|
|
131
|
+
};
|
|
132
|
+
const relay = () => control.abort(); const aborted = () => finish(deny(expired ? 'unavailable' : 'cancelled'));
|
|
133
|
+
control.signal.addEventListener('abort', aborted, { once: true }); context.signal.addEventListener('abort', relay, { once: true });
|
|
134
|
+
timer = setTimeout(() => { expired = true; control.abort(); }, timeoutMs); if (context.signal.aborted) relay();
|
|
135
|
+
// The task is deliberately not raced internally: ignored fetch/read cancellation retains the transport slot.
|
|
136
|
+
const work = async (): Promise<AuthorizationDecision> => {
|
|
137
|
+
if (control.signal.aborted) return deny(expired ? 'unavailable' : 'cancelled');
|
|
138
|
+
let response: Response | undefined; let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
139
|
+
let cancellation: Promise<void> | undefined;
|
|
140
|
+
const cancelBody = (): Promise<void> | undefined => {
|
|
141
|
+
if (cancellation) return cancellation;
|
|
142
|
+
try { if (reader) cancellation = reader.cancel().catch(() => {}); else if (response?.body) cancellation = response.body.cancel().catch(() => {}); }
|
|
143
|
+
catch { cancellation = Promise.resolve(); }
|
|
144
|
+
return cancellation;
|
|
145
|
+
};
|
|
146
|
+
const stopBody = () => { void cancelBody(); };
|
|
147
|
+
control.signal.addEventListener('abort', stopBody, { once: true });
|
|
148
|
+
try {
|
|
149
|
+
response = await transport(destination, { method: 'POST', headers: new Headers(fixedHeaders), body: payload,
|
|
150
|
+
signal: control.signal, redirect: 'error', credentials: 'omit', cache: 'no-store', referrerPolicy: 'no-referrer' });
|
|
151
|
+
if (control.signal.aborted || closed) return deny(expired ? 'unavailable' : 'cancelled');
|
|
152
|
+
if (response.status !== 200 || response.redirected || (response.url && response.url !== destination)
|
|
153
|
+
|| !/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '') || !response.body) return deny('unavailable');
|
|
154
|
+
const length = response.headers.get('content-length');
|
|
155
|
+
if (length !== null && (!/^[0-9]{1,9}$/.test(length) || Number(length) > maxResponseBytes)) return deny('unavailable');
|
|
156
|
+
reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0;
|
|
157
|
+
for (;;) {
|
|
158
|
+
if (control.signal.aborted) return deny(expired ? 'unavailable' : 'cancelled');
|
|
159
|
+
const item = await reader.read(); if (item.done) break;
|
|
160
|
+
size += item.value.byteLength; if (size > maxResponseBytes) return deny('unavailable'); if (item.value.byteLength) chunks.push(new Uint8Array(item.value));
|
|
161
|
+
}
|
|
162
|
+
const bytes = new Uint8Array(size); let offset = 0;
|
|
163
|
+
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
|
164
|
+
const decision = frame(new TextDecoder('utf-8', { fatal: true }).decode(bytes), requestId, version);
|
|
165
|
+
if (Date.now() >= deadline && !control.signal.aborted) { expired = true; control.abort(); }
|
|
166
|
+
return control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : decision ?? deny('unavailable');
|
|
167
|
+
} catch { return deny(control.signal.aborted ? expired ? 'unavailable' : 'cancelled' : 'unavailable'); }
|
|
168
|
+
finally { control.signal.removeEventListener('abort', stopBody); await cancelBody(); if (reader) reader.releaseLock(); }
|
|
169
|
+
};
|
|
170
|
+
void Promise.resolve().then(work).then(result => {
|
|
171
|
+
active.delete(control);
|
|
172
|
+
// Cleanup and trusted transport callbacks can consume wall time while timers are unable to run.
|
|
173
|
+
if (Date.now() >= deadline && !control.signal.aborted) { expired = true; control.abort(); }
|
|
174
|
+
finish(control.signal.aborted || closed ? deny(expired ? 'unavailable' : 'cancelled') : result);
|
|
175
|
+
}, () => { active.delete(control); finish(deny('unavailable')); });
|
|
176
|
+
});
|
|
177
|
+
};
|
|
178
|
+
return Object.freeze({ version, authorize, close() { if (closed) return; closed = true; for (const control of active) control.abort(); } });
|
|
179
|
+
}
|
|
180
|
+
/** Core enforcement and audit own the single decision receipt; closing also aborts the owned remote policy. */
|
|
181
|
+
export function createHttpAuthorizer(options: HttpAuthorizerOptions): Authorizer {
|
|
182
|
+
const policy = createHttpAuthorizationPolicy(options);
|
|
183
|
+
try {
|
|
184
|
+
const authorizer = createAuthorizer({ policy,
|
|
185
|
+
...(options.permissions === undefined ? {} : { permissions: options.permissions }),
|
|
186
|
+
...(options.audit === undefined ? {} : { audit: options.audit }), ...(options.limits === undefined ? {} : { limits: options.limits }) });
|
|
187
|
+
return Object.freeze({ ...authorizer, close() { authorizer.close(); policy.close(); } });
|
|
188
|
+
} catch (error) { policy.close(); throw error; }
|
|
189
|
+
}
|