@nmnmcc/ability 0.2.0 → 1.0.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.
Files changed (58) hide show
  1. package/README.md +462 -454
  2. package/dist/Authorizer.d.ts +241 -0
  3. package/dist/Authorizer.d.ts.map +1 -0
  4. package/dist/Authorizer.js +340 -0
  5. package/dist/Authorizer.js.map +1 -0
  6. package/dist/Condition.d.ts +915 -0
  7. package/dist/Condition.d.ts.map +1 -0
  8. package/dist/Condition.js +1123 -0
  9. package/dist/Condition.js.map +1 -0
  10. package/dist/Decision.d.ts +131 -0
  11. package/dist/Decision.d.ts.map +1 -0
  12. package/dist/Decision.js +83 -0
  13. package/dist/Decision.js.map +1 -0
  14. package/dist/Domain.d.ts +158 -0
  15. package/dist/Domain.d.ts.map +1 -0
  16. package/dist/Domain.js +76 -0
  17. package/dist/Domain.js.map +1 -0
  18. package/dist/HttpApi.d.ts +173 -0
  19. package/dist/HttpApi.d.ts.map +1 -0
  20. package/dist/HttpApi.js +185 -0
  21. package/dist/HttpApi.js.map +1 -0
  22. package/dist/Policy.d.ts +687 -0
  23. package/dist/Policy.d.ts.map +1 -0
  24. package/dist/Policy.js +1339 -0
  25. package/dist/Policy.js.map +1 -0
  26. package/dist/Principal.d.ts +35 -0
  27. package/dist/Principal.d.ts.map +1 -0
  28. package/dist/Principal.js +37 -0
  29. package/dist/Principal.js.map +1 -0
  30. package/dist/Resource.d.ts +364 -0
  31. package/dist/Resource.d.ts.map +1 -0
  32. package/dist/Resource.js +844 -0
  33. package/dist/Resource.js.map +1 -0
  34. package/dist/Rule.d.ts +275 -0
  35. package/dist/Rule.d.ts.map +1 -0
  36. package/dist/Rule.js +257 -0
  37. package/dist/Rule.js.map +1 -0
  38. package/dist/_virtual/_rolldown/runtime.js +1 -2
  39. package/dist/index.d.ts +9 -3
  40. package/dist/index.js +9 -3
  41. package/package.json +61 -72
  42. package/src/Authorizer.ts +894 -0
  43. package/src/Condition.ts +2997 -0
  44. package/src/Decision.ts +117 -0
  45. package/src/Domain.ts +246 -0
  46. package/src/HttpApi.ts +348 -0
  47. package/src/Policy.ts +3315 -0
  48. package/src/Principal.ts +41 -0
  49. package/src/Resource.ts +1805 -0
  50. package/src/Rule.ts +683 -0
  51. package/src/index.ts +57 -0
  52. package/dist/Ability.d.ts +0 -491
  53. package/dist/Ability.js +0 -207
  54. package/dist/AbilityExtra.d.ts +0 -79
  55. package/dist/AbilityExtra.js +0 -187
  56. package/dist/internal/ability.d.ts +0 -90
  57. package/dist/internal/ability.js +0 -550
  58. package/dist/internal/serializable.js +0 -22
package/README.md CHANGED
@@ -1,581 +1,589 @@
1
1
  # @nmnmcc/ability
2
2
 
3
- Authorization primitives for Effect programs, backed by CASL's rule engine.
3
+ Authorization tools for Effect programs. Authorization means the work of
4
+ deciding if a principal may do an act. A principal is the one who asks: a
5
+ person, a user token, or a Bot.
4
6
 
5
- This package models authorization checks as `Effect` values and keeps failures
6
- in the typed error channel, while preserving the familiar CASL rule model:
7
- actions, subjects, fields, conditions, allow rules, and deny rules.
7
+ The library is made with [Effect](https://effect.website) only:
8
+
9
+ - Resources and principals are Schema classes. The types of rules, conditions
10
+ and checks all come from them.
11
+ - A condition is plain data. You can test it on a value, make it smaller with
12
+ the principal, change it into a database query, and keep it as JSON.
13
+ - A policy is a tree. Lists of rules are its leaves, and you put policies
14
+ together with `all`, `any`, `firstOf` and `ceiling`.
15
+ - An `Authorizer` is an Effect service. A "no" goes into the error channel. When
16
+ a policy can not be loaded, the check fails, so an error is never a "yes".
8
17
 
9
18
  ## Requirements
10
19
 
11
- - TypeScript projects should use strict type checking to get the full public API
12
- guarantees.
13
- - `effect` and `@casl/ability` are peer dependencies.
14
- - CASL APIs are not re-exported. Import official CASL helpers directly from
15
- `@casl/ability`.
20
+ - Use strict type checking. Without it, the types do not give all of their
21
+ safety.
22
+ - `effect` is a peer dependency. Your project must install it.
16
23
 
17
- ## Installation
24
+ ## Install
18
25
 
19
26
  ```sh
20
- yarn add @nmnmcc/ability effect @casl/ability
27
+ pnpm add @nmnmcc/ability effect
21
28
  ```
22
29
 
23
30
  ## Overview
24
31
 
25
- The main entry point is the following import:
26
-
27
32
  ```ts
28
- import {Ability, AbilityExtra} from "@nmnmcc/ability"
33
+ import {
34
+ Authorizer,
35
+ Condition,
36
+ Decision,
37
+ Domain,
38
+ Policy,
39
+ Principal,
40
+ Resource,
41
+ Rule,
42
+ } from "@nmnmcc/ability"
43
+ import * as AbilityHttpApi from "@nmnmcc/ability/HttpApi"
29
44
  ```
30
45
 
31
- | Concept | Description |
32
- | ------- | ----------- |
33
- | `Ability` | An immutable, ordered set of authorization rules. |
34
- | `Rule` | A yieldable allow or deny rule recorded by `Ability.define`. |
35
- | `Ability.define` | Synchronously builds an `Ability` from a generator DSL. |
36
- | `Ability.check` | The authorization decision API. It succeeds with `void` or fails through the Effect error channel. |
37
- | `Ability.subject` | Wraps a plain object with an explicit subject name without mutating the object. |
38
- | `AbilityExtra` | Helpers for compact rule transport and rule-to-query transforms. |
39
-
40
- Important behavior:
41
-
42
- - Last matching rule wins.
43
- - `manage` means any action.
44
- - `all` means any subject.
45
- - Checks do not return booleans. Use Effect combinators to derive booleans when
46
- needed.
47
-
48
- ## Getting Started
49
-
50
- Define your domain subjects as a type-level map:
51
-
52
- ```ts
53
- import {Effect} from "effect"
54
- import {Ability} from "@nmnmcc/ability"
55
-
56
- interface Post {
57
- readonly id: string
58
- readonly authorId: string
59
- readonly published: boolean
60
- readonly title: string
61
- readonly body: string
62
- }
46
+ | Module | What it is |
47
+ | ------------ | --------------------------------------------------------------------------- |
48
+ | `Resource` | A kind of thing to act on, with its actions, its Schema, and a path. |
49
+ | `Principal` | The Schema of the one who asks. |
50
+ | `Domain` | The principal and all the resources. Every other type comes from it. |
51
+ | `Condition` | A test on a resource value, as plain data. |
52
+ | `Rule` | An allow rule or a deny rule. |
53
+ | `Policy` | A tree of rules that gives a decision, a residual condition, and fields. |
54
+ | `Decision` | `Allow`, `Deny` or `NotApplicable`. |
55
+ | `Authorizer` | An Effect service that checks the principal of the current request. |
56
+ | `HttpApi` | Annotations and a middleware for `effect/http-api`. A separate entry point. |
63
57
 
64
- type Subjects = {
65
- readonly Post: Post
66
- }
67
- ```
58
+ ## First Steps
68
59
 
69
- Define an ability synchronously:
60
+ Make the principal and the resources. `Resource.Class` works in the same way as
61
+ `Schema.TaggedClass`. The class is a Schema, a constructor, and a resource at
62
+ the same time:
70
63
 
71
64
  ```ts
72
- const ability = Ability.define<Subjects>()(function* (ability) {
73
- yield* ability.allow("read", "Post")
74
-
75
- yield* ability.allow("update", "Post", {
76
- fields: ["title", "body"],
77
- conditions: {authorId: "u1"},
78
- reason: "Authors can edit their own content"
79
- })
80
-
81
- yield* ability.deny("delete", "Post", {
82
- conditions: {published: true},
83
- reason: "Published posts cannot be deleted"
84
- })
85
- })
65
+ import { Effect, Schema } from "effect"
66
+ import { Decision, Domain, Policy, Principal, Resource } from "@nmnmcc/ability"
67
+
68
+ class User extends Principal.Class<User>("User")({
69
+ id: Schema.String,
70
+ }) {}
71
+
72
+ class Post extends Resource.Class<Post>()("Post", {
73
+ actions: ["read", "update", "delete"],
74
+ fields: {
75
+ id: Schema.String,
76
+ authorId: Schema.String,
77
+ published: Schema.Boolean,
78
+ title: Schema.String,
79
+ body: Schema.String,
80
+ },
81
+ }) {}
82
+
83
+ const Blog = Domain.make({ principal: User, resources: [Post] })
86
84
  ```
87
85
 
88
- Check permissions inside an Effect program:
86
+ Make a policy. Each `yield*` gives one rule. The function runs at once and gives
87
+ back the policy:
89
88
 
90
89
  ```ts
91
- const post: Post = {
92
- id: "p1",
93
- authorId: "u1",
94
- published: true,
95
- title: "Hello",
96
- body: "World"
97
- }
98
-
99
- const program = Effect.gen(function* () {
100
- yield* Ability.check(ability, {
101
- action: "update",
102
- subject: "Post",
103
- value: post,
104
- field: "title"
105
- })
106
-
107
- const deleteResult = yield* Ability.check(ability, {
108
- action: "delete",
109
- subject: "Post",
110
- value: post
111
- }).pipe(
112
- Effect.match({
113
- onFailure: (error) =>
114
- error._tag === "AuthorizationError" ? error.reason : "unexpected failure",
115
- onSuccess: () => "deleted"
116
- })
117
- )
118
-
119
- return deleteResult
90
+ const policy = Policy.define(Blog)(function* (_) {
91
+ yield* _.allow("read", Post)
92
+
93
+ yield* _.allow("update", Post, {
94
+ fields: ["title", "body"],
95
+ when: ($) => $.eq("authorId", $.principal("id")),
96
+ reason: "Writers may change their own posts",
97
+ })
98
+
99
+ yield* _.deny("delete", Post, {
100
+ when: ($) => $.eq("published", true),
101
+ reason: "No one may delete a published post",
102
+ })
120
103
  })
121
104
  ```
122
105
 
123
- ## Defining Rules
124
-
125
- **Syntax**
126
-
127
- ```ts
128
- Ability.define<Subjects>()(
129
- function* (ability) {
130
- yield* ability.allow(action, subject, options)
131
- yield* ability.deny(action, subject, options)
132
- },
133
- options
134
- )
135
- ```
136
-
137
- `Ability.define` returns an `Ability` directly. It is not wrapped in `Effect`.
138
- The yielded `Rule` values are collected in order and stored immutably.
106
+ The types check every name. `_.allow("fly", Post)` is a type error, because
107
+ `fly` is not an action of `Post`. `$.eq("authorId", 5)` is a type error, because
108
+ `authorId` is a string. `$.principal("name")` is a type error, because the
109
+ principal has no `name` field.
139
110
 
140
- **Example** (Multiple Actions)
111
+ Get a decision:
141
112
 
142
113
  ```ts
143
- const ability = Ability.define<Subjects>()(function* (ability) {
144
- yield* ability.allow(["read", "update"], "Post", {
145
- fields: ["title", "body"],
146
- conditions: {authorId: "u1"}
147
- })
114
+ const writer = User.make({ id: "u1" })
115
+ const post = Post.make({
116
+ id: "p1",
117
+ authorId: "u1",
118
+ published: true,
119
+ title: "Hello",
120
+ body: "World",
148
121
  })
149
- ```
150
-
151
- **Example** (`manage` and `all`)
152
122
 
153
- ```ts
154
- const ability = Ability.define<Subjects>()(function* (ability) {
155
- yield* ability.allow("manage", "all")
156
- yield* ability.deny("delete", "Post", {
157
- conditions: {published: true},
158
- reason: "Published posts cannot be deleted"
159
- })
123
+ const decision = Policy.decideSync(policy, {
124
+ principal: writer,
125
+ action: "delete",
126
+ resource: post,
160
127
  })
161
- ```
162
-
163
- Rules are resolved from the end of the rule list. In the example above, the
164
- later `deny("delete", "Post")` can override the earlier `allow("manage", "all")`
165
- when its condition matches.
166
-
167
- ## Checking Permissions
168
-
169
- **Syntax**
170
128
 
171
- ```ts
172
- Ability.check(ability, request)
173
- ability.pipe(Ability.check(request))
174
- ```
175
-
176
- `Ability.check` returns:
177
-
178
- ```ts
179
- Effect.Effect<void, Ability.AuthorizationError | Ability.ConditionError | Ability.SubjectDetectionError>
180
- ```
181
-
182
- - Success means the request is authorized.
183
- - `AuthorizationError` means no allow rule matched, or the winning rule was a
184
- deny rule.
185
- - `ConditionError` means condition matching threw while evaluating a rule.
186
- - `SubjectDetectionError` means the request did not provide a subject and the
187
- subject could not be detected from the value.
188
-
189
- **Example** (Boolean Derived From Effect)
190
-
191
- ```ts
192
- const canUpdateTitle = yield* Ability.check(ability, {
193
- action: "update",
194
- subject: "Post",
195
- value: post,
196
- field: "title"
197
- }).pipe(
198
- Effect.match({
199
- onFailure: () => false,
200
- onSuccess: () => true
201
- })
202
- )
129
+ decision._tag // "Deny"
130
+ Decision.reason(decision) // "No one may delete a published post"
203
131
  ```
204
132
 
205
- There is no synchronous `can`, `cannot`, or `allows` API in this package.
133
+ ## Resources
206
134
 
207
- ## Conditions And Fields
135
+ A resource has a kind name, a list of actions, and Schema fields. Every value
136
+ has a `_tag` field with the kind name. The library uses `_tag` to find the
137
+ resource of a value.
208
138
 
209
- Conditions use CASL's Mongo-style matcher and `MongoQuery` type.
210
-
211
- **Example** (Mongo-Style Conditions)
139
+ There are two ways to make a resource:
212
140
 
213
141
  ```ts
214
- interface Comment {
215
- readonly authorId: string
216
- readonly body: string
217
- }
218
-
219
- interface PostWithComments extends Post {
220
- readonly comments: ReadonlyArray<Comment>
142
+ // A Schema class. Its body may have its own getters and methods.
143
+ class Bot extends Resource.Class<Bot>()("Bot", {
144
+ actions: ["read", "update"],
145
+ fields: { id: Schema.String, ownerUserId: Schema.NullOr(Schema.String) },
146
+ }) {
147
+ get shared() {
148
+ return this.ownerUserId === null
149
+ }
221
150
  }
222
151
 
223
- type Subjects = {
224
- readonly Post: PostWithComments
225
- }
226
-
227
- const ability = Ability.define<Subjects>()(function* (ability) {
228
- yield* ability.allow("read", "Post", {
229
- conditions: {
230
- published: {$eq: false},
231
- comments: {$elemMatch: {authorId: "u1"}}
232
- }
233
- })
152
+ // Plain objects with a `_tag` field.
153
+ const Trigger = Resource.make("Trigger", {
154
+ actions: ["read", "write"],
155
+ fields: { id: Schema.String, enabled: Schema.Boolean },
234
156
  })
157
+ const trigger = Trigger.make({ id: "t1", enabled: true })
235
158
  ```
236
159
 
237
- Fields are typed as dot paths, with bounded recursion for predictable
238
- type-checking. CASL-style field patterns are also accepted.
239
-
240
- **Example** (Field Restrictions)
160
+ A resource may have a path. The path puts the resource in a tree, so one rule
161
+ can cover a part of the tree:
241
162
 
242
163
  ```ts
243
- interface Address {
244
- readonly city: string
245
- readonly street: string
246
- }
247
-
248
- interface PostWithAddress extends Post {
249
- readonly address: Address
250
- }
251
-
252
- type Subjects = {
253
- readonly Post: PostWithAddress
254
- }
255
-
256
- const ability = Ability.define<Subjects>()(function* (ability) {
257
- yield* ability.allow("update", "Post", {
258
- fields: ["title", "address.**"],
259
- conditions: {authorId: "u1"}
260
- })
261
- })
262
-
263
- const post = {} as PostWithAddress
264
-
265
- yield* Ability.check(ability, {
266
- action: "update",
267
- subject: "Post",
268
- value: post,
269
- field: "address.city"
164
+ class Bot extends Resource.Class<Bot>()("Bot", {
165
+ actions: ["read", "update"],
166
+ fields: {
167
+ id: Schema.String,
168
+ organizationId: Schema.String,
169
+ ownerUserId: Schema.NullOr(Schema.String),
170
+ },
171
+ path: (f) => ["org", f.organizationId, "user", f.ownerUserId, "bot", f.id],
172
+ }) {}
173
+
174
+ // Every resource of the organization of the principal.
175
+ _.allow("read", "*", {
176
+ when: ($) => $.under("org", $.principal("organizationId")),
270
177
  })
271
178
  ```
272
179
 
273
- When you check a request without `value`, conditional allow rules can still
274
- authorize the action for the subject type. Pass `value` when you need object
275
- conditions to be evaluated for a specific resource. Conditional deny rules also
276
- need a value before their conditions can match; unconditional deny rules still
277
- apply without a value.
180
+ ## Rules
181
+
182
+ - `_.allow(action, resource, options)` and `_.deny(...)` make rules. The action
183
+ and the resource may be lists.
184
+ - The action `"*"` means every action. The resource `"*"` means every resource.
185
+ - `when` is the condition. It gets a builder with the types of the resource.
186
+ - `fields` makes the rule about some fields only. `*` stands for any part of one
187
+ field name, and `**` for any number of parts, also none: `settings.*` covers
188
+ `settings.model`, and `**.secret` covers `secret` and `settings.secret`.
189
+ - `reason`, `id` and `meta` are kept with the rule. `meta` is extra data, such
190
+ as the scope of a grant. Give its Schema to `Domain.make({ meta })`.
191
+
192
+ An allow rule with fields covers a request for the whole value: "may update some
193
+ fields" is a yes. This is true only for a kind that has one of these fields. A
194
+ deny rule with fields does not stop a request for the whole value.
195
+
196
+ To know if a kind has a field that a pattern fits, the library walks the Schema
197
+ of the kind: its fields, the keys of its records, and the getters of its
198
+ classes. For some key Schemas it can only try sample keys, so it may not find a
199
+ field that is there. Then the answer for the whole value is "no", never a wrong
200
+ "yes".
201
+
202
+ ## Conditions
203
+
204
+ The builder in `when` has these functions:
205
+
206
+ | Function | True when |
207
+ | ------------------------ | ------------------------------------------------- |
208
+ | `eq`, `ne` | The field is (not) equal to the value. |
209
+ | `lt`, `lte`, `gt`, `gte` | The field is less or greater. Numbers or strings. |
210
+ | `in` | The field is equal to one of the values. |
211
+ | `exists` | The field is not `null` and not missing. |
212
+ | `under(...prefix)` | The path of the resource starts with the prefix. |
213
+ | `and`, `or`, `not` | Logic. |
214
+ | `principal(field)` | Not a test. It gives a field of the principal. |
215
+ | `predicate(name, test)` | The test function says yes. It may be an Effect. |
216
+
217
+ A missing field of a resource has the value `null`. A field of the principal
218
+ that is `null` or missing is different: a test with it is always false, also
219
+ with `ne`. So a guest with no `userId` never matches a Bot with no owner. To
220
+ test for `null`, use a fixed value, as in `$.eq("ownerUserId", null)`.
221
+
222
+ `predicate` is the one way out of plain data. Its test may give a boolean or an
223
+ `Effect`. The error type and the service type of the `Effect` go into the types
224
+ of the policy and of every check. A policy with a predicate can not become JSON
225
+ or a query, and the type system stops you when you try.
226
+
227
+ A predicate also keeps the types of the value and the principal that it reads.
228
+ So a predicate for a Bot can not go into a rule for a Trigger. Make conditions
229
+ with the builder: a node made by hand is not a condition in the types.
230
+
231
+ ## Policies
232
+
233
+ A list of rules has a combining algorithm. It decides which rule gives the
234
+ answer when more than one rule applies:
235
+
236
+ | Algorithm | Winner |
237
+ | ------------------------- | ---------------------------------------- |
238
+ | `denyOverrides` (default) | A deny rule wins over every allow rule. |
239
+ | `permitOverrides` | An allow rule wins over every deny rule. |
240
+ | `firstApplicable` | The first rule that applies. |
241
+ | `lastApplicable` | The last rule that applies. |
278
242
 
279
- ## Permitted Fields
243
+ ```ts
244
+ const policy = Policy.define(Blog, { algorithm: "lastApplicable" })(
245
+ function* (_) {
246
+ // ...
247
+ },
248
+ )
249
+ ```
280
250
 
281
- Use `Ability.permittedFields` to derive the request fields allowed by matching
282
- rules. Allow rules add fields; deny rules remove fields.
251
+ Put policies together:
283
252
 
284
- **Syntax**
253
+ | Combinator | Decision |
254
+ | ----------------------------- | ---------------------------------------------------------------- |
255
+ | `Policy.all([a, b])` | Every policy must allow. One deny is enough to deny. |
256
+ | `Policy.any([a, b])` | One allow is enough. |
257
+ | `Policy.firstOf([a, b])` | The first policy that allows or denies. |
258
+ | `Policy.ceiling(policy, cap)` | A deny from `cap` always wins. An allow from `cap` does nothing. |
285
259
 
286
- ```ts
287
- Ability.permittedFields(ability, request, {
288
- fieldsFrom: (rule) => rule.fields ?? fallbackFields
289
- })
290
- ```
260
+ A policy tree may have at most 256 levels. A combinator throws an error for a
261
+ deeper tree, and the policy Schema does not decode one. A deeper tree could fill
262
+ the stack of a check. The JSON form of a policy may have at most 1000 levels of
263
+ objects and arrays, so a deep input fails to decode before it fills the stack. A
264
+ field path may have at most 256 parts.
291
265
 
292
- **Example**
266
+ For example, a user token may never do more than its member, and the platform
267
+ has deny rules for everyone:
293
268
 
294
269
  ```ts
295
- const fields = yield* Ability.permittedFields(
296
- ability,
297
- {
298
- action: "update",
299
- subject: "Post",
300
- value: post
301
- },
302
- {
303
- fieldsFrom: (rule) => rule.fields ?? ["id", "authorId", "published", "title", "body"]
304
- }
270
+ const forToken = Policy.all([memberPolicy, tokenPolicy]).pipe(
271
+ Policy.ceiling(platformPolicy),
305
272
  )
306
273
  ```
307
274
 
308
- `fieldsFrom` is used when a matching rule does not declare explicit fields.
275
+ A decision is one of three answers: `Allow`, `Deny`, or `NotApplicable`, when no
276
+ rule gives an answer. A check treats `NotApplicable` as a "no", but an
277
+ authorizer with a decider asks the decider first.
309
278
 
310
- ## Subjects
279
+ ## Questions to a Policy
311
280
 
312
- A check request can provide the subject name explicitly:
281
+ | Function | Answer |
282
+ | ------------------------ | -------------------------------------------------------------- |
283
+ | `Policy.decide` | The decision for one resource value, as an `Effect`. |
284
+ | `Policy.decideSync` | The same, at once. Only for policies with no predicates. |
285
+ | `Policy.explain` | The decision and the rules that were tested, for an audit log. |
286
+ | `Policy.residual` | The condition on resource values that the policy allows. |
287
+ | `Policy.coverage` | If the policy allows all, none or some of a part of a kind. |
288
+ | `Policy.permittedFields` | The fields of a value that the policy lets a request use. |
313
289
 
314
- ```ts
315
- yield* Ability.check(ability, {
316
- action: "read",
317
- subject: "Post",
318
- value: post
319
- })
320
- ```
290
+ `Policy.residual` puts the principal into every rule and gives a condition on
291
+ the resource fields only. It is `True` when the policy allows every value of the
292
+ kind, and `False` when it allows none. Use it to ask "may this principal do this
293
+ act on some value of this kind?", or to make a database query.
321
294
 
322
- You can also wrap a value with a subject name:
295
+ When a rule that the request may use has a predicate, the residual is one
296
+ predicate with the name `"policy"`. It runs the whole policy for each value, so
297
+ it gives the same answers and the same failures as `Policy.decide`.
323
298
 
324
- ```ts
325
- const wrapped = Ability.subject("Post", post)
299
+ A deep policy tree may give a very large residual. When it would have more than
300
+ 10000 nodes, `Policy.residual` throws an error, and a check in an `Authorizer`
301
+ fails. It throws an error too when a rule that the request may use reads a
302
+ getter of a class: the read may fail when the policy runs, and a smaller
303
+ condition could leave it out.
326
304
 
327
- yield* Ability.check(ability, {
328
- action: "read",
329
- value: wrapped
330
- })
305
+ ### Scopes
331
306
 
332
- const original = Ability.unwrapSubject(wrapped)
333
- ```
307
+ A scope is a part of a kind, such as the posts of one writer. Give it as
308
+ `within`, with the same builder as the condition of a rule. A scope is plain
309
+ data: it may not have a predicate.
334
310
 
335
- `Ability.subject` is pure and does not mutate the wrapped object.
311
+ There are three questions about a scope. Each one is a question about two sets:
312
+ the values in the scope, and the values that the policy allows.
336
313
 
337
- If neither `subject` nor a typed subject wrapper is provided, configure subject
338
- detection:
314
+ | Question | Sets | Function |
315
+ | -------------------------------------- | ------------------- | ------------------------------- |
316
+ | May the principal act on every value? | scope ⊆ allowed | `Policy.coverage` is `All` |
317
+ | Which values may the principal act on? | scope ∩ allowed | `Policy.residual` |
318
+ | May the principal act on some value? | scope ∩ allowed ≠ ∅ | `Policy.coverage` is not `None` |
339
319
 
340
320
  ```ts
341
- const ability = Ability.define<Subjects>()(
342
- function* (ability) {
343
- yield* ability.allow("read", "Post")
344
- },
345
- {
346
- detectSubjectType: (value) => (value as {readonly __typename: "Post"}).__typename
347
- }
348
- )
349
-
350
- yield* Ability.check(ability, {
351
- action: "read",
352
- value: {
353
- ...post,
354
- __typename: "Post"
355
- }
356
- })
321
+ const ownPosts = {
322
+ principal: writer,
323
+ action: "update",
324
+ kind: "Post",
325
+ within: ($) => $.eq("authorId", $.principal("id")),
326
+ } satisfies Policy.KindRequest<typeof Blog>
327
+
328
+ Policy.coverage(policy, ownPosts)._tag // "All"
329
+ Policy.residual(policy, ownPosts) // authorId = "u1"
357
330
  ```
358
331
 
359
- Without a custom detector, subject detection falls back to constructor metadata
360
- when available.
361
-
362
- ## Action Aliases
363
-
364
- Action aliases expand one rule action into additional checkable actions.
365
-
366
- **Example**
332
+ Use "every value" for an act on a value that does not exist yet. A new post has
333
+ no id, but its author is known, so a check on the scope of its author tells if
334
+ the writer may make it.
335
+
336
+ `Policy.coverage` gives one of four answers. Each one has `condition`, the exact
337
+ list query for the scope:
338
+
339
+ - `All`: the policy allows every value in the scope.
340
+ - `None`: the policy allows no value in the scope. An empty scope is `None` too,
341
+ so a scope with a mistake never gives a "yes".
342
+ - `Some`: the policy allows some values and not others. It gives an example of
343
+ each, `allowed` and `refused`.
344
+ - `Unknown`: the policy has a predicate, a condition tests a field that is not a
345
+ plain scalar, or the search went past its budget.
346
+
347
+ The answer is exact. Each test in a condition compares one field with fixed
348
+ values, so these values cut the values of the field into a few parts, and every
349
+ value in one part gives the same answer. `Condition.satisfiable` tries one value
350
+ from each part, one field at a time. It takes the values of each field from the
351
+ Schema of the resource: its literals, `null` for a nullable or optional field,
352
+ and finite or integer numbers. It does not know other Schema checks, such as a
353
+ minimum length, so a field with such a check is not plain (see below).
354
+
355
+ The search answers only for plain scalar fields: a string, a number, a boolean,
356
+ a literal, `null`, or an optional field or a union of these, with no checks
357
+ other than finite and integer checks, on a path of required fields of plain
358
+ structs. For another field, such as a class, a record, a union of structs, a
359
+ date or a field of `Schema.declare`, a value may have data that the Schema does
360
+ not show, so the answer is `Unknown`. A check on a kind then says no.
361
+ `Resource.isPlainField` tells if a field is plain. This is true for each rule
362
+ that the request may use, also for a test that a smaller condition leaves out: a
363
+ read of a field that is not plain, such as a getter, may fail in a check.
364
+
365
+ A "yes" also needs a value of the whole kind, so each required field of the kind
366
+ must surely have values, also a field that the condition does not test. A
367
+ required field with a check other than finite and integer checks, such as a
368
+ minimum length, may have no value, so then the answer is `Unknown` in place of
369
+ `All` or `Some`. `Resource.hasValue` tells if a Schema surely has a value.
370
+
371
+ "Some" means that some value of the Schema is allowed. It does not mean that
372
+ such a value is in your database. To know that, run the condition as a query.
373
+
374
+ ## Queries
375
+
376
+ Change a residual condition into a query with `Condition.fold`. You give one
377
+ function for each kind of node:
367
378
 
368
379
  ```ts
369
- const ability = Ability.define<Subjects>()(
370
- function* (ability) {
371
- yield* ability.allow("modify", "Post", {
372
- fields: ["title", "body"],
373
- conditions: {authorId: "u1"}
374
- })
375
- },
376
- {
377
- actionAliases: {
378
- modify: ["update", "delete"]
379
- } as const
380
- }
381
- )
380
+ const toSql = Condition.fold<string>({
381
+ true: () => "TRUE",
382
+ false: () => "FALSE",
383
+ compare: (op, field, value) => `${field} ${sqlOperator(op)} ${quote(value)}`,
384
+ in: (field, values) => `${field} IN (${values.map(quote).join(", ")})`,
385
+ exists: (field) => `${field} IS NOT NULL`,
386
+ and: (parts) => `(${parts.join(" AND ")})`,
387
+ or: (parts) => `(${parts.join(" OR ")})`,
388
+ not: (part) => `NOT ${part}`,
389
+ })
382
390
 
383
- yield* Ability.check(ability, {
384
- action: "update",
385
- subject: "Post",
386
- value: post,
387
- field: "title"
391
+ const program = Effect.gen(function* () {
392
+ const where = yield* toSql(
393
+ Policy.residual(policy, { principal, action: "read", kind: "Post" }),
394
+ )
388
395
  })
389
396
  ```
390
397
 
391
- Aliases are one-directional. A `modify` rule matches `update` and `delete`, but
392
- separate `update` and `delete` rules do not imply `modify`.
398
+ `fold` fails with `Untranslatable` on a predicate, unless you give a `predicate`
399
+ function too. Take care with `null`: in this library `ne` is true when the field
400
+ is `null`, but in SQL `x <> 'a'` is not true when `x` is `NULL`. Use
401
+ `IS DISTINCT FROM` or a similar form. Give the values to the database as bound
402
+ parameters. A value from a principal may have a quote in it, and in the SQL text
403
+ it could change the query. `examples/openbot-rbac.ts` shows how.
393
404
 
394
- Invalid aliases fail fast:
405
+ ## JSON
395
406
 
396
- - `manage` cannot be used as an alias name.
397
- - Aliases cannot target `manage`.
398
- - Aliases cannot target an empty list.
399
- - Cyclic aliases are rejected.
407
+ A policy with no predicates can become JSON:
400
408
 
401
- ## Raw Rules And Updates
409
+ ```ts
410
+ const PolicySchema = Policy.schema(Blog)
402
411
 
403
- Raw rules are JSON-safe data structures.
412
+ const json = Schema.encodeSync(PolicySchema)(policy)
413
+ const again = Schema.decodeUnknownSync(PolicySchema)(json)
414
+ ```
404
415
 
405
- **Syntax**
416
+ Decoding checks every kind, action, field and principal field against the
417
+ domain, and `meta` against the `meta` Schema of the domain. So a policy from a
418
+ database can not name a field that does not exist.
406
419
 
407
- ```ts
408
- Ability.fromRawRules<Subjects>(rules, options)
409
- Ability.toRawRules(ability)
410
- Ability.update(ability, rules)
411
- ability.pipe(Ability.update(rules))
412
- ```
420
+ ## Authorizer
413
421
 
414
- **Example**
422
+ An authorizer is an Effect service. It gets the principal of the current
423
+ request, loads its policy, and keeps the policy in a cache.
415
424
 
416
425
  ```ts
417
- const ability = yield* Ability.fromRawRules<Subjects>([
418
- {
419
- action: "read",
420
- subject: "Post",
421
- conditions: {authorId: "u1"}
422
- },
423
- {
424
- action: "delete",
425
- subject: "Post",
426
- inverted: true,
427
- reason: "No deletes"
428
- }
429
- ])
426
+ class Identity extends Context.Service<Identity, User>()("app/Identity") {}
430
427
 
431
- const rules = yield* Ability.toRawRules(ability)
428
+ class Auth extends Authorizer.Service<Auth, { requires: Identity }>()(
429
+ "app/Auth",
430
+ Blog,
431
+ ) {}
432
432
 
433
- const nextAbility = yield* Ability.update(ability, [
434
- {
435
- action: "read",
436
- subject: "Post"
437
- }
438
- ])
433
+ const AuthLive = Authorizer.layer(Auth, {
434
+ principal: Identity,
435
+ policy: (user) => loadPolicyOf(user),
436
+ cache: { capacity: 1000, timeToLive: "30 seconds" },
437
+ })
439
438
  ```
440
439
 
441
- `Ability.update` returns a new immutable ability and reuses the current ability
442
- options, including action aliases and subject detection.
440
+ Two principals with the same data get one policy from the cache. So the loader
441
+ must decide by the data of the principal only. When it tests that an object of
442
+ the principal is a given object, as `role === admin` does, give `cache: false`.
443
443
 
444
- `Ability.fromRawRules` and `Ability.update` can fail with:
445
-
446
- - `RawRuleError` for invalid raw rules.
447
- - `AliasError` for invalid action alias configuration.
448
-
449
- ## Introspection
450
-
451
- The introspection helpers are also Effect values and support data-first and
452
- data-last usage.
453
-
454
- | Function | Behavior |
455
- | -------- | -------- |
456
- | `Ability.possibleRulesFor` | Returns rules that may apply before field and condition checks. |
457
- | `Ability.rulesFor` | Returns rules that may apply after field checks, but before condition checks. |
458
- | `Ability.relevantRuleFor` | Returns the winning rule after field and condition checks. |
459
- | `Ability.actionsFor` | Returns actions that have rules for a subject. |
460
-
461
- **Example**
444
+ Use it in a handler:
462
445
 
463
446
  ```ts
464
- const rules = yield* Ability.rulesFor(ability, {
465
- action: "update",
466
- subject: "Post",
467
- field: "title"
468
- })
469
-
470
- const rule = yield* Ability.relevantRuleFor(ability, {
471
- action: "delete",
472
- subject: "Post",
473
- value: post
447
+ const handler = Effect.gen(function* () {
448
+ yield* Auth.check({ action: "update", resource: post })
449
+ yield* Auth.check({ action: "read", kind: "Post" })
450
+ yield* Auth.guard(
451
+ { action: "update", resource: post },
452
+ {
453
+ hide: () => PostNotFound.make({ id: post.id }),
454
+ },
455
+ )
456
+ const where = yield* Auth.filter({ action: "read", kind: "Post" })
457
+ // A new post of the writer: every post of this author may be made.
458
+ yield* Auth.check({
459
+ action: "update",
460
+ kind: "Post",
461
+ within: ($) => $.eq("authorId", $.principal("id")),
462
+ })
463
+ const covered = yield* Auth.coverage({ action: "delete", kind: "Post" })
464
+ const showDeleteButton = covered._tag !== "None"
474
465
  })
475
-
476
- const actions = yield* ability.pipe(
477
- Ability.actionsFor({
478
- subject: "Post"
479
- })
480
- )
481
466
  ```
482
467
 
483
- `possibleRulesFor`, `rulesFor`, and `actionsFor` can fail with
484
- `SubjectDetectionError`. `relevantRuleFor` can also fail with `ConditionError`.
468
+ | Function | What it does |
469
+ | ----------------- | ----------------------------------------------------------------------------- |
470
+ | `check` | Succeeds with `void`, or fails with `Forbidden`. |
471
+ | `guard` | Fails with your error when the principal may not read the value, then checks. |
472
+ | `filter` | Gives the residual condition, for a list query. |
473
+ | `coverage` | Tells if the principal may act on all, none or some values in a scope. |
474
+ | `decide` | Gives the decision. It does not fail on a "no". |
475
+ | `permittedFields` | Gives the fields that the principal may use. |
476
+ | `invalidate` | Removes a cached policy, after a change to the rules of a principal. |
485
477
 
486
- ## AbilityExtra
478
+ A check on a kind (`{ action, kind }`) passes only when the policy allows the
479
+ act on every value of the kind. With `within`, it passes only when the policy
480
+ allows the act on every value in the scope, and the scope is not empty. The
481
+ decider is asked only when no value in the scope is denied.
487
482
 
488
- `AbilityExtra` works with already-defined abilities and JSON-safe rules.
483
+ `filter` gives `False` when the principal may act on no value. Then the list is
484
+ empty, and that is not an error.
489
485
 
490
- ### Compact Rule Transport
486
+ The errors of a check:
491
487
 
492
- ```ts
493
- import {AbilityExtra} from "@nmnmcc/ability"
488
+ - `Forbidden`: the policy says no. It has the action, the kind, the field, and
489
+ the reason of the rule.
490
+ - `PolicyUnavailable`: the policy could not be loaded. It keeps the cause.
491
+ - `Pending`: the decider must wait for an answer. It has a `ticket`.
494
492
 
495
- const packed = AbilityExtra.packRules(rules)
496
- const unpacked = AbilityExtra.unpackRules(packed)
497
- ```
493
+ ### Deciders
498
494
 
499
- `packRules` converts raw rules into compact tuples. `unpackRules` restores the
500
- raw rule objects.
501
-
502
- ### Default Fields From Conditions
503
-
504
- `rulesToFields` extracts scalar condition values from matching allow rules. This
505
- is useful when creating initial values from authorization rules.
495
+ When no rule gives an answer, the authorizer asks the decider, if there is one.
496
+ A decider may answer at once, or fail with `Pending` when a person or a Bot must
497
+ answer later:
506
498
 
507
499
  ```ts
508
- const defaults = yield* AbilityExtra.rulesToFields(ability, {
509
- action: "read",
510
- subject: "Post"
500
+ Authorizer.layer(Auth, {
501
+ principal: Identity,
502
+ policy: loadPolicyOf,
503
+ decider: (request) =>
504
+ requests
505
+ .create(request)
506
+ .pipe(Effect.flatMap((ticket) => Authorizer.Pending.make({ ticket }))),
511
507
  })
512
508
  ```
513
509
 
514
- For a rule with `{conditions: {authorId: "u1"}}`, the returned object includes
515
- `{authorId: "u1"}`.
510
+ When the answer comes, keep it as a rule, for example in a grant policy that
511
+ comes first: `Policy.firstOf([grants, rules])`.
516
512
 
517
- ### Rule-To-Query Conversion
513
+ ## HttpApi
518
514
 
519
- Use `rulesToCondition` when you own the logical query representation:
515
+ `@nmnmcc/ability/HttpApi` checks requests in an `effect/http-api` server. Each
516
+ endpoint says what it needs. An endpoint with no annotation is closed, so a new
517
+ endpoint does nothing until you say what it needs:
520
518
 
521
519
  ```ts
522
- const condition = yield* AbilityExtra.rulesToCondition(
523
- ability,
524
- {
525
- action: "read",
526
- subject: "Post"
527
- },
528
- (rule) => rule.conditions ?? {},
529
- {
530
- and: (conditions) => ({$and: conditions}),
531
- or: (conditions) => ({$or: conditions}),
532
- not: (condition) => ({$not: condition}),
533
- empty: () => ({})
534
- }
535
- )
536
- ```
537
-
538
- Use `rulesToQuery` for the built-in generic logical shape:
520
+ import * as AbilityHttpApi from "@nmnmcc/ability/HttpApi"
521
+
522
+ class Authorization extends HttpApiMiddleware.Service<
523
+ Authorization,
524
+ { requires: Identity }
525
+ >()("app/Authorization", { error: AbilityHttpApi.errors }) {}
526
+
527
+ const update = HttpApiEndpoint.patch("update", "/posts/:id", {
528
+ params: { id: Schema.String },
529
+ }).annotate(AbilityHttpApi.Required, [
530
+ AbilityHttpApi.requires(Auth, "update", "Post", (params) =>
531
+ Posts.find(params["id"]),
532
+ ),
533
+ ])
539
534
 
540
- ```ts
541
- const query = yield* ability.pipe(
542
- AbilityExtra.rulesToQuery(
543
- {
544
- action: "read",
545
- subject: "Post"
546
- },
547
- (rule) => rule.conditions ?? {}
548
- )
535
+ const health = HttpApiEndpoint.get("health", "/health").annotate(
536
+ AbilityHttpApi.Required,
537
+ [],
549
538
  )
550
- ```
551
-
552
- Rule conversion callbacks may return plain values or Effects. If a conversion
553
- callback throws, the helper fails with `QueryGenerationError`.
554
539
 
555
- ## CASL Peer Dependency
540
+ // The checks run only in a group that uses the middleware.
541
+ const posts = HttpApiGroup.make("posts")
542
+ .add(update, health)
543
+ .middleware(Authorization)
556
544
 
557
- This package uses the official CASL rule engine for indexing and Mongo-style
558
- condition matching, but it does not re-export CASL APIs.
545
+ const AuthorizationLive = AbilityHttpApi.layer(Authorization, Auth)
546
+ ```
559
547
 
560
- Import CASL APIs from `@casl/ability` when you need them:
548
+ An act on a part of a kind takes a scope from the path parameters. A list takes
549
+ `lists`: the middleware does not check every value, because the handler gets its
550
+ query with `Auth.filter`, with the same scope. An empty list is not an error,
551
+ unless you give `nonEmpty: true`. Then the middleware needs a coverage of `All`
552
+ or `Some`, so `Unknown` fails too:
561
553
 
562
554
  ```ts
563
- import {AbilityBuilder, createMongoAbility, subject} from "@casl/ability"
555
+ const create = HttpApiEndpoint.post("create", "/users/:user/posts", {
556
+ params: { user: Schema.String },
557
+ }).annotate(AbilityHttpApi.Required, [
558
+ AbilityHttpApi.requires(Auth, "update", "Post", {
559
+ within: (params) => ($) => $.eq("authorId", params["user"] ?? ""),
560
+ }),
561
+ ])
564
562
 
565
- const {can, cannot, build} = new AbilityBuilder(createMongoAbility)
563
+ const list = HttpApiEndpoint.get("list", "/users/:user/posts", {
564
+ params: { user: Schema.String },
565
+ }).annotate(AbilityHttpApi.Required, [
566
+ AbilityHttpApi.lists(Auth, "read", "Post", {
567
+ within: (params) => ($) => $.eq("authorId", params["user"] ?? ""),
568
+ }),
569
+ ])
570
+ ```
566
571
 
567
- can("read", "Post")
568
- cannot("delete", "Post", {published: true})
572
+ A path parameter may be `undefined`. A scope with `undefined` in it is a defect,
573
+ so give another value for it.
569
574
 
570
- const caslAbility = build()
571
- const canRead = caslAbility.can("read", subject("Post", post))
572
- ```
575
+ The annotations and the layer do nothing alone. Give the middleware to every
576
+ group with `.middleware(Authorization)`, or to the whole API. An endpoint in a
577
+ group without the middleware is not checked.
573
578
 
574
- ORM adapters and `accessibleBy`-style helpers are not implemented here. Use the
575
- official CASL ecosystem packages for those integrations.
579
+ `GroupRequired` gives a default for a whole group: one list for GET requests and
580
+ one for every other method. `AbilityHttpApi.errors` gives the errors with HTTP
581
+ status codes: 403, 503, and 409.
576
582
 
577
583
  ## Examples
578
584
 
579
- - [examples/basic.ts](./examples/basic.ts)
580
- - [examples/advanced.ts](./examples/advanced.ts)
581
- - [tests/Ability.test.ts](./tests/Ability.test.ts)
585
+ ```sh
586
+ node examples/basic.ts
587
+ node examples/authorizer.ts
588
+ node examples/openbot-rbac.ts
589
+ ```