foldkit-guard 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -7
- package/dist/agent.d.mts +1 -1
- package/dist/{attach-BdHNdPNM.d.mts → attach-BVG6LsFf.d.mts} +71 -4
- package/dist/attach-BVG6LsFf.d.mts.map +1 -0
- package/dist/{attach-COgJIox7.mjs → attach-BZyVvs7H.mjs} +21 -6
- package/dist/attach-BZyVvs7H.mjs.map +1 -0
- package/dist/{condition-C6Czs2Xn.mjs → condition-Dunujvzy.mjs} +2 -2
- package/dist/{condition-C6Czs2Xn.mjs.map → condition-Dunujvzy.mjs.map} +1 -1
- package/dist/drizzle.d.mts +1 -1
- package/dist/drizzle.mjs +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +37 -6
- package/dist/index.mjs.map +1 -1
- package/dist/me-DeSZOGt3.mjs +40 -0
- package/dist/me-DeSZOGt3.mjs.map +1 -0
- package/dist/media.d.mts +30 -0
- package/dist/media.d.mts.map +1 -0
- package/dist/media.mjs +41 -0
- package/dist/media.mjs.map +1 -0
- package/dist/origin-CN6ThFTp.mjs +13 -0
- package/dist/origin-CN6ThFTp.mjs.map +1 -0
- package/dist/{placed-Bs_mnBTF.mjs → placed-CkyMqxFw.mjs} +4 -3
- package/dist/placed-CkyMqxFw.mjs.map +1 -0
- package/dist/server.d.mts +11 -1
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +34 -3
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +1 -1
- package/dist/sync.mjs +5 -5
- package/dist/sync.mjs.map +1 -1
- package/package.json +25 -15
- package/dist/attach-BdHNdPNM.d.mts.map +0 -1
- package/dist/attach-COgJIox7.mjs.map +0 -1
- package/dist/placed-Bs_mnBTF.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
# foldkit-guard
|
|
2
2
|
|
|
3
3
|
Who may do what, declared once on a Foldkit Plus domain, and enforced on every
|
|
4
|
-
path a row is read or written by.
|
|
5
|
-
explains the design and why.
|
|
4
|
+
path a row is read or written by.
|
|
6
5
|
|
|
7
6
|
## What it is
|
|
8
7
|
|
|
@@ -62,8 +61,8 @@ pnpm add effect foldkit-entity foldkit-guard
|
|
|
62
61
|
`foldkit-guard` is the shared declaration. Its subpaths bring their packages
|
|
63
62
|
as optional peers: `foldkit-guard/server` needs `foldkit-remote` and
|
|
64
63
|
`foldkit-remote-server`, `/drizzle` also `foldkit-remote-drizzle` and
|
|
65
|
-
`drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`,
|
|
66
|
-
`/agent` `foldkit-remote`.
|
|
64
|
+
`drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`,
|
|
65
|
+
`/agent` `foldkit-remote`, and `/media` `foldkit-media`.
|
|
67
66
|
|
|
68
67
|
## Sixty seconds
|
|
69
68
|
|
|
@@ -97,7 +96,7 @@ const G = Guards.declare(
|
|
|
97
96
|
isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),
|
|
98
97
|
inProject: guard.row(TodoFields, p => Expr.in(TodoFields.fields.projectId, p.projectIds)),
|
|
99
98
|
}),
|
|
100
|
-
{ key: user => user.id },
|
|
99
|
+
{ key: user => user.id, unguarded: 'deny' },
|
|
101
100
|
)
|
|
102
101
|
|
|
103
102
|
// Server: the body of every principal guard, and nothing else.
|
|
@@ -204,8 +203,9 @@ Guards.matrix([Todo])
|
|
|
204
203
|
- `Guards.guardFields(Todo, 'Read')` names the members a row interaction's
|
|
205
204
|
guards read, so a change to one is known to change who may.
|
|
206
205
|
- A surface with no guards on a guarded Entity falls to the set's
|
|
207
|
-
`unguarded
|
|
208
|
-
`
|
|
206
|
+
`unguarded`, which `declare` requires so the choice is written down:
|
|
207
|
+
`'deny'` refuses it (the matrix prints `closed`), `'allow'` lets everyone
|
|
208
|
+
(`open`).
|
|
209
209
|
|
|
210
210
|
## Deciding reads and writes
|
|
211
211
|
|
|
@@ -319,6 +319,33 @@ const TodoSource = source(Db.Todo, { filter: GuardServer.filter(Todo, Policy) })
|
|
|
319
319
|
- `visible` is the row's Read. Member and relation Reads are the Source's
|
|
320
320
|
`filter`, as `TodoSource` has it.
|
|
321
321
|
|
|
322
|
+
A body may need a service, a membership lookup say, and name it in its
|
|
323
|
+
Effect. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,
|
|
324
|
+
`GuardSync`) take a Policy that needs nothing more, since a read rule runs
|
|
325
|
+
inside a read whose requirements are the Source's. Provide the services once,
|
|
326
|
+
at startup; what changes with each request belongs in the principal:
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
class Memberships extends Context.Service<
|
|
330
|
+
Memberships,
|
|
331
|
+
{ readonly admins: ReadonlyArray<string> }
|
|
332
|
+
>()('app/Memberships') {}
|
|
333
|
+
|
|
334
|
+
const Checked = G.implement({
|
|
335
|
+
isAdmin: principal =>
|
|
336
|
+
Effect.map(Memberships, ({ admins }) =>
|
|
337
|
+
Option.exists(principal, user => admins.includes(user.id)),
|
|
338
|
+
),
|
|
339
|
+
})
|
|
340
|
+
const ReadPolicy = Checked.provide(Context.make(Memberships, { admins: ['ada'] }))
|
|
341
|
+
GuardDrizzle.visible(ReadPolicy, [Todo]) // a type error with `Checked`
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
A seam built from `ReadPolicy` counts as built from `Checked`, so
|
|
345
|
+
`GuardServer.validate(Checked, …)` accepts it: `validate` checks that a seam
|
|
346
|
+
runs the declared rules, not which services they were given. The write seams take the
|
|
347
|
+
Policy as it is and require its services where the write runs.
|
|
348
|
+
|
|
322
349
|
## Serving writes
|
|
323
350
|
|
|
324
351
|
A declared write (`Mutation.write`) is served by `RemoteServer.write` with no
|
|
@@ -515,6 +542,40 @@ May.canLink(row.may, Todo, 'project', 'Link')
|
|
|
515
542
|
- `foldkit-crud`'s editor locks the keys the reader may not set with
|
|
516
543
|
`locks: May.locks(Todo)`, for `foldkit-mixins-form`'s `locked`.
|
|
517
544
|
|
|
545
|
+
## Who the client is: `Me`
|
|
546
|
+
|
|
547
|
+
"Show the Admin link", "show a sign-in page rather than a 404" and "who am
|
|
548
|
+
I signed in as" are questions about the visitor, not about a row.
|
|
549
|
+
`Guards.me` declares them as one Entity with one row, `me`: everyone reads
|
|
550
|
+
their own and no one writes it. It holds `signedIn`, `key` (the principal's
|
|
551
|
+
`key`, `Option.none()` for a visitor) and `may` for the interactions named
|
|
552
|
+
here; `GuardServer.me` serves it, deciding `may` with the Policy.
|
|
553
|
+
|
|
554
|
+
```ts
|
|
555
|
+
const OpenAdmin = Interaction.make('OpenAdmin')
|
|
556
|
+
|
|
557
|
+
// Shared domain code, beside the other Entities.
|
|
558
|
+
export const Me = Guards.me(G, {
|
|
559
|
+
interactions: { [OpenAdmin.key]: [G.isAdmin] },
|
|
560
|
+
})
|
|
561
|
+
|
|
562
|
+
// The server: one Source among the others.
|
|
563
|
+
const MeSource = GuardServer.me(Me, Policy)
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
- The client reads `Me` through Remote like any row (`Entity.select(Me,
|
|
567
|
+
{ signedIn: true, key: true, may: true })`), so it is `Loading`, `Ready`
|
|
568
|
+
or stale as data is, survives SSR, and `Remote.forget` on any change of
|
|
569
|
+
principal (a sign-in as much as a sign-out) drops it. `May.can(me.may, OpenAdmin.key)` is the server's answer; no rule runs
|
|
570
|
+
on the client.
|
|
571
|
+
- Its Read is `Guards.anyone`, whatever the set leaves `unguarded`, and its
|
|
572
|
+
writes are nobody's, as the matrix prints them. `Guards.anyone` serves any
|
|
573
|
+
surface that is public under a set that denies the rest: a Read of it
|
|
574
|
+
restricts no one, so a Sync document over its rows needs no readers and
|
|
575
|
+
`validate` lets a Source share them.
|
|
576
|
+
- `may` is read with the row, as any `may` is: a principal whose role
|
|
577
|
+
changes sees it when `Me` is read again.
|
|
578
|
+
|
|
518
579
|
## When a rule refuses
|
|
519
580
|
|
|
520
581
|
| Cause | Server | Client |
|
|
@@ -634,6 +695,48 @@ has a `RequestedArchive` with the todo's `id`.
|
|
|
634
695
|
- It is the agent's gate, not the check: the Message's mutation is checked on
|
|
635
696
|
the server, under the same principal.
|
|
636
697
|
|
|
698
|
+
## Uploads
|
|
699
|
+
|
|
700
|
+
`foldkit-media`'s upload routes ask one question of an `UploadPolicy`
|
|
701
|
+
before reading a byte: may this request upload (`Upload`), or have an image
|
|
702
|
+
named by URL described (`DescribeUrl`)? `foldkit-guard/media` answers it with
|
|
703
|
+
principal guards, for who your resolver says is asking:
|
|
704
|
+
|
|
705
|
+
```ts
|
|
706
|
+
import { Layer } from 'effect'
|
|
707
|
+
import { uploadLayer, uploadsKeyValueStore } from 'foldkit-media/server'
|
|
708
|
+
import { GuardMedia } from 'foldkit-guard/media'
|
|
709
|
+
|
|
710
|
+
const uploads = uploadLayer().pipe(
|
|
711
|
+
Layer.provide(
|
|
712
|
+
Layer.mergeAll(
|
|
713
|
+
uploadsKeyValueStore(),
|
|
714
|
+
inspector,
|
|
715
|
+
GuardMedia.uploadPolicy(Policy, { resolve, Upload: [G.isAdmin], DescribeUrl: [G.isAdmin] }),
|
|
716
|
+
),
|
|
717
|
+
),
|
|
718
|
+
)
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
`resolve` is the resolver your Remote server is given:
|
|
722
|
+
`(request: Request) => Effect<Option<User>, E, R>`, which
|
|
723
|
+
`AuthServer.resolver` from `foldkit-auth/server` is. `inspector` is
|
|
724
|
+
`foldkit-media`'s `Inspector` for where you run (`inspectorSharp()`,
|
|
725
|
+
`inspectorImages(env.IMAGES)`).
|
|
726
|
+
|
|
727
|
+
- Only principal guards: no row exists before an upload, so a row guard is a
|
|
728
|
+
type error. A route admits when any one of its guards allows, and a route
|
|
729
|
+
given no guards admits nobody.
|
|
730
|
+
- The resolver gets the request's URL, method and headers and never its
|
|
731
|
+
body, so the route still reads no byte before the policy answers.
|
|
732
|
+
- A resolver that fails (an untrusted origin, a session that ended) is a
|
|
733
|
+
`401`; a principal the guards refuse is a `403`. Either says only its kind:
|
|
734
|
+
an `explain` sentence stays on the server.
|
|
735
|
+
- `Policy` must need no service; give it what its bodies need with
|
|
736
|
+
`Policy.provide`, as the other seams take it.
|
|
737
|
+
- Beside a deployment's secret for scripts:
|
|
738
|
+
`uploadPolicyAny(uploadPolicyBearer(secret), GuardMedia.uploadPolicy(…))`.
|
|
739
|
+
|
|
637
740
|
## Limits
|
|
638
741
|
|
|
639
742
|
- **No rule runs on the client.** `may` is the server's answer for the row as
|
package/dist/agent.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { j as MayAnswer, l as InteractionKey } from "./attach-BVG6LsFf.mjs";
|
|
2
2
|
import { RemoteData } from "foldkit-remote";
|
|
3
3
|
//#region src/agent.d.ts
|
|
4
4
|
/** A row read with `may`, as `Data.get(Row, id).read(model)` gives it. */
|
|
@@ -132,6 +132,36 @@ declare const May: {
|
|
|
132
132
|
};
|
|
133
133
|
};
|
|
134
134
|
//#endregion
|
|
135
|
+
//#region src/me.d.ts
|
|
136
|
+
/** The one row's id. */
|
|
137
|
+
declare const ME = "me";
|
|
138
|
+
declare const MeFields: Entity<"Me", {
|
|
139
|
+
readonly id: Schema.String;
|
|
140
|
+
/** Whether the server answered as someone. */
|
|
141
|
+
readonly signedIn: Schema.Boolean;
|
|
142
|
+
/** Who the server answered as: `declare`'s `key` of the principal. */
|
|
143
|
+
readonly key: Schema.OptionFromNullOr<Schema.String>;
|
|
144
|
+
}, {}, {}>;
|
|
145
|
+
/** `Me`'s Entity, with `may`. */
|
|
146
|
+
type MeEntity = ReturnType<typeof May.member<typeof MeFields>>;
|
|
147
|
+
/**
|
|
148
|
+
* `Me` for guard set `G`: everyone reads their own row, no one writes it, and
|
|
149
|
+
* each interaction is answered in `may` as `G`'s bodies decide it for the
|
|
150
|
+
* asker (`May.can(me.may, OpenAdmin.key)`).
|
|
151
|
+
*
|
|
152
|
+
* ```ts
|
|
153
|
+
* const OpenAdmin = Interaction.make('OpenAdmin')
|
|
154
|
+
* export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
declare const me: <Name extends string, User>(G: {
|
|
158
|
+
readonly name: Name;
|
|
159
|
+
readonly schema: Schema.Codec<User, unknown>;
|
|
160
|
+
readonly unguarded: 'allow' | 'deny';
|
|
161
|
+
}, options?: {
|
|
162
|
+
readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions'];
|
|
163
|
+
}) => MeEntity;
|
|
164
|
+
//#endregion
|
|
135
165
|
//#region src/index.d.ts
|
|
136
166
|
/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */
|
|
137
167
|
type Decision = boolean | {
|
|
@@ -245,6 +275,12 @@ interface Policy<User, R = never> {
|
|
|
245
275
|
readonly linkable: (entity: AnyEntity, principal: Option.Option<User>, relation: string, interaction: 'Link' | 'Unlink') => Effect.Effect<Option.Option<RowRule>, never, R>;
|
|
246
276
|
/** The principal's fields as row guards' inputs; a visitor has none. */
|
|
247
277
|
readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>;
|
|
278
|
+
/**
|
|
279
|
+
* Who the principal is: `declare`'s `key`, the same function as `G.key`,
|
|
280
|
+
* here for a server seam that holds the Policy and not the set. Not
|
|
281
|
+
* `keyOf`, which names a principal by every field, for sharing re-reads.
|
|
282
|
+
*/
|
|
283
|
+
readonly key: (user: User) => string;
|
|
248
284
|
/**
|
|
249
285
|
* Who is asking, as the rules see it: every field of the principal, encoded,
|
|
250
286
|
* a visitor included. Two requests by one person with the same claims answer
|
|
@@ -260,6 +296,21 @@ interface Policy<User, R = never> {
|
|
|
260
296
|
* seam that is handed the principal untyped.
|
|
261
297
|
*/
|
|
262
298
|
readonly isPrincipal: (value: unknown) => value is Option.Option<User>;
|
|
299
|
+
/**
|
|
300
|
+
* This Policy with services its bodies need provided, such as a membership
|
|
301
|
+
* lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,
|
|
302
|
+
* `GuardSync`) take a Policy that needs nothing more: a read rule runs inside
|
|
303
|
+
* a read whose requirements are its Source's. Provide what stays put here,
|
|
304
|
+
* once; carry what changes per request in the principal. A seam built from
|
|
305
|
+
* the result counts as built from this Policy: `validate` checks the rules,
|
|
306
|
+
* not the services given them. `GuardSync.authorize` runs bodies
|
|
307
|
+
* synchronously, so what it is given must answer without suspending.
|
|
308
|
+
*
|
|
309
|
+
* ```ts
|
|
310
|
+
* const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))
|
|
311
|
+
* ```
|
|
312
|
+
*/
|
|
313
|
+
readonly provide: <Provided extends R>(context: Context.Context<Provided>) => Policy<User, Exclude<R, Provided>>;
|
|
263
314
|
}
|
|
264
315
|
/** The builders a guard set's declaration is given, typed by its principal. */
|
|
265
316
|
interface Builders<User> {
|
|
@@ -287,6 +338,16 @@ declare const Guards: {
|
|
|
287
338
|
}>>;
|
|
288
339
|
}>>;
|
|
289
340
|
}> : never;
|
|
341
|
+
/**
|
|
342
|
+
* `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no
|
|
343
|
+
* one writes, with `signedIn`, the principal's `key`, and `may` for the
|
|
344
|
+
* interactions named here. Serve it with `GuardServer.me`.
|
|
345
|
+
*
|
|
346
|
+
* ```ts
|
|
347
|
+
* export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
me: typeof me;
|
|
290
351
|
/**
|
|
291
352
|
* One application's guards, under `name` (its principal's Context key, and
|
|
292
353
|
* what the matrix prints). `principal` is a `Schema.Struct`: its fields are
|
|
@@ -302,7 +363,12 @@ declare const Guards: {
|
|
|
302
363
|
*/
|
|
303
364
|
declare: <const Name extends string, Fields extends Schema.Struct.Fields, const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never; }>(name: Name, principal: Schema.Struct<Fields>, build: (guard: Builders<Schema.Struct.Type<Fields>>) => S, options: {
|
|
304
365
|
readonly key: (user: Schema.Struct.Type<Fields>) => string;
|
|
305
|
-
|
|
366
|
+
/**
|
|
367
|
+
* What a surface of a guarded Entity with no rules decides: `'deny'`
|
|
368
|
+
* refuses it, `'allow'` lets everyone. Required, so an open surface is
|
|
369
|
+
* a decision written down; `Guards.matrix` prints it `closed` or `open`.
|
|
370
|
+
*/
|
|
371
|
+
readonly unguarded: 'allow' | 'deny';
|
|
306
372
|
}) => GuardSet<Name, Schema.Struct.Type<Fields>, S>;
|
|
307
373
|
attach: <Name extends string, User, E extends AnyEntity>(G: {
|
|
308
374
|
readonly name: Name;
|
|
@@ -310,7 +376,8 @@ declare const Guards: {
|
|
|
310
376
|
readonly unguarded: 'allow' | 'deny';
|
|
311
377
|
}, config: Attach<NoInfer<User>, NoInfer<Name>, E>) => (entity: E) => E;
|
|
312
378
|
attached: typeof attached;
|
|
313
|
-
all: <const Rules extends ReadonlyArray<Exclude<AnyRule, Inherit<string
|
|
379
|
+
all: <const Rules extends readonly [Exclude<AnyRule, Inherit<string>>, ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>]>(...rules: Rules) => All<Rules[number]>;
|
|
380
|
+
anyone: Readonly<All<never>>;
|
|
314
381
|
inherit: <const Relation extends string>(relation: Relation) => Inherit<Relation>;
|
|
315
382
|
on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(rules: Rules, deny: D) => On<Rules[number], D>;
|
|
316
383
|
redact: <const A>(value: A) => Redact<A>;
|
|
@@ -436,5 +503,5 @@ interface Attachment {
|
|
|
436
503
|
}
|
|
437
504
|
declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
|
|
438
505
|
//#endregion
|
|
439
|
-
export {
|
|
440
|
-
//# sourceMappingURL=attach-
|
|
506
|
+
export { May as A, PrincipalGuard as C, RowSpec as D, RowGuard as E, RowRule as F, MaySchema as M, Condition as N, ME as O, MemberRead as P, Policy as S, PrincipalSpec as T, Builders as _, Deny as a, Guards as b, Interaction as c, Redact as d, RuleFor as f, Body as g, AnyGuard as h, Attachment as i, MayAnswer as j, MeEntity as k, InteractionKey as l, About as m, AnyRule as n, Explain as o, Surface as p, Attach as r, Inherit as s, All as t, On as u, Decision as v, PrincipalOf as w, Placeholders as x, GuardSet as y };
|
|
507
|
+
//# sourceMappingURL=attach-BVG6LsFf.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-BVG6LsFf.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;EA8CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B;;;;;;;EAoBW,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;;;cC/JJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cAerD;;;;;;EAMX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;EAON,MAAG,KAAQ,WAAS,mCAAqC;;;;;;EAQzD,SAAM,KACC,WAAS,mCACqB,mBAClC,OAAO;;EAGV,SAA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AAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;aAE5D,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
|
|
@@ -65,7 +65,7 @@ const mergeAttachments = (attachments) => {
|
|
|
65
65
|
const showRule = (rule) => Match.valueTags(rule, {
|
|
66
66
|
PrincipalGuard: ({ name }) => name,
|
|
67
67
|
RowGuard: ({ name }) => name,
|
|
68
|
-
All: ({ rules }) => `all(${rules.map(showRule).join(", ")})`,
|
|
68
|
+
All: ({ rules }) => rules.length === 0 ? "anyone" : `all(${rules.map(showRule).join(", ")})`,
|
|
69
69
|
Inherit: ({ relation }) => `inherit(${relation})`
|
|
70
70
|
});
|
|
71
71
|
const showDeny = (deny) => Match.valueTags(deny, {
|
|
@@ -96,13 +96,20 @@ const surfaceOf = (attachment, target) => Match.valueTags(target, {
|
|
|
96
96
|
Relation: ({ relation, interaction }) => Option.fromUndefinedOr(attachment.relations[relation]?.[interaction])
|
|
97
97
|
});
|
|
98
98
|
/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */
|
|
99
|
-
|
|
99
|
+
/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */
|
|
100
|
+
const isAnyone = (rule) => rule._tag === "All" && rule.rules.length === 0;
|
|
101
|
+
/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */
|
|
102
|
+
const restricts = (surface) => Option.exists(surface, ({ rules }) => !rules.some(isAnyone));
|
|
103
|
+
const readRowsRuled = (attachment) => restricts(surfaceOf(attachment, {
|
|
104
|
+
_tag: "Row",
|
|
105
|
+
interaction: "Read"
|
|
106
|
+
})) || attachment.always.some((rule) => !isAnyone(rule));
|
|
100
107
|
/** Whether `member`, a field or a relation, has a Read rule of its own. */
|
|
101
|
-
const readRuled = (attachment, member) =>
|
|
108
|
+
const readRuled = (attachment, member) => restricts(surfaceOf(attachment, {
|
|
102
109
|
_tag: "Member",
|
|
103
110
|
member,
|
|
104
111
|
interaction: "Read"
|
|
105
|
-
})) ||
|
|
112
|
+
})) || restricts(surfaceOf(attachment, {
|
|
106
113
|
_tag: "Relation",
|
|
107
114
|
relation: member,
|
|
108
115
|
interaction: "Read"
|
|
@@ -230,6 +237,14 @@ const Attaching = {
|
|
|
230
237
|
_tag: "All",
|
|
231
238
|
rules: Object.freeze([...rules])
|
|
232
239
|
}),
|
|
240
|
+
/**
|
|
241
|
+
* A rule everyone passes, a visitor included: a conjunction of nothing.
|
|
242
|
+
* For a surface that is public under a set whose `unguarded` is `'deny'`.
|
|
243
|
+
*/
|
|
244
|
+
anyone: Object.freeze({
|
|
245
|
+
_tag: "All",
|
|
246
|
+
rules: Object.freeze([])
|
|
247
|
+
}),
|
|
233
248
|
/** This row's Read is the Read of the row its `one` relation points at. */
|
|
234
249
|
inherit: (relation) => Object.freeze({
|
|
235
250
|
_tag: "Inherit",
|
|
@@ -267,6 +282,6 @@ const Attaching = {
|
|
|
267
282
|
})).join("\n")
|
|
268
283
|
};
|
|
269
284
|
//#endregion
|
|
270
|
-
export {
|
|
285
|
+
export { isAnyone as a, restricts as c, defaultDeny as i, surfaceOf as l, Interaction as n, readRowsRuled as o, attached as r, readRuled as s, Attaching as t };
|
|
271
286
|
|
|
272
|
-
//# sourceMappingURL=attach-
|
|
287
|
+
//# sourceMappingURL=attach-BZyVvs7H.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF,MAAa,cAAc;;AAEzB,OAAkC,SAAkC;CAClE,IAAK,QAAkC,SAAS,IAAI,GAClD,MAAM,IAAI,MAAM,sCAAsC,KAAK,4BAA4B;CAEzF,OAAO,OAAO,OAAO;EAAE;EAAM,KAAK;CAA6B,CAAC;AAClE,EACF;AAyIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iB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B,GAAG,IAAI,IACL,CAAC,GAAI,WAAW,IAAI,YAAY,EAAE,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as defaultDeny,
|
|
1
|
+
import { i as defaultDeny, l as surfaceOf, r as attached } from "./attach-BZyVvs7H.mjs";
|
|
2
2
|
import { Effect, Match, Option } from "effect";
|
|
3
3
|
import { Query, evaluate } from "foldkit-entity";
|
|
4
4
|
//#region src/condition.ts
|
|
@@ -210,4 +210,4 @@ const rowTarget = (interaction) => ({
|
|
|
210
210
|
//#endregion
|
|
211
211
|
export { deciding as n, readsPrincipal as r, Condition as t };
|
|
212
212
|
|
|
213
|
-
//# sourceMappingURL=condition-
|
|
213
|
+
//# sourceMappingURL=condition-Dunujvzy.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"condition-C6Czs2Xn.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport { Query, evaluate, type AnyEntity } from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n | { readonly _tag: 'Row'; readonly guard: RowGuard<any, AnyEntity> }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard }) => evaluate(guard.query, input, [values]).length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAC1D,MAAM,QAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAG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,OAAO,QAAQ,CAAC,CAAC;EAC/B,SAAQ,eAAc;GACpB,MAAM,WAAW,QAAQ,SAAQ,WAAU;IACzC,MAAM,SAAS,OAAO,OAAO,OAAO,WAAW,MAAM,IAChD;KAAE,MAAM;KAAY,UAAU;KAAQ;IAAY,IAClD;KAAE,MAAM;KAAU;KAAQ;IAAY;IAC3C,OAAO,OAAO,MAAM,UAAU,YAAY,MAAM,GAAG;KACjD,cAAc,CAAC;KACf,SAAS,EAAE,OAAO,WAAW,CAC3B;MAAE;MAAQ;MAAO,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;KAAE,CAC3E;IACF,CAAC;GACH,CAAC;GACD,OAAO,OAAO,IACZ,cACE,SAAS,SAAS,EAAE,YAAY,KAAK,GACrC,QACA,OACF,IACA,cACE,SAAS,KAAK,EAAE,QAAQ,OAAO,YAAY;IACzC;IACA,WAAW,UAAU,OAAO,EAAE;IAC9B;GACF,EAAE,CACN;EACF;CACF,CAAC;;CAGH,WACE,QACA,aACoD;EACpD,MAAM,SAAS;GAAE,MAAM;GAAY;GAAU;EAAY;EACzD,OAAO,OAAO,MACZ,OAAO,QAAQ,SAAS,MAAM,IAAG,eAAc,UAAU,YAAY,MAAM,CAAC,GAC5E;GACE,cAAc,OAAO,QAAQ,OAAO,KAAK,CAAC;GAC1C,SAAS,EAAE,OAAO,WAChB,OAAO,IAAI,cAAc,OAAO,QAAQ,OAAO,IAAG,cAChD,OAAO,KAAK;IACV,WAAW,UAAU,OAAO,EAAE;IAC9B,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;GACxD,CAAC,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
|
|
1
|
+
{"version":3,"file":"condition-Dunujvzy.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport { Query, evaluate, type AnyEntity } from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n | { readonly _tag: 'Row'; readonly guard: RowGuard<any, AnyEntity> }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard }) => evaluate(guard.query, input, [values]).length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAC1D,MAAM,QAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAGxD,MAAM,OAAO,eAAoD;CAC/D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAAY;EAClC,IAAI,UAAU,SAAS,SAAS,OAAO;EACvC,IAAI,UAAU,SAAS,UAAU,KAAK,KAAK,SAAS;CACtD;CACA,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;CACnC,OAAO,OAAO,OAAO;EAAE,MAAM;EAAO,YAAY,OAAO,OAAO,IAAI;CAAE,CAAC;AACvE;;AAGA,MAAM,MAAM,eAAoD;CAC9D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAAY;EAClC,IAAI,UAAU,SAAS,UAAU,OAAO;EACxC,IAAI,UAAU,SAAS,SAAS,KAAK,KAAK,SAAS;CACrD;CACA,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;CACnC,OAAO,OAAO,OAAO;EAAE,MAAM;EAAM,YAAY,OAAO,OAAO,IAAI;CAAE,CAAC;AACtE;AAEA,MAAa,YAAY;CACvB;CACA;CACA;CACA;;;;;;CAOA,QACE,WACA,QACA,OACA,YACY;EACZ,MAAM,SAAS,SACb,MAAM,UAAU,MAAM;GACpB,cAAc;GACd,aAAa;GACb,MAAM,EAAE,YAAY,SAAS,MAAM,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW;GACtE,UAAU,EAAE,eAAe,QAAQ,QAAQ;GAC3C,MAAM,EAAE,iBAAiB,WAAW,MAAM,KAAK;GAC/C,KAAK,EAAE,i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C,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
|
package/dist/drizzle.d.mts
CHANGED
package/dist/drizzle.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
2
|
-
import { n as rowRules } from "./placed-
|
|
1
|
+
import { r as attached } from "./attach-BZyVvs7H.mjs";
|
|
2
|
+
import { n as rowRules } from "./placed-CkyMqxFw.mjs";
|
|
3
3
|
import { Effect, Match, Option } from "effect";
|
|
4
4
|
import { Query } from "foldkit-entity";
|
|
5
5
|
import { RemoteServerError } from "foldkit-remote-server";
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, May, type MayAnswer, MaySchema, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
|
|
1
|
+
import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-BVG6LsFf.mjs";
|
|
2
|
+
export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, ME, May, type MayAnswer, MaySchema, type MeEntity, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
|