@niscorp/charter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DOCS.md ADDED
@@ -0,0 +1,229 @@
1
+ # Charter — API Reference
2
+
3
+ Every export of `@niscorp/charter`. The package is a pure function library: no
4
+ state, no I/O, no side effects.
5
+
6
+ ## Types
7
+
8
+ ### `Charter`
9
+
10
+ ```typescript
11
+ type Charter = Record<string, RoleDef>;
12
+ ```
13
+
14
+ The document: role name → role definition.
15
+
16
+ ### `RoleDef`
17
+
18
+ ```typescript
19
+ type RoleDef =
20
+ | string[] // sugar: an actions-only role
21
+ | {
22
+ extends?: string[]; // compose whole roles (per section)
23
+ without?: string[]; // subtract whole roles (per section)
24
+ allow?: string[]; // sugar → actions.allow
25
+ deny?: string[]; // sugar → actions.deny
26
+ actions?: Selection; // the actions universe
27
+ data?: Selection; // the data universe
28
+ layouts?: Selection; // the layouts universe
29
+ scoping?: string; // how far this role reaches (see below)
30
+ };
31
+ ```
32
+
33
+ A bare `string[]` is an actions-only role. Top-level `allow`/`deny` are sugar
34
+ for the `actions` section — an actions-only role never names a section. Using
35
+ both the sugar and an explicit `actions:` on one role is an error (the verifier
36
+ catches it).
37
+
38
+ #### `scoping` — how far a role reaches
39
+
40
+ A section says *which* ids a role holds. `scoping` says *how far* they reach when
41
+ they use them — an opaque name the governed target resolves, exactly like the
42
+ strings in every section. The charter does not know what it means; it only knows
43
+ which role said it.
44
+
45
+ ```typescript
46
+ { member: { actions: ['me.*'], data: ['bookings.read'], scoping: 'personal' },
47
+ desk: { extends: ['member'], data: ['memberships.read'] } }
48
+ ```
49
+
50
+ Both roles hold `bookings.read`. The member reaches their own rows; the desk
51
+ reaches the studio's. One grant, two reaches, decided by the rung.
52
+
53
+ **`scoping` is NOT composed by `extends`, and that is deliberate.** Every section
54
+ accumulates upward — a desk holding everything a member holds is exactly right
55
+ for actions and data. Reach is the opposite: a desk extends a member's *screens*
56
+ but must not extend a member's *"only my own rows"*, or the roster it exists to
57
+ read would filter to the one person operating it. A role's reach is its own
58
+ answer or none.
59
+
60
+ **One role in, one profile out.** `resolveScoping` takes a single role, because
61
+ reach is a property of a role and a function handed several has no answer to give.
62
+
63
+ ```typescript
64
+ resolveScoping(charter, 'member') // 'personal'
65
+ resolveScoping(charter, 'desk') // undefined — not inherited
66
+ ```
67
+
68
+ A principal holding several roles is normal, not a conflict: somebody who teaches
69
+ at a studio and trains there is an instructor *and* a member. Compile one policy
70
+ per role and merge them (vex: `mergeScopePolicies`); the principal may do
71
+ anything any of their roles permits, and each role reaches as far as its own
72
+ profile says.
73
+
74
+ ```typescript
75
+ mergeScopePolicies(
76
+ roles.map((role) => createScopePolicy(resolvePrincipal(charter, grants, [role], 'data'), behaviors, resolveScoping(charter, role))),
77
+ )
78
+ ```
79
+
80
+ This function used to take a list and throw when two roles named different
81
+ profiles. That rule was not defending against anything — it was written by
82
+ analogy to two granted layout variants for one action, which genuinely conflict
83
+ because a screen renders one. Two reaches do not conflict; they add.
84
+
85
+ ### `Selection`
86
+
87
+ ```typescript
88
+ type Selection = string[] | { allow?: string[]; deny?: string[] };
89
+ ```
90
+
91
+ Within a section: a bare glob list (sugar for `{ allow }`) or explicit
92
+ `allow`/`deny`.
93
+
94
+ ### `Section`
95
+
96
+ ```typescript
97
+ type Section = 'actions' | 'data' | 'layouts';
98
+ ```
99
+
100
+ Which universe a selection resolves in. `actions` selects Nova action ids,
101
+ `data` selects `table.verb` capabilities, `layouts` selects layout-variant ids
102
+ (ring 2 — moss's dialect).
103
+
104
+ ---
105
+
106
+ ## Globs
107
+
108
+ ### `matchGlob(pattern, id): boolean`
109
+
110
+ One wildcard: `*` matches any run of characters, including dots. `matchGlob('crm.*', 'crm.deal.form')` is `true`. No `**`, no braces, no regex.
111
+
112
+ ### `matchAll(patterns, ids): Set<string>`
113
+
114
+ Every id in `ids` selected by any pattern in `patterns`.
115
+
116
+ ---
117
+
118
+ ## Resolution
119
+
120
+ ### `resolveRole(charter, universe, role, section, memo?, visiting?): ReadonlySet<string>`
121
+
122
+ Resolve one role in one section against `universe`. Applies the algebra
123
+ (`extends` ∪ `allow` − `deny` − `without`). `memo` and `visiting` are internal
124
+ accumulators for recursion and cycle detection; callers pass neither.
125
+
126
+ Throws `CharterError` on an unknown role reference or a role cycle.
127
+
128
+ ### `resolvePrincipal(charter, universe, roles, section?): Set<string>`
129
+
130
+ The union of the resolved sets for every role the principal wears, in one
131
+ section. `section` defaults to `'actions'`. This is the function a server calls
132
+ at login.
133
+
134
+ ```typescript
135
+ resolvePrincipal(charter, actionIds, ['sales', 'dev'], 'actions'); // granted actions
136
+ resolvePrincipal(charter, verbLeaves, ['sales', 'dev'], 'data'); // granted table.verb caps
137
+ ```
138
+
139
+ ### `normalizeRole(def, section): { allow, deny, extends, without }`
140
+
141
+ The atoms of one role for one section, with sugar expanded. Exposed for tools
142
+ that inspect a role's raw selection (the verifier uses it); most callers want
143
+ `resolveRole`.
144
+
145
+ ### `CharterError`
146
+
147
+ Thrown by the resolver for unknown-role and cycle errors. `verifyCharter`
148
+ catches these and reports them as `resolution` errors rather than throwing.
149
+
150
+ ---
151
+
152
+ ## Verification
153
+
154
+ ### `verifyCharter(charter, universes, assignments?, closure?): VerifyReport`
155
+
156
+ Run every coherence check against both universes. Call at boot/CI; refuse to
157
+ serve if `report.errors` is non-empty.
158
+
159
+ - `universes: { actions: readonly string[]; data: readonly string[]; layouts?: readonly string[] }`
160
+ — the id sets each section resolves against, handed in by the composer. The
161
+ `layouts` universe is optional: absent, the section is inert (a charter's
162
+ `layouts` keys resolve against nothing and are not verified); handed in, its
163
+ dead-deny/dead-allow/orphan/leaves-only checks run like any other section.
164
+ - `assignments?: Record<string, readonly string[]>` — `principal → roles`, used
165
+ by the `subtractive-assigned` check.
166
+ - `closure?: ClosureAuditor` — the injected per-role cross-action audit.
167
+
168
+ ### `ClosureAuditor`
169
+
170
+ ```typescript
171
+ type ClosureAuditor = (grantedIds: readonly string[], layoutIds?: readonly string[]) => string[];
172
+ ```
173
+
174
+ Given a role's resolved action ids (and, when the app governs layouts, its
175
+ granted variant ids), return the cross-action wiring problems inside that
176
+ closure. Supplied by the consumer that owns actions (Nova exports
177
+ `auditClosure(definitions)`; moss wraps it and substitutes granted variants so
178
+ the audit sees each role's effective definitions).
179
+
180
+ ### `VerifyReport`
181
+
182
+ ```typescript
183
+ type VerifyReport = {
184
+ errors: VerifyIssue[]; // refuse to boot if non-empty
185
+ warnings: VerifyIssue[]; // deploy, but review
186
+ perRole: RoleClosure[]; // resolved actions + data + closure issues, per role
187
+ };
188
+
189
+ type VerifyIssue = { level: 'error' | 'warning'; rule: string; detail: string };
190
+ type RoleClosure = { role: string; actions: string[]; data: string[]; layouts: string[]; issues: string[] };
191
+ ```
192
+
193
+ ### The checks
194
+
195
+ | rule | level | meaning |
196
+ |---|---|---|
197
+ | `resolution` | error | a cycle or unknown-role reference (per section) |
198
+ | `leaves-only` | error | an id is a namespace of another id — namespaces are never actions |
199
+ | `ambiguous-selection` | error | a role has both top-level `allow`/`deny` and an explicit `actions:` |
200
+ | `dead-deny` | error | a deny glob matches nothing — silent means unprotected |
201
+ | `dead-allow` | warning | an allow glob matches nothing — noise |
202
+ | `orphan` | warning | an action granted by no role — deployed but unreachable |
203
+ | `re-allow` | warning | a role re-allows an id an ancestor denied |
204
+ | `subtractive-assigned` | warning | a role used in `without` is also assigned to a principal |
205
+ | *(closure)* | via `RoleClosure.issues` | cross-action wiring problems from the injected auditor |
206
+
207
+ ---
208
+
209
+ ## Usage pattern
210
+
211
+ ```typescript
212
+ import { resolvePrincipal, verifyCharter } from '@niscorp/charter';
213
+
214
+ // 1. Boot: derive the universes from the governed targets, refuse incoherence.
215
+ const universes = {
216
+ actions: Object.keys(app.actions), // the shell's dialect
217
+ data: scopeGrants(schema.tables), // vex's dialect
218
+ };
219
+ const report = verifyCharter(app.charter, universes, app.assignments, auditClosure(app.actions));
220
+ if (report.errors.length > 0) {
221
+ throw new Error(report.errors.map((e) => `${e.rule}: ${e.detail}`).join('\n'));
222
+ }
223
+
224
+ // 2. Per login: resolve, hand the sets to the enforcers.
225
+ const grantedActions = resolvePrincipal(app.charter, universes.actions, roles, 'actions');
226
+ const grantedData = resolvePrincipal(app.charter, universes.data, roles, 'data');
227
+ const policy = createScopePolicy(grantedData, app.behaviors); // vex enforces
228
+ // the shell mounts only grantedActions
229
+ ```
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # @niscorp/charter
2
+
3
+ A universe-blind policy engine. Roles map glob selections over **opaque string universes**; the engine resolves them to a concrete id set per principal, and a verifier refuses an incoherent charter before it ships. Zero dependencies, by design.
4
+
5
+ The engine never learns what a string means. You hand it a universe of ids (Nova action ids, `table.verb` capabilities, anything), a charter that selects over them with globs, and it returns the resolved set. The same code resolves any domain — access control is one algebra, not one per resource kind.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @niscorp/charter
11
+ ```
12
+
13
+ No peer dependencies. It imports nothing and manufactures no universe of its own — each governed target exports its own dialect and the composer hands the universe in.
14
+
15
+ ## Quick Example
16
+
17
+ ```typescript
18
+ import { resolvePrincipal, verifyCharter } from '@niscorp/charter';
19
+
20
+ // The charter — role names → selections. `extends` composes whole roles;
21
+ // globs select within a universe; deny wins.
22
+ const charter = {
23
+ viewer: ['crm.contacts', 'crm.*.view'],
24
+ sales: { extends: ['viewer'], allow: ['crm.*'], deny: ['crm.*.delete'] },
25
+ admin: { extends: ['sales'], allow: ['crm.*.delete', 'settings'] },
26
+ };
27
+
28
+ // The universe of ids that actually exist — the app derives this
29
+ // (here, the action ids it ships). The engine never invents it.
30
+ const actions = ['crm.contacts', 'crm.contact.view', 'crm.deal.view', 'crm.deal.delete', 'settings'];
31
+
32
+ // What a principal wearing ['sales'] may reach:
33
+ resolvePrincipal(charter, actions, ['sales']);
34
+ // Set { 'crm.contacts', 'crm.contact.view', 'crm.deal.view' }
35
+ // crm.* matched everything; deny crm.*.delete removed the delete.
36
+
37
+ // Refuse incoherence at boot — a dead deny, an ambiguous selection,
38
+ // an unreachable action all surface here.
39
+ const report = verifyCharter(charter, { actions, data: [] });
40
+ if (report.errors.length > 0) throw new Error('charter is incoherent');
41
+ ```
42
+
43
+ ## What it is
44
+
45
+ - **Universe-blind.** `resolvePrincipal(charter, universe, roles, section)` runs the same resolution against any universe. `actions` selects Nova action ids; `data` selects `table.verb` capabilities (the vex-policy dialect); `layouts` selects layout-variant ids (ring 2 — moss's dialect: which variant of an action's layout a principal is served). Adding a governed domain is adding a universe, never new grammar.
46
+ - **A small algebra.** `resolved(role) = (∪ extends ∪ match(allow)) − match(deny) − ∪ without`. Order-independent, deny wins within a role, denies don't inherit. Roles compose whole roles; each section resolves independently.
47
+ - **One glob rule.** `*` matches any run of characters including dots — `crm.*` matches `crm.deal.form`. No `**`, no braces, no regex. When a pattern can't be expressed, the fix is a better id.
48
+ - **A verifier that refuses.** `verifyCharter` runs the opinions the grammar deliberately omits: a dead deny is an **error** (a typo'd deny fails silent, and silent means unprotected); a dead allow is a warning; ambiguous selections, namespace-as-action, orphan actions, re-allowed ancestor denies all surface. "If it boots, it's coherent."
49
+
50
+ ## What it is not
51
+
52
+ It does not enforce, store documents, or know about HTTP, databases, or your app. The charter and the assignment rows are the **app's** artifacts. Enforcement is the governed target's job — vex compiles the resolved `data` set into a scope policy; a shell mounts only the resolved `actions`. Charter resolves and refuses; it never runs at request time.
53
+
54
+ See [DESIGN.md](DESIGN.md) for the thesis and [DOCS.md](DOCS.md) for the full API.
package/dist/index.cjs ADDED
@@ -0,0 +1,177 @@
1
+ 'use strict';
2
+
3
+ // src/glob.ts
4
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
+ var toRegExp = (pattern) => new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
6
+ var matchGlob = (pattern, id) => toRegExp(pattern).test(id);
7
+ var matchAll = (patterns, ids) => {
8
+ const out = /* @__PURE__ */ new Set();
9
+ for (const pattern of patterns) {
10
+ const re = toRegExp(pattern);
11
+ for (const id of ids) if (re.test(id)) out.add(id);
12
+ }
13
+ return out;
14
+ };
15
+
16
+ // src/resolve.ts
17
+ var CharterError = class extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "CharterError";
21
+ }
22
+ };
23
+ var asSelection = (s) => s === void 0 ? { allow: [], deny: [] } : Array.isArray(s) ? { allow: s, deny: [] } : { allow: s.allow ?? [], deny: s.deny ?? [] };
24
+ var normalizeRole = (def, section) => {
25
+ if (Array.isArray(def)) {
26
+ return section === "actions" ? { allow: def, deny: [], extends: [], without: [] } : { allow: [], deny: [], extends: [], without: [] };
27
+ }
28
+ const composition = { extends: def.extends ?? [], without: def.without ?? [] };
29
+ const sel = section === "actions" && def.actions === void 0 ? { allow: def.allow ?? [], deny: def.deny ?? [] } : asSelection(def[section]);
30
+ return { ...sel, ...composition };
31
+ };
32
+ var resolveRole = (charter, universe, role, section, memo = /* @__PURE__ */ new Map(), visiting = /* @__PURE__ */ new Set()) => {
33
+ const cached = memo.get(role);
34
+ if (cached !== void 0) return cached;
35
+ const def = charter[role];
36
+ if (def === void 0) throw new CharterError(`Unknown role "${role}"`);
37
+ if (visiting.has(role)) throw new CharterError(`Role cycle through "${role}"`);
38
+ visiting.add(role);
39
+ const { allow, extends: parents, deny, without } = normalizeRole(def, section);
40
+ const resolved = /* @__PURE__ */ new Set();
41
+ for (const parent of parents) for (const id of resolveRole(charter, universe, parent, section, memo, visiting)) resolved.add(id);
42
+ for (const id of matchAll(allow, universe)) resolved.add(id);
43
+ for (const id of matchAll(deny, universe)) resolved.delete(id);
44
+ for (const sub of without) for (const id of resolveRole(charter, universe, sub, section, memo, visiting)) resolved.delete(id);
45
+ visiting.delete(role);
46
+ memo.set(role, resolved);
47
+ return resolved;
48
+ };
49
+ var resolveScoping = (charter, role) => {
50
+ const def = charter[role];
51
+ return def === void 0 || Array.isArray(def) ? void 0 : def.scoping;
52
+ };
53
+ var resolvePrincipal = (charter, universe, roles, section = "actions") => {
54
+ const memo = /* @__PURE__ */ new Map();
55
+ const out = /* @__PURE__ */ new Set();
56
+ for (const role of roles) for (const id of resolveRole(charter, universe, role, section, memo)) out.add(id);
57
+ return out;
58
+ };
59
+
60
+ // src/verify.ts
61
+ var verifyCharter = (charter, universes, wearable = [], closure) => {
62
+ const actionUniverse = universes.actions;
63
+ const sections = universes.layouts === void 0 ? ["actions", "data"] : ["actions", "data", "layouts"];
64
+ const universeOf = {
65
+ actions: universes.actions,
66
+ data: universes.data,
67
+ layouts: universes.layouts ?? []
68
+ };
69
+ const errors = [];
70
+ const warnings = [];
71
+ const perRole = [];
72
+ const resolved = { actions: /* @__PURE__ */ new Map(), data: /* @__PURE__ */ new Map(), layouts: /* @__PURE__ */ new Map() };
73
+ for (const section of sections) {
74
+ const memo = /* @__PURE__ */ new Map();
75
+ for (const role of Object.keys(charter)) {
76
+ try {
77
+ resolved[section].set(role, resolveRole(charter, universeOf[section], role, section, memo));
78
+ } catch (e) {
79
+ errors.push({ level: "error", rule: "resolution", detail: `${section}: ${e instanceof CharterError ? e.message : String(e)}` });
80
+ }
81
+ }
82
+ }
83
+ const leavesOnly = (universe, kind) => {
84
+ for (const a of universe) {
85
+ for (const b of universe) {
86
+ if (b.startsWith(`${a}.`)) {
87
+ errors.push({ level: "error", rule: "leaves-only", detail: `id "${a}" is a namespace of "${b}" \u2014 namespaces are never ${kind}` });
88
+ break;
89
+ }
90
+ }
91
+ }
92
+ };
93
+ leavesOnly(actionUniverse, "actions");
94
+ if (universes.layouts !== void 0) leavesOnly(universes.layouts, "variants");
95
+ for (const [role, def] of Object.entries(charter)) {
96
+ if (Array.isArray(def)) continue;
97
+ if (def.actions !== void 0 && (def.allow !== void 0 || def.deny !== void 0)) {
98
+ errors.push({ level: "error", rule: "ambiguous-selection", detail: `role "${role}" has both top-level allow/deny and an "actions" section \u2014 one selection per section` });
99
+ }
100
+ }
101
+ for (const section of sections) {
102
+ for (const [role, def] of Object.entries(charter)) {
103
+ const { allow, deny } = normalizeRole(def, section);
104
+ for (const glob of deny) {
105
+ if (matchAll([glob], universeOf[section]).size === 0) {
106
+ errors.push({ level: "error", rule: "dead-deny", detail: `role "${role}" denies "${glob}" (${section}) which matches nothing \u2014 silent means unprotected` });
107
+ }
108
+ }
109
+ for (const glob of allow) {
110
+ if (matchAll([glob], universeOf[section]).size === 0) {
111
+ warnings.push({ level: "warning", rule: "dead-allow", detail: `role "${role}" allows "${glob}" (${section}) which matches nothing` });
112
+ }
113
+ }
114
+ }
115
+ }
116
+ const orphans = (section, kind) => {
117
+ const reachable = /* @__PURE__ */ new Set();
118
+ for (const set of resolved[section].values()) for (const id of set) reachable.add(id);
119
+ for (const id of universeOf[section]) {
120
+ if (!reachable.has(id)) warnings.push({ level: "warning", rule: "orphan", detail: `${kind} "${id}" is granted by no role \u2014 deployed but unreachable` });
121
+ }
122
+ };
123
+ orphans("actions", "action");
124
+ if (universes.layouts !== void 0) orphans("layouts", "layout variant");
125
+ const ancestorDenied = (role, section, seen = /* @__PURE__ */ new Set()) => {
126
+ const out = /* @__PURE__ */ new Set();
127
+ const def = charter[role];
128
+ if (def === void 0 || seen.has(role)) return out;
129
+ seen.add(role);
130
+ for (const parent of normalizeRole(def, section).extends) {
131
+ const parentDef = charter[parent];
132
+ if (parentDef === void 0) continue;
133
+ for (const id of matchAll(normalizeRole(parentDef, section).deny, universeOf[section])) out.add(id);
134
+ for (const id of ancestorDenied(parent, section, seen)) out.add(id);
135
+ }
136
+ return out;
137
+ };
138
+ for (const section of sections) {
139
+ for (const [role, set] of resolved[section]) {
140
+ for (const id of ancestorDenied(role, section)) {
141
+ if (set.has(id)) {
142
+ warnings.push({ level: "warning", rule: "re-allow", detail: `role "${role}" re-allows "${id}" (${section}) which an ancestor denied` });
143
+ }
144
+ }
145
+ }
146
+ }
147
+ const subtractive = /* @__PURE__ */ new Set();
148
+ for (const def of Object.values(charter)) {
149
+ if (Array.isArray(def)) continue;
150
+ for (const sub of def.without ?? []) subtractive.add(sub);
151
+ }
152
+ const worn = new Set(wearable.flat());
153
+ for (const role of subtractive) {
154
+ if (worn.has(role)) {
155
+ warnings.push({ level: "warning", rule: "subtractive-assigned", detail: `role "${role}" is referenced in "without" but is also assigned to a principal` });
156
+ }
157
+ }
158
+ for (const role of Object.keys(charter)) {
159
+ const actions = [...resolved.actions.get(role) ?? []].sort();
160
+ const data = [...resolved.data.get(role) ?? []].sort();
161
+ const layouts = [...resolved.layouts.get(role) ?? []].sort();
162
+ const issues = closure?.(actions, layouts) ?? [];
163
+ perRole.push({ role, actions, data, layouts, issues });
164
+ }
165
+ return { errors, warnings, perRole };
166
+ };
167
+
168
+ exports.CharterError = CharterError;
169
+ exports.matchAll = matchAll;
170
+ exports.matchGlob = matchGlob;
171
+ exports.normalizeRole = normalizeRole;
172
+ exports.resolvePrincipal = resolvePrincipal;
173
+ exports.resolveRole = resolveRole;
174
+ exports.resolveScoping = resolveScoping;
175
+ exports.verifyCharter = verifyCharter;
176
+ //# sourceMappingURL=index.cjs.map
177
+ //# sourceMappingURL=index.cjs.map