@protobase/schema 0.0.0-stage → 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/LICENSE +202 -0
- package/dist/access/capability.d.ts +10 -0
- package/dist/access/capability.js +30 -0
- package/dist/access/combine.js +39 -0
- package/dist/access/index.d.ts +8 -0
- package/dist/access/pick-view.d.ts +8 -0
- package/dist/access/pick-view.js +11 -0
- package/dist/access/resolve.d.ts +61 -0
- package/dist/access/resolve.js +150 -0
- package/dist/access/restrict.d.ts +16 -0
- package/dist/access/restrict.js +37 -0
- package/dist/access/roles.d.ts +30 -0
- package/dist/access/roles.js +55 -0
- package/dist/access/rule.d.ts +11 -0
- package/dist/access/rule.js +9 -0
- package/dist/access/types.d.ts +37 -0
- package/dist/enum-label.d.ts +4 -0
- package/dist/enum-label.js +5 -0
- package/dist/field.d.ts +69 -0
- package/dist/field.js +85 -0
- package/dist/fields/bigint.js +12 -0
- package/dist/fields/boolean.js +9 -0
- package/dist/fields/country.js +9 -0
- package/dist/fields/currency.js +9 -0
- package/dist/fields/date.js +9 -0
- package/dist/fields/decimal.js +22 -0
- package/dist/fields/enum.js +12 -0
- package/dist/fields/integer.js +14 -0
- package/dist/fields/json.js +9 -0
- package/dist/fields/relation.js +9 -0
- package/dist/fields/text.js +19 -0
- package/dist/fields/timestamp.js +9 -0
- package/dist/fields/uuid.js +9 -0
- package/dist/fields.d.ts +23 -0
- package/dist/fields.js +49 -0
- package/dist/filter/check-field.js +25 -0
- package/dist/filter/check-model.js +123 -0
- package/dist/filter/check-value.js +64 -0
- package/dist/filter/check.d.ts +16 -0
- package/dist/filter/check.js +22 -0
- package/dist/filter/datetime.js +33 -0
- package/dist/filter/duration.js +16 -0
- package/dist/filter/errors.js +29 -0
- package/dist/filter/evaluate.d.ts +12 -0
- package/dist/filter/evaluate.js +33 -0
- package/dist/filter/index.d.ts +7 -0
- package/dist/filter/lift.js +107 -0
- package/dist/filter/lower.js +170 -0
- package/dist/filter/operators.js +26 -0
- package/dist/filter/order-by.d.ts +23 -0
- package/dist/filter/order-by.js +51 -0
- package/dist/filter/parse.d.ts +20 -0
- package/dist/filter/parse.js +28 -0
- package/dist/filter/print.d.ts +5 -0
- package/dist/filter/print.js +7 -0
- package/dist/filter/profile.js +69 -0
- package/dist/filter/where.d.ts +58 -0
- package/dist/filter/where.js +121 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +21 -0
- package/dist/keys.d.ts +12 -0
- package/dist/keys.js +57 -0
- package/dist/layout.d.ts +12 -0
- package/dist/layout.js +21 -0
- package/dist/model.d.ts +333 -0
- package/dist/naming.js +4 -0
- package/dist/nav-recent.d.ts +8 -0
- package/dist/nav-recent.js +37 -0
- package/dist/refs.d.ts +11 -0
- package/dist/refs.js +8 -0
- package/dist/relation-field.d.ts +6 -0
- package/dist/relation-field.js +12 -0
- package/dist/resource-model.d.ts +15 -0
- package/dist/resource-model.js +71 -0
- package/dist/resource-types.d.ts +21 -0
- package/dist/resource.d.ts +47 -0
- package/dist/resource.js +97 -0
- package/dist/search-match.d.ts +29 -0
- package/dist/search-match.js +50 -0
- package/dist/user-menu.d.ts +25 -0
- package/dist/user-menu.js +32 -0
- package/dist/view-actions.d.ts +24 -0
- package/dist/view-actions.js +35 -0
- package/dist/view-field.d.ts +16 -0
- package/dist/view-field.js +39 -0
- package/dist/view-widgets.d.ts +16 -0
- package/dist/view-widgets.js +24 -0
- package/dist/view.d.ts +69 -0
- package/dist/view.js +109 -0
- package/package.json +31 -3
- package/README.md +0 -3
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.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/access/capability.d.ts
|
|
2
|
+
export type CapabilityAction = 'read' | 'create' | 'update' | 'delete';
|
|
3
|
+
export type CapabilityScope = 'own' | 'team';
|
|
4
|
+
/**
|
|
5
|
+
* `<resource|area>.<action>[.<scope>]` with `*` wildcards, or `*` alone. Pass the names as the
|
|
6
|
+
* type parameter of `defineRoles` to make unknown names compile-time errors.
|
|
7
|
+
*/
|
|
8
|
+
export type Capability<Name extends string = string> = '*' | `${Name | '*'}.${CapabilityAction | '*'}` | `${Name | '*'}.${CapabilityAction | '*'}.${CapabilityScope | '*'}`;
|
|
9
|
+
export type Grant = 'all' | CapabilityScope;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/access/capability.ts
|
|
2
|
+
const pattern = /^(\*|[A-Za-z][A-Za-z0-9_]*)\.(\*|read|create|update|delete)(?:\.(\*|own|team))?$/;
|
|
3
|
+
/** Parses and validates a capability string; throws on anything that is not one. */
|
|
4
|
+
const parseCapability = (capability) => {
|
|
5
|
+
if (capability === "*") return {
|
|
6
|
+
name: "*",
|
|
7
|
+
action: "*"
|
|
8
|
+
};
|
|
9
|
+
const match = pattern.exec(capability);
|
|
10
|
+
if (!match) throw new Error(`Invalid capability "${capability}": expected <resource|area>.<read|create|update|delete|*>[.<own|team|*>] or "*"`);
|
|
11
|
+
return {
|
|
12
|
+
name: match[1],
|
|
13
|
+
action: match[2],
|
|
14
|
+
scope: match[3]
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
const matches = (pattern, value) => pattern === "*" || pattern === value;
|
|
18
|
+
/**
|
|
19
|
+
* The scopes with which `held` grants `wanted`'s resource and action. An unscoped (or `.*`)
|
|
20
|
+
* capability grants everything; `.own` and `.team` narrow to rows.
|
|
21
|
+
*/
|
|
22
|
+
const grantsOf = (held, wanted) => {
|
|
23
|
+
const have = parseCapability(held);
|
|
24
|
+
if (!matches(have.name, wanted.name) && wanted.name !== "*") return [];
|
|
25
|
+
if (!matches(have.action, wanted.action) && wanted.action !== "*") return [];
|
|
26
|
+
if (have.scope === void 0 || have.scope === "*") return ["all"];
|
|
27
|
+
return [have.scope];
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { grantsOf, parseCapability };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { parseFilter } from "../filter/parse.js";
|
|
2
|
+
import { createWhere } from "../filter/where.js";
|
|
3
|
+
//#region src/access/combine.ts
|
|
4
|
+
const span = {
|
|
5
|
+
start: 0,
|
|
6
|
+
end: 0
|
|
7
|
+
};
|
|
8
|
+
/** Turns an access result into a verdict or a `FilterExpr`. */
|
|
9
|
+
const normalize = (result) => {
|
|
10
|
+
if (typeof result !== "string") return result;
|
|
11
|
+
const parsed = parseFilter(result);
|
|
12
|
+
if (!parsed.ok || !parsed.ast) throw new Error(`Access rule returned an invalid filter "${result}": ${parsed.errors[0]?.message ?? "empty"}`);
|
|
13
|
+
return parsed.ast;
|
|
14
|
+
};
|
|
15
|
+
const andResults = (a, b) => {
|
|
16
|
+
const [x, y] = [normalize(a), normalize(b)];
|
|
17
|
+
if (x === false || y === false) return false;
|
|
18
|
+
if (x === true) return y;
|
|
19
|
+
if (y === true) return x;
|
|
20
|
+
return {
|
|
21
|
+
kind: "and",
|
|
22
|
+
args: [x, y],
|
|
23
|
+
span
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
const orResults = (a, b) => {
|
|
27
|
+
const [x, y] = [normalize(a), normalize(b)];
|
|
28
|
+
if (x === true || y === true) return true;
|
|
29
|
+
if (x === false) return y;
|
|
30
|
+
if (y === false) return x;
|
|
31
|
+
return {
|
|
32
|
+
kind: "or",
|
|
33
|
+
args: [x, y],
|
|
34
|
+
span
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
const where = createWhere();
|
|
38
|
+
//#endregion
|
|
39
|
+
export { andResults, normalize, orResults, where };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { AccessAction, AccessContext, AccessFn, AccessResult, AccessUser, FieldAccess, FieldRule } from "./types.js";
|
|
2
|
+
import { Capability, CapabilityAction, CapabilityScope } from "./capability.js";
|
|
3
|
+
import { Rule, rule } from "./rule.js";
|
|
4
|
+
import { Roles, RolesOptions, defineRoles } from "./roles.js";
|
|
5
|
+
import { pickView } from "./pick-view.js";
|
|
6
|
+
import { AccessSource, ResolveOptions, ResolvedAccess, RowFilterOperation, accessWarnings, checkRecord, fieldsUsedBy, resolveAccess } from "./resolve.js";
|
|
7
|
+
import { restrictModel } from "./restrict.js";
|
|
8
|
+
export { type AccessAction, type AccessContext, type AccessFn, type AccessResult, type AccessSource, type AccessUser, type Capability, type CapabilityAction, type CapabilityScope, type FieldAccess, type FieldRule, type ResolveOptions, type ResolvedAccess, type Roles, type RolesOptions, type RowFilterOperation, type Rule, accessWarnings, checkRecord, defineRoles, fieldsUsedBy, pickView, resolveAccess, restrictModel, rule };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { ViewModel } from "../model.js";
|
|
2
|
+
//#region src/access/pick-view.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Picks the view for a user: the first role-specific view whose roles intersect the user's,
|
|
5
|
+
* otherwise the default view (one without roles). With `resource`, only that resource's views count.
|
|
6
|
+
*/
|
|
7
|
+
export declare const pickView: (views: readonly ViewModel[], roles: readonly string[], resource?: string) => ViewModel | undefined;
|
|
8
|
+
//#endregion
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/access/pick-view.ts
|
|
2
|
+
/**
|
|
3
|
+
* Picks the view for a user: the first role-specific view whose roles intersect the user's,
|
|
4
|
+
* otherwise the default view (one without roles). With `resource`, only that resource's views count.
|
|
5
|
+
*/
|
|
6
|
+
const pickView = (views, roles, resource) => {
|
|
7
|
+
const candidates = resource === void 0 ? views : views.filter((view) => view.resource === resource);
|
|
8
|
+
return candidates.find((view) => view.roles?.some((role) => roles.includes(role))) ?? candidates.find((view) => !view.roles?.length);
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { pickView };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { CheckedFilter, ResourceModel } from "../model.js";
|
|
2
|
+
import { AccessAction, AccessContext, AccessFn, FieldAccess } from "./types.js";
|
|
3
|
+
import { EvaluateOptions } from "../filter/evaluate.js";
|
|
4
|
+
import "../filter/index.js";
|
|
5
|
+
import { Rule } from "./rule.js";
|
|
6
|
+
//#region src/access/resolve.d.ts
|
|
7
|
+
/** What the resolver needs from a resource; `ResourceBuilder` satisfies it. */
|
|
8
|
+
export type AccessSource = {
|
|
9
|
+
toModel: () => ResourceModel;
|
|
10
|
+
accessRules: Partial<Record<AccessAction, AccessFn>>;
|
|
11
|
+
fieldAccess: () => Record<string, FieldAccess>;
|
|
12
|
+
};
|
|
13
|
+
export type ResolveOptions = {
|
|
14
|
+
/**
|
|
15
|
+
* The project's roles. When given, an operation without a rule is denied unless the user's
|
|
16
|
+
* roles grant `<resource>.<action>` (so admin's `*` still passes). Fields without a rule
|
|
17
|
+
* follow their resource.
|
|
18
|
+
*/
|
|
19
|
+
roles?: {
|
|
20
|
+
can: (capability: any) => Rule;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Overrides what an operation without a rule does. Without `roles` the default is `allow`,
|
|
24
|
+
* the single-admin case; with `roles` it is the capability check above. Choosing `allow`
|
|
25
|
+
* together with `roles` is an explicit opt-in, see `accessWarnings`.
|
|
26
|
+
*/
|
|
27
|
+
defaultAccess?: 'allow' | 'deny';
|
|
28
|
+
};
|
|
29
|
+
/** Startup warnings for risky option combinations; the caller decides how to report them. */
|
|
30
|
+
export declare const accessWarnings: (options: ResolveOptions) => string[];
|
|
31
|
+
export type RowFilterOperation = 'read' | 'create' | 'update' | 'delete';
|
|
32
|
+
export type ResolvedAccess = {
|
|
33
|
+
operations: Record<AccessAction, boolean>;
|
|
34
|
+
/** Operations whose rule needs the record (or input); check them with `checkRecord`. */
|
|
35
|
+
recordChecks: AccessAction[];
|
|
36
|
+
/** Columns the caller may see; everything else must be left out of results, filters, sorts and search. */
|
|
37
|
+
readableFields: string[];
|
|
38
|
+
writableFields: {
|
|
39
|
+
create: string[];
|
|
40
|
+
update: string[];
|
|
41
|
+
};
|
|
42
|
+
/** ANDed into queries (`read` covers list and read) or checked against records (`create`). */
|
|
43
|
+
rowFilter: Partial<Record<RowFilterOperation, CheckedFilter>>;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Resolves everything a request may do with a resource: operations, row filters, readable and
|
|
47
|
+
* writable columns. Pure with respect to the database; downstream code applies the result
|
|
48
|
+
* and must not re-decide access.
|
|
49
|
+
*/
|
|
50
|
+
export declare const resolveAccess: (source: AccessSource, ctx: Omit<AccessContext, "model" | "operation"> & {
|
|
51
|
+
user: NonNullable<AccessContext["user"]>;
|
|
52
|
+
}, options?: ResolveOptions) => Promise<ResolvedAccess>;
|
|
53
|
+
/**
|
|
54
|
+
* Record-level check for an operation: runs the rule with the record (and input) and evaluates
|
|
55
|
+
* a returned filter against it. Creates are checked against the input, other operations
|
|
56
|
+
* against the existing record.
|
|
57
|
+
*/
|
|
58
|
+
export declare const checkRecord: (source: AccessSource, ctx: Omit<AccessContext, "model" | "operation" | "record">, operation: AccessAction, record: Record<string, unknown> | undefined, input?: Record<string, unknown>, options?: ResolveOptions & EvaluateOptions) => Promise<boolean>;
|
|
59
|
+
/** Names of the fields a checked filter refers to, so callers can reject filters on unreadable columns. */
|
|
60
|
+
export declare const fieldsUsedBy: (filter: CheckedFilter) => string[];
|
|
61
|
+
//#endregion
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { checkFilter } from "../filter/check.js";
|
|
2
|
+
import { evaluateFilter } from "../filter/evaluate.js";
|
|
3
|
+
import { andResults, normalize } from "./combine.js";
|
|
4
|
+
//#region src/access/resolve.ts
|
|
5
|
+
/** Startup warnings for risky option combinations; the caller decides how to report them. */
|
|
6
|
+
const accessWarnings = (options) => options.roles && options.defaultAccess === "allow" ? ["Roles are configured but defaultAccess is \"allow\": operations without an access rule are open to every user."] : [];
|
|
7
|
+
const operations = [
|
|
8
|
+
"read",
|
|
9
|
+
"list",
|
|
10
|
+
"create",
|
|
11
|
+
"update",
|
|
12
|
+
"delete"
|
|
13
|
+
];
|
|
14
|
+
const ruleFor = (source, model, operation, options) => {
|
|
15
|
+
const explicit = source.accessRules[operation] ?? (operation === "list" ? source.accessRules.read : void 0);
|
|
16
|
+
if (explicit) return explicit;
|
|
17
|
+
if (options.defaultAccess) return options.defaultAccess === "allow";
|
|
18
|
+
if (!options.roles) return true;
|
|
19
|
+
return options.roles.can(`${model.name}.${operation === "list" ? "read" : operation}`);
|
|
20
|
+
};
|
|
21
|
+
const checked = (model, expr, operation) => {
|
|
22
|
+
const trusted = {
|
|
23
|
+
...model,
|
|
24
|
+
fields: Object.fromEntries(Object.entries(model.fields).map(([name, field]) => [name, {
|
|
25
|
+
...field,
|
|
26
|
+
filterable: true
|
|
27
|
+
}]))
|
|
28
|
+
};
|
|
29
|
+
const result = checkFilter(trusted, expr);
|
|
30
|
+
if (!result.ok) throw new Error(`The ${operation} access rule of "${model.name}" returned an invalid filter: ${result.errors[0].message}`);
|
|
31
|
+
return result.filter;
|
|
32
|
+
};
|
|
33
|
+
const decide = async (rule, ctx) => {
|
|
34
|
+
try {
|
|
35
|
+
return normalize(await rule(ctx));
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (error instanceof TypeError) return "record";
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const verdict = async (rule, ctx, fallback, what) => {
|
|
42
|
+
if (!rule) return fallback;
|
|
43
|
+
const result = normalize(await rule(ctx));
|
|
44
|
+
if (typeof result !== "boolean") throw new Error(`${what} must be role-based and return a boolean; a row filter (.own, .team) cannot apply to a column`);
|
|
45
|
+
return result;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Resolves everything a request may do with a resource: operations, row filters, readable and
|
|
49
|
+
* writable columns. Pure with respect to the database; downstream code applies the result
|
|
50
|
+
* and must not re-decide access.
|
|
51
|
+
*/
|
|
52
|
+
const resolveAccess = async (source, ctx, options = {}) => {
|
|
53
|
+
const model = source.toModel();
|
|
54
|
+
const allowed = {};
|
|
55
|
+
const recordChecks = [];
|
|
56
|
+
const filters = {};
|
|
57
|
+
for (const operation of operations) {
|
|
58
|
+
if (operation === "list" && !source.accessRules.list) {
|
|
59
|
+
allowed.list = allowed.read;
|
|
60
|
+
if (recordChecks.includes("read")) recordChecks.push("list");
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const rule = ruleFor(source, model, operation, options);
|
|
64
|
+
const decision = typeof rule === "boolean" ? rule : await decide(rule, {
|
|
65
|
+
...ctx,
|
|
66
|
+
model,
|
|
67
|
+
operation
|
|
68
|
+
});
|
|
69
|
+
if (decision === "record") {
|
|
70
|
+
allowed[operation] = true;
|
|
71
|
+
recordChecks.push(operation);
|
|
72
|
+
} else if (typeof decision === "boolean") allowed[operation] = decision;
|
|
73
|
+
else {
|
|
74
|
+
allowed[operation] = true;
|
|
75
|
+
filters[operation] = decision;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const fieldRules = source.fieldAccess();
|
|
79
|
+
const fieldContext = (operation) => ({
|
|
80
|
+
...ctx,
|
|
81
|
+
model,
|
|
82
|
+
operation
|
|
83
|
+
});
|
|
84
|
+
const names = Object.keys(model.fields);
|
|
85
|
+
const readableFields = [];
|
|
86
|
+
const writable = {
|
|
87
|
+
create: [],
|
|
88
|
+
update: []
|
|
89
|
+
};
|
|
90
|
+
for (const name of names) {
|
|
91
|
+
const rules = fieldRules[name];
|
|
92
|
+
const field = model.fields[name];
|
|
93
|
+
if (allowed.list || allowed.read) {
|
|
94
|
+
if (await verdict(rules?.read, fieldContext("read"), true, `The read rule of field "${name}"`)) readableFields.push(name);
|
|
95
|
+
}
|
|
96
|
+
for (const operation of ["create", "update"]) {
|
|
97
|
+
if (!allowed[operation] || field.readOnly) continue;
|
|
98
|
+
if (await verdict(rules?.[operation], fieldContext(operation), true, `The ${operation} rule of field "${name}"`)) writable[operation].push(name);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const readFilter = filters.list && filters.read ? andResults(filters.list, filters.read) : filters.read ?? filters.list;
|
|
102
|
+
const rowFilter = {};
|
|
103
|
+
const byOperation = [
|
|
104
|
+
["read", readFilter],
|
|
105
|
+
["create", filters.create],
|
|
106
|
+
["update", filters.update],
|
|
107
|
+
["delete", filters.delete]
|
|
108
|
+
];
|
|
109
|
+
for (const [operation, filter] of byOperation) if (filter && typeof filter === "object") rowFilter[operation] = checked(model, filter, operation);
|
|
110
|
+
else if (filter === false) allowed[operation === "read" ? "read" : operation] = false;
|
|
111
|
+
return {
|
|
112
|
+
operations: allowed,
|
|
113
|
+
recordChecks,
|
|
114
|
+
readableFields,
|
|
115
|
+
writableFields: writable,
|
|
116
|
+
rowFilter
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Record-level check for an operation: runs the rule with the record (and input) and evaluates
|
|
121
|
+
* a returned filter against it. Creates are checked against the input, other operations
|
|
122
|
+
* against the existing record.
|
|
123
|
+
*/
|
|
124
|
+
const checkRecord = async (source, ctx, operation, record, input, options = {}) => {
|
|
125
|
+
const model = source.toModel();
|
|
126
|
+
const rule = ruleFor(source, model, operation, options);
|
|
127
|
+
if (typeof rule === "boolean") return rule;
|
|
128
|
+
const result = normalize(await rule({
|
|
129
|
+
...ctx,
|
|
130
|
+
model,
|
|
131
|
+
operation,
|
|
132
|
+
record
|
|
133
|
+
}, record, input));
|
|
134
|
+
if (typeof result === "boolean") return result;
|
|
135
|
+
const subject = operation === "create" ? input : record;
|
|
136
|
+
if (!subject) throw new Error(`Checking a ${operation} filter for "${model.name}" needs ${operation === "create" ? "the input" : "the record"}`);
|
|
137
|
+
return evaluateFilter(checked(model, result, operation), subject, options);
|
|
138
|
+
};
|
|
139
|
+
/** Names of the fields a checked filter refers to, so callers can reject filters on unreadable columns. */
|
|
140
|
+
const fieldsUsedBy = (filter) => {
|
|
141
|
+
switch (filter.kind) {
|
|
142
|
+
case "and":
|
|
143
|
+
case "or": return [...new Set(filter.args.flatMap(fieldsUsedBy))];
|
|
144
|
+
case "not": return fieldsUsedBy(filter.arg);
|
|
145
|
+
case "search": return [];
|
|
146
|
+
default: return [filter.field.name];
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
//#endregion
|
|
150
|
+
export { accessWarnings, checkRecord, fieldsUsedBy, resolveAccess };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ResourceModel } from "../model.js";
|
|
2
|
+
import { ResolvedAccess } from "./resolve.js";
|
|
3
|
+
//#region src/access/restrict.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The resource as one user may see it: only readable fields remain, and a field is `readOnly`
|
|
6
|
+
* unless it is writable on create or update. `search` (and `searchMatch`) shrinks to readable fields, and `tenant`,
|
|
7
|
+
* `softDelete` and `owner` are dropped when their field is hidden. Key columns always stay,
|
|
8
|
+
* because records are addressed by them.
|
|
9
|
+
*
|
|
10
|
+
* Use the restricted model for everything user-facing (checking filters, sorts, queries,
|
|
11
|
+
* OpenAPI, `/meta`), so hidden fields cannot be referenced at all. Row filters from access
|
|
12
|
+
* rules (`access.rowFilter`) are checked against the full model instead and kept separate:
|
|
13
|
+
* they may use hidden or non-filterable columns.
|
|
14
|
+
*/
|
|
15
|
+
export declare const restrictModel: (model: ResourceModel, access: Pick<ResolvedAccess, "readableFields" | "writableFields">) => ResourceModel;
|
|
16
|
+
//#endregion
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/access/restrict.ts
|
|
2
|
+
/**
|
|
3
|
+
* The resource as one user may see it: only readable fields remain, and a field is `readOnly`
|
|
4
|
+
* unless it is writable on create or update. `search` (and `searchMatch`) shrinks to readable fields, and `tenant`,
|
|
5
|
+
* `softDelete` and `owner` are dropped when their field is hidden. Key columns always stay,
|
|
6
|
+
* because records are addressed by them.
|
|
7
|
+
*
|
|
8
|
+
* Use the restricted model for everything user-facing (checking filters, sorts, queries,
|
|
9
|
+
* OpenAPI, `/meta`), so hidden fields cannot be referenced at all. Row filters from access
|
|
10
|
+
* rules (`access.rowFilter`) are checked against the full model instead and kept separate:
|
|
11
|
+
* they may use hidden or non-filterable columns.
|
|
12
|
+
*/
|
|
13
|
+
const restrictModel = (model, access) => {
|
|
14
|
+
const visible = /* @__PURE__ */ new Set([...access.readableFields, ...model.primaryKey]);
|
|
15
|
+
const writable = /* @__PURE__ */ new Set([...access.writableFields.create, ...access.writableFields.update]);
|
|
16
|
+
const keep = (name) => name !== void 0 && visible.has(name) ? name : void 0;
|
|
17
|
+
const search = model.search?.filter((name) => visible.has(name));
|
|
18
|
+
const searchMatch = model.searchMatch && Object.entries(model.searchMatch).filter(([name]) => visible.has(name));
|
|
19
|
+
const { search: _search, searchMatch: _searchMatch, tenant: _tenant, softDelete: _softDelete, owner: _owner, ...rest } = model;
|
|
20
|
+
const tenant = keep(model.tenant);
|
|
21
|
+
const softDelete = keep(model.softDelete);
|
|
22
|
+
const owner = keep(model.owner);
|
|
23
|
+
return {
|
|
24
|
+
...rest,
|
|
25
|
+
fields: Object.fromEntries(Object.entries(model.fields).filter(([name]) => visible.has(name)).map(([name, field]) => [name, {
|
|
26
|
+
...field,
|
|
27
|
+
readOnly: !writable.has(name)
|
|
28
|
+
}])),
|
|
29
|
+
...search?.length && { search },
|
|
30
|
+
...searchMatch?.length && { searchMatch: Object.fromEntries(searchMatch) },
|
|
31
|
+
...tenant && { tenant },
|
|
32
|
+
...softDelete && { softDelete },
|
|
33
|
+
...owner && { owner }
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { restrictModel };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { AccessUser } from "./types.js";
|
|
2
|
+
import { Capability, Grant } from "./capability.js";
|
|
3
|
+
import { Rule } from "./rule.js";
|
|
4
|
+
//#region src/access/roles.d.ts
|
|
5
|
+
export type RolesOptions = {
|
|
6
|
+
/** Ids of the users in `user`'s team; `.team` scopes become `owner IN teamOf(user)`. */
|
|
7
|
+
teamOf?: (user: AccessUser) => readonly (string | number)[] | Promise<readonly (string | number)[]>;
|
|
8
|
+
/** Resource and area names; when given, unknown names in capabilities throw at definition. */
|
|
9
|
+
names?: readonly string[];
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Defines roles as bundles of capability strings. Pass the resource and area names as the type
|
|
13
|
+
* parameter to reject unknown names at compile time:
|
|
14
|
+
* `defineRoles<'orders' | 'costs'>({ sales: ['orders.read.own'] })`.
|
|
15
|
+
*/
|
|
16
|
+
export declare const defineRoles: <Name extends string = string>(definitions: Record<string, readonly Capability<Name>[]>, options?: RolesOptions) => {
|
|
17
|
+
definitions: Record<string, readonly Capability<Name>[]>;
|
|
18
|
+
grants: (user: AccessUser, capability: string) => Set<Grant>;
|
|
19
|
+
/** Whether the user holds the capability at all, in any scope. For areas and field rules. */
|
|
20
|
+
has: (user: AccessUser, capability: Capability<Name>) => boolean;
|
|
21
|
+
/**
|
|
22
|
+
* A rule that allows when the user's roles grant the capability: `true` for an unscoped
|
|
23
|
+
* grant, a row filter for `.own` and `.team`, `false` otherwise.
|
|
24
|
+
*/
|
|
25
|
+
can: (capability: Capability<Name>) => Rule;
|
|
26
|
+
/** A rule that allows when the user has any of the roles. */
|
|
27
|
+
is: (...roles: string[]) => Rule;
|
|
28
|
+
};
|
|
29
|
+
export type Roles = ReturnType<typeof defineRoles>;
|
|
30
|
+
//#endregion
|