foldkit-guard 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/agent.d.mts +1 -3
- package/dist/agent.d.mts.map +1 -1
- package/dist/agent.mjs +2 -3
- package/dist/{attach-BVG6LsFf.d.mts → attach-BnP9_Uca.d.mts} +18 -15
- package/dist/attach-BnP9_Uca.d.mts.map +1 -0
- package/dist/{attach-BZyVvs7H.mjs → attach-CRCF5XHS.mjs} +16 -4
- package/dist/attach-CRCF5XHS.mjs.map +1 -0
- package/dist/{condition-Dunujvzy.mjs → condition-Bl1UgEpM.mjs} +6 -6
- package/dist/condition-Bl1UgEpM.mjs.map +1 -0
- package/dist/drizzle.d.mts +8 -5
- package/dist/drizzle.d.mts.map +1 -1
- package/dist/drizzle.mjs +11 -14
- package/dist/drizzle.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +12 -11
- package/dist/index.mjs.map +1 -1
- package/dist/{may-DK-2lomO.mjs → may-DzCAt_5M.mjs} +2 -3
- package/dist/{may-DK-2lomO.mjs.map → may-DzCAt_5M.mjs.map} +1 -1
- package/dist/{me-DeSZOGt3.mjs → me-BYpuVqJE.mjs} +4 -5
- package/dist/{me-DeSZOGt3.mjs.map → me-BYpuVqJE.mjs.map} +1 -1
- package/dist/media.d.mts +1 -3
- package/dist/media.d.mts.map +1 -1
- package/dist/media.mjs +1 -2
- package/dist/{origin-CN6ThFTp.mjs → origin-igJoiz74.mjs} +2 -3
- package/dist/{origin-CN6ThFTp.mjs.map → origin-igJoiz74.mjs.map} +1 -1
- package/dist/{placed-CkyMqxFw.mjs → placed-BvdNmZJu.mjs} +4 -5
- package/dist/{placed-CkyMqxFw.mjs.map → placed-BvdNmZJu.mjs.map} +1 -1
- package/dist/server.d.mts +1 -3
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +15 -13
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +1 -3
- package/dist/sync.d.mts.map +1 -1
- package/dist/sync.mjs +4 -5
- package/dist/sync.mjs.map +1 -1
- package/package.json +13 -13
- package/dist/attach-BVG6LsFf.d.mts.map +0 -1
- package/dist/attach-BZyVvs7H.mjs.map +0 -1
- package/dist/condition-Dunujvzy.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -99,7 +99,9 @@ const G = Guards.declare(
|
|
|
99
99
|
{ key: user => user.id, unguarded: 'deny' },
|
|
100
100
|
)
|
|
101
101
|
|
|
102
|
-
// Server: the body of every principal guard, and nothing else.
|
|
102
|
+
// Server: the body of every principal guard, and nothing else. A row guard
|
|
103
|
+
// calling a primitive operator runs it by the table given as a second argument,
|
|
104
|
+
// `G.implement(bodies, { operators })`; `Operators.kernel` when not given.
|
|
103
105
|
const Policy = G.implement({
|
|
104
106
|
isAdmin: principal => Option.exists(principal, user => user.role === 'admin'),
|
|
105
107
|
})
|
|
@@ -221,7 +223,7 @@ const readable = Effect.runSync(Policy.readable(Todo, ada))
|
|
|
221
223
|
// isAdmin was false, so: isOwner or inProject, over each row
|
|
222
224
|
|
|
223
225
|
const t1 = { id: 't1', ownerId: 'ada', projectId: 'p9', title: 'Write the README' }
|
|
224
|
-
Condition.holds(readable, t1, Policy.inputOf(ada), () => false)
|
|
226
|
+
Condition.holds(readable, t1, Policy.inputOf(ada), () => false, Policy.operators)
|
|
225
227
|
// true
|
|
226
228
|
```
|
|
227
229
|
|
|
@@ -316,6 +318,10 @@ const TodoSource = source(Db.Todo, { filter: GuardServer.filter(Todo, Policy) })
|
|
|
316
318
|
is not fails its first read, which is when the binding is first known.
|
|
317
319
|
- The principal reaches a binding untyped, so it is checked: one that is not
|
|
318
320
|
an `Option` of the set's schema is a defect, never read as a visitor.
|
|
321
|
+
- A rule calling a primitive operator compiles by the SQL table `bind` is
|
|
322
|
+
given, and is checked when built against the one passed here
|
|
323
|
+
(`GuardDrizzle.visible(Policy, [Todo], { operators })`, the kernel when not
|
|
324
|
+
given), since `visible` is built before `bind`.
|
|
319
325
|
- `visible` is the row's Read. Member and relation Reads are the Source's
|
|
320
326
|
`filter`, as `TodoSource` has it.
|
|
321
327
|
|
package/dist/agent.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { j as MayAnswer, l as InteractionKey } from "./attach-
|
|
1
|
+
import { j as MayAnswer, l as InteractionKey } from "./attach-BnP9_Uca.mjs";
|
|
2
2
|
import { RemoteData } from "foldkit-remote";
|
|
3
|
-
//#region src/agent.d.ts
|
|
4
3
|
/** A row read with `may`, as `Data.get(Row, id).read(model)` gives it. */
|
|
5
4
|
type MayRow = RemoteData<{
|
|
6
5
|
readonly may: MayAnswer;
|
|
@@ -35,6 +34,5 @@ export declare const GuardAgent: {
|
|
|
35
34
|
*/
|
|
36
35
|
available: <Model>(interaction: 'Update' | 'Delete' | InteractionKey, row: (model: Model) => MayRow) => (model: Model) => boolean;
|
|
37
36
|
};
|
|
38
|
-
//#endregion
|
|
39
37
|
export {};
|
|
40
38
|
//# sourceMappingURL=agent.d.mts.map
|
package/dist/agent.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.mts","names":[],"sources":["../src/agent.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent.d.mts","names":[],"sources":["../src/agent.ts"],"mappings":";;;KAaK,SAAS;WAAsB,KAAK;;qBA6B5B;;;;;;;;;;;;;EAaX,YACG,OAAO,OAAK,mCACwB,gBAAc,MAC3C;aAAoB,OAAO;aAAgB,OAAO;QAAY,YAAM;aAGjE,OAAO;aACP,OAAO;;aACO;aAAyB;;;;;;;EAQpD,YACG,OAAK,mCAAqC,gBAAc,MAAQ,OAAO,UAAU,YAAM,OAChF"}
|
package/dist/agent.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as May } from "./may-
|
|
1
|
+
import { t as May } from "./may-DzCAt_5M.mjs";
|
|
2
2
|
import { Option } from "effect";
|
|
3
3
|
import { RemoteData } from "foldkit-remote";
|
|
4
|
-
|
|
4
|
+
// src/agent.ts
|
|
5
5
|
/**
|
|
6
6
|
* `foldkit-guard/agent`: a `foldkit-agent` capability's `authorize` and
|
|
7
7
|
* `available`, read from the `may` the server answered for a row the Model
|
|
@@ -50,7 +50,6 @@ const GuardAgent = {
|
|
|
50
50
|
*/
|
|
51
51
|
available: (interaction, row) => (model) => decided(row(model), interaction) === true
|
|
52
52
|
};
|
|
53
|
-
//#endregion
|
|
54
53
|
export { GuardAgent };
|
|
55
54
|
|
|
56
55
|
//# sourceMappingURL=agent.mjs.map
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Context, Effect, Option, Schema } from "effect";
|
|
2
|
-
import { AnyEntity, AnyQuery, Entity, InputExpr, Predicate } from "foldkit-entity";
|
|
3
|
-
//#region src/condition.d.ts
|
|
2
|
+
import { AnyEntity, AnyQuery, Entity, InputExpr, MemoryOperators, Predicate } from "foldkit-entity";
|
|
4
3
|
type Condition = {
|
|
5
4
|
readonly _tag: 'Always';
|
|
6
5
|
} | {
|
|
@@ -37,8 +36,9 @@ declare const Condition: {
|
|
|
37
36
|
* Whether a row's stored values meet `condition`, its row guards read with
|
|
38
37
|
* `input` (the principal's, from `G.inputOf`). `inherit` answers whether the
|
|
39
38
|
* row a relation points at is readable, which only the caller can look up.
|
|
39
|
+
* `operators` runs the guards' primitive operators: the policy's.
|
|
40
40
|
*/
|
|
41
|
-
holds: (condition: Condition, values: Readonly<Record<string, unknown>>, input: Readonly<Record<string, unknown>>, inherit: (relation: string) => boolean) => boolean;
|
|
41
|
+
holds: (condition: Condition, values: Readonly<Record<string, unknown>>, input: Readonly<Record<string, unknown>>, inherit: (relation: string) => boolean, operators: MemoryOperators) => boolean;
|
|
42
42
|
/**
|
|
43
43
|
* `condition` with every row guard that reads one of `unset`, and every
|
|
44
44
|
* relation of them it follows, refused: a field a create leaves unset
|
|
@@ -60,8 +60,6 @@ interface RowRule {
|
|
|
60
60
|
readonly condition: Condition;
|
|
61
61
|
readonly deny: Deny;
|
|
62
62
|
}
|
|
63
|
-
//#endregion
|
|
64
|
-
//#region src/may.d.ts
|
|
65
63
|
/**
|
|
66
64
|
* The answer: per row interaction (`Update`, `Delete`, and each one the
|
|
67
65
|
* application named), per member with its own `Update` rule, and per relation
|
|
@@ -131,8 +129,6 @@ declare const May: {
|
|
|
131
129
|
locked: (row: Readonly<Record<string, unknown>>, member: string) => boolean;
|
|
132
130
|
};
|
|
133
131
|
};
|
|
134
|
-
//#endregion
|
|
135
|
-
//#region src/me.d.ts
|
|
136
132
|
/** The one row's id. */
|
|
137
133
|
declare const ME = "me";
|
|
138
134
|
declare const MeFields: Entity<"Me", {
|
|
@@ -161,8 +157,6 @@ declare const me: <Name extends string, User>(G: {
|
|
|
161
157
|
}, options?: {
|
|
162
158
|
readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions'];
|
|
163
159
|
}) => MeEntity;
|
|
164
|
-
//#endregion
|
|
165
|
-
//#region src/index.d.ts
|
|
166
160
|
/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */
|
|
167
161
|
type Decision = boolean | {
|
|
168
162
|
readonly allowed: false;
|
|
@@ -239,12 +233,24 @@ type GuardSet<Name extends string, User, S> = { readonly [K in keyof S]: GuardOf
|
|
|
239
233
|
readonly unguarded: 'allow' | 'deny';
|
|
240
234
|
/** The principal's fields as row guards' inputs, encoded as stored values are. */
|
|
241
235
|
readonly inputOf: (user: User) => Readonly<Record<string, unknown>>;
|
|
242
|
-
/**
|
|
243
|
-
|
|
236
|
+
/**
|
|
237
|
+
* The bodies of the principal guards: every one, and nothing else. `operators`
|
|
238
|
+
* runs the row guards' primitive operators in memory; `Operators.kernel` when
|
|
239
|
+
* not given.
|
|
240
|
+
*/
|
|
241
|
+
readonly implement: <R = never>(bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R>; }, options?: {
|
|
242
|
+
readonly operators?: MemoryOperators | undefined;
|
|
243
|
+
}) => Policy<User, R>;
|
|
244
244
|
};
|
|
245
245
|
/** The server's half of a guard set: every principal guard's body. */
|
|
246
246
|
interface Policy<User, R = never> {
|
|
247
247
|
readonly set: string;
|
|
248
|
+
/**
|
|
249
|
+
* How a row guard's primitive operators are run in memory: by `decide`,
|
|
250
|
+
* `Condition.holds` and every guarded server judging a row. Given to
|
|
251
|
+
* `implement`; `Operators.kernel` when not.
|
|
252
|
+
*/
|
|
253
|
+
readonly operators: MemoryOperators;
|
|
248
254
|
/**
|
|
249
255
|
* Whether `guard` allows `principal`, for a row guard over `row` (its stored,
|
|
250
256
|
* encoded values). A visitor passes no row guard that reads a principal's
|
|
@@ -385,8 +391,6 @@ declare const Guards: {
|
|
|
385
391
|
guardFields: (entity: AnyEntity, interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey) => ReadonlyArray<string>;
|
|
386
392
|
matrix: (entities: ReadonlyArray<AnyEntity>) => string;
|
|
387
393
|
};
|
|
388
|
-
//#endregion
|
|
389
|
-
//#region src/attach.d.ts
|
|
390
394
|
declare const InteractionBrand: unique symbol;
|
|
391
395
|
/** An interaction the application names, used as a computed key: `[Archive.key]`. */
|
|
392
396
|
type InteractionKey<Name extends string = string> = Name & {
|
|
@@ -502,6 +506,5 @@ interface Attachment {
|
|
|
502
506
|
readonly always: ReadonlyArray<AnyRule>;
|
|
503
507
|
}
|
|
504
508
|
declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
|
|
505
|
-
//#endregion
|
|
506
509
|
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-
|
|
510
|
+
//# sourceMappingURL=attach-BnP9_Uca.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-BnP9_Uca.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;;;;;;;;;;EA+CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;EAoBU,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;cCjKJ,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,SAAS,UAAU,WAAS,KAAO,WAAS,SAAW,GAAC,QAAUA,aAAW;;EAI7E,UAAU,UAAU,WAAS,KACtB,WAAS,SACL,GAAC,gBACM,yBAAuB;;;;;;;;;;;EAczC,QAAK,QAAW;IACd;eAAU;;IACV,SAAM,KAAQ,SAAS,0BAAwB;;;;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E5D,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;;cAoRpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Match, Option } from "effect";
|
|
2
2
|
import { Entity, Query, ReadFilter } from "foldkit-entity";
|
|
3
3
|
import { Metadata } from "foldkit-metadata";
|
|
4
|
-
|
|
4
|
+
// src/attach.ts
|
|
5
5
|
/**
|
|
6
6
|
* Attaching a guard set's guards to an Entity, per surface and interaction,
|
|
7
7
|
* as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.
|
|
@@ -97,6 +97,19 @@ const surfaceOf = (attachment, target) => Match.valueTags(target, {
|
|
|
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
|
+
/** The rules, each `all` opened into its parts: every guard they ask. */
|
|
101
|
+
const flattenRules = (rules) => rules.flatMap((rule) => Match.valueTags(rule, {
|
|
102
|
+
PrincipalGuard: () => [rule],
|
|
103
|
+
RowGuard: () => [rule],
|
|
104
|
+
All: ({ rules: parts }) => flattenRules(parts),
|
|
105
|
+
Inherit: () => [rule]
|
|
106
|
+
}));
|
|
107
|
+
/** Every rule attached anywhere: on the row, each member and relation, and always. */
|
|
108
|
+
const attachedRules = (attachment) => flattenRules([...attachment.always, ...[
|
|
109
|
+
attachment.row,
|
|
110
|
+
...Object.values(attachment.members),
|
|
111
|
+
...Object.values(attachment.relations)
|
|
112
|
+
].flatMap((surfaces) => Object.values(surfaces)).flatMap((surface) => surface.rules)]);
|
|
100
113
|
const isAnyone = (rule) => rule._tag === "All" && rule.rules.length === 0;
|
|
101
114
|
/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */
|
|
102
115
|
const restricts = (surface) => Option.exists(surface, ({ rules }) => !rules.some(isAnyone));
|
|
@@ -281,7 +294,6 @@ const Attaching = {
|
|
|
281
294
|
onSome: (attachment) => linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`)
|
|
282
295
|
})).join("\n")
|
|
283
296
|
};
|
|
284
|
-
|
|
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 };
|
|
297
|
+
export { defaultDeny as a, readRowsRuled as c, surfaceOf as d, attachedRules as i, readRuled as l, Interaction as n, flattenRules as o, attached as r, isAnyone as s, Attaching as t, restricts as u };
|
|
286
298
|
|
|
287
|
-
//# sourceMappingURL=attach-
|
|
299
|
+
//# sourceMappingURL=attach-CRCF5XHS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-CRCF5XHS.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. */\n/** The rules, each `all` opened into its parts: every guard they ask. */\nexport const flattenRules = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<AnyRule> =>\n rules.flatMap(rule =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [rule],\n RowGuard: () => [rule],\n All: ({ rules: parts }) => flattenRules(parts),\n Inherit: () => [rule],\n }),\n )\n\n/** Every rule attached anywhere: on the row, each member and relation, and always. */\nexport const attachedRules = (attachment: Attachment): ReadonlyArray<AnyRule> =>\n flattenRules([\n ...attachment.always,\n ...[\n attachment.row,\n ...Object.values(attachment.members),\n ...Object.values(attachment.relations),\n ]\n .flatMap(surfaces => Object.values(surfaces))\n .flatMap(surface => surface.rules),\n ])\n\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,iBAAiB,MAA+B,aAAqB,UAAmB;CAC5F,MAAM,SAAS,KAAK;CACpB,KAAK,eACH,WAAW,KAAA,IACP,QACA;EACE,OAAO,CAAC,GAAG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CAG7C,KACE,OACA,SACyB,OAAO,OAAO;EAAE,MAAM;EAAM,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;EAAG;CAAK,CAAC;;CAG/F,SAAkB,UAAwB,OAAO,OAAO;EAAE,MAAM;EAAU;CAAM,CAAC;;CAGjF,UAAU,WAA4B,OAAO,OAAO;EAAE,MAAM;EAAW;CAAO,CAAC;;;;;;CAO/E,cACE,QACA,gBAEA,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC;EACf,SAAQ,eAAc,CACpB,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,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as defaultDeny, d as surfaceOf, r as attached } from "./attach-CRCF5XHS.mjs";
|
|
2
2
|
import { Effect, Match, Option } from "effect";
|
|
3
3
|
import { Query, evaluate } from "foldkit-entity";
|
|
4
|
-
|
|
4
|
+
// src/condition.ts
|
|
5
5
|
/**
|
|
6
6
|
* What an attachment's read rules come to for one principal, once its
|
|
7
7
|
* principal guards are decided: a condition over the row, which an
|
|
@@ -47,12 +47,13 @@ const Condition = {
|
|
|
47
47
|
* Whether a row's stored values meet `condition`, its row guards read with
|
|
48
48
|
* `input` (the principal's, from `G.inputOf`). `inherit` answers whether the
|
|
49
49
|
* row a relation points at is readable, which only the caller can look up.
|
|
50
|
+
* `operators` runs the guards' primitive operators: the policy's.
|
|
50
51
|
*/
|
|
51
|
-
holds: (condition, values, input, inherit) => {
|
|
52
|
+
holds: (condition, values, input, inherit, operators) => {
|
|
52
53
|
const holds = (each) => Match.valueTags(each, {
|
|
53
54
|
Always: () => true,
|
|
54
55
|
Never: () => false,
|
|
55
|
-
Row: ({ guard }) => evaluate(guard.query, input, [values]).length === 1,
|
|
56
|
+
Row: ({ guard }) => evaluate(guard.query, input, [values], { operators }).length === 1,
|
|
56
57
|
Inherit: ({ relation }) => inherit(relation),
|
|
57
58
|
And: ({ conditions }) => conditions.every(holds),
|
|
58
59
|
Or: ({ conditions }) => conditions.some(holds)
|
|
@@ -207,7 +208,6 @@ const rowTarget = (interaction) => ({
|
|
|
207
208
|
_tag: "Row",
|
|
208
209
|
interaction
|
|
209
210
|
});
|
|
210
|
-
//#endregion
|
|
211
211
|
export { deciding as n, readsPrincipal as r, Condition as t };
|
|
212
212
|
|
|
213
|
-
//# sourceMappingURL=condition-
|
|
213
|
+
//# sourceMappingURL=condition-Bl1UgEpM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"condition-Bl1UgEpM.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, type MemoryOperators } 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 * `operators` runs the guards' primitive operators: the policy's.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\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], { operators }).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,UAA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,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"}
|
package/dist/drizzle.d.mts
CHANGED
|
@@ -1,20 +1,23 @@
|
|
|
1
|
-
import { S as Policy } from "./attach-
|
|
1
|
+
import { S as Policy } from "./attach-BnP9_Uca.mjs";
|
|
2
2
|
import { AnyEntity } from "foldkit-entity";
|
|
3
|
-
import { Visible } from "foldkit-remote-drizzle";
|
|
4
|
-
//#region src/drizzle.d.ts
|
|
3
|
+
import { DrizzleOperators, Visible } from "foldkit-remote-drizzle";
|
|
5
4
|
export declare const GuardDrizzle: {
|
|
6
5
|
/**
|
|
7
6
|
* The `visible` rule of each of `entities`, the Entities as `Guards.attach`
|
|
8
7
|
* returned them, by name, for `bind`'s storage. Checked here, before any
|
|
9
8
|
* request: a row guard this compiler cannot run, and an inherited Read whose
|
|
10
9
|
* Entity is not listed, has no Read rule, or leads back to itself, throw.
|
|
10
|
+
* `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),
|
|
11
|
+
* so a rule calling an operator it lacks is refused here; the kernel's when
|
|
12
|
+
* not given. Give both the same table.
|
|
11
13
|
*
|
|
12
14
|
* ```ts
|
|
13
15
|
* const visible = GuardDrizzle.visible(Policy, [Todo, Project])
|
|
14
16
|
* bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })
|
|
15
17
|
* ```
|
|
16
18
|
*/
|
|
17
|
-
visible: <User, const Es extends ReadonlyArray<AnyEntity>>(policy: Policy<User>, entities: Es
|
|
19
|
+
visible: <User, const Es extends ReadonlyArray<AnyEntity>>(policy: Policy<User>, entities: Es, options?: {
|
|
20
|
+
readonly operators?: DrizzleOperators | undefined;
|
|
21
|
+
}) => { readonly [K in Es[number]['name']]: Visible; };
|
|
18
22
|
};
|
|
19
|
-
//#endregion
|
|
20
23
|
//# sourceMappingURL=drizzle.d.mts.map
|
package/dist/drizzle.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drizzle.d.mts","names":[],"sources":["../src/drizzle.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"drizzle.d.mts","names":[],"sources":["../src/drizzle.ts"],"mappings":";;;qBAoCa;;;;;;;;;;;;;;;EAeX,UAAU,YAAY,WAAW,cAAc,YAAU,QAC/C,OAAO,OAAK,UACV,IAAE;aACQ,YAAY;oBACnB,KAAK,qBAAqB"}
|
package/dist/drizzle.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
2
|
-
import { n as rowRules } from "./placed-
|
|
1
|
+
import { o as flattenRules, r as attached } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { n as rowRules } from "./placed-BvdNmZJu.mjs";
|
|
3
3
|
import { Effect, Match, Option } from "effect";
|
|
4
4
|
import { Query } from "foldkit-entity";
|
|
5
5
|
import { RemoteServerError } from "foldkit-remote-server";
|
|
6
6
|
import { and, or, sql } from "drizzle-orm";
|
|
7
|
-
import { compileWhere, idColumn, supported } from "foldkit-remote-drizzle";
|
|
8
|
-
|
|
7
|
+
import { DrizzleOperators, compileWhere, idColumn, supported as supported$1 } from "foldkit-remote-drizzle";
|
|
8
|
+
// src/drizzle.ts
|
|
9
9
|
/**
|
|
10
10
|
* A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:
|
|
11
11
|
* each principal guard decided, what is left compiled to SQL over the table,
|
|
@@ -19,12 +19,6 @@ const readRules = (entity) => Option.match(attached(entity), {
|
|
|
19
19
|
onNone: () => [],
|
|
20
20
|
onSome: (attachment) => [...attachment.always, ...attachment.row["Read"]?.rules ?? []]
|
|
21
21
|
});
|
|
22
|
-
const flatten = (rules) => rules.flatMap((rule) => Match.valueTags(rule, {
|
|
23
|
-
PrincipalGuard: () => [rule],
|
|
24
|
-
RowGuard: () => [rule],
|
|
25
|
-
All: ({ rules: parts }) => flatten(parts),
|
|
26
|
-
Inherit: () => [rule]
|
|
27
|
-
}));
|
|
28
22
|
const nothing = sql`1 = 0`;
|
|
29
23
|
const GuardDrizzle = {
|
|
30
24
|
/**
|
|
@@ -32,21 +26,25 @@ const GuardDrizzle = {
|
|
|
32
26
|
* returned them, by name, for `bind`'s storage. Checked here, before any
|
|
33
27
|
* request: a row guard this compiler cannot run, and an inherited Read whose
|
|
34
28
|
* Entity is not listed, has no Read rule, or leads back to itself, throw.
|
|
29
|
+
* `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),
|
|
30
|
+
* so a rule calling an operator it lacks is refused here; the kernel's when
|
|
31
|
+
* not given. Give both the same table.
|
|
35
32
|
*
|
|
36
33
|
* ```ts
|
|
37
34
|
* const visible = GuardDrizzle.visible(Policy, [Todo, Project])
|
|
38
35
|
* bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })
|
|
39
36
|
* ```
|
|
40
37
|
*/
|
|
41
|
-
visible: (policy, entities) => {
|
|
38
|
+
visible: (policy, entities, options = {}) => {
|
|
39
|
+
const sqlOperators = options.operators ?? DrizzleOperators.kernel;
|
|
42
40
|
const byName = new Map(entities.map((entity) => [entity.name, entity]));
|
|
43
41
|
const inherits = /* @__PURE__ */ new Map();
|
|
44
42
|
for (const entity of entities) {
|
|
45
43
|
const targets = [];
|
|
46
|
-
for (const rule of
|
|
44
|
+
for (const rule of flattenRules(readRules(entity))) Match.valueTags(rule, {
|
|
47
45
|
PrincipalGuard: () => {},
|
|
48
46
|
RowGuard: (guard) => {
|
|
49
|
-
const missing = Query.unsupported(guard.query, supported);
|
|
47
|
+
const missing = Query.unsupported(guard.query, supported$1, sqlOperators);
|
|
50
48
|
if (missing.length > 0) fail(`${entity.name}'s ${guard.name} needs ${missing.join(", ")}, which SQL here does not run`);
|
|
51
49
|
},
|
|
52
50
|
All: () => {},
|
|
@@ -91,7 +89,6 @@ visible: (policy, entities) => {
|
|
|
91
89
|
};
|
|
92
90
|
return Object.fromEntries(entities.map((entity) => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]));
|
|
93
91
|
} };
|
|
94
|
-
//#endregion
|
|
95
92
|
export { GuardDrizzle };
|
|
96
93
|
|
|
97
94
|
//# sourceMappingURL=drizzle.mjs.map
|
package/dist/drizzle.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drizzle.mjs","names":[],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n compileWhere,\n idColumn,\n supported,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst
|
|
1
|
+
{"version":3,"file":"drizzle.mjs","names":["supported"],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n compileWhere,\n idColumn,\n supported,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),\n * so a rule calling an operator it lacks is refused here; the kernel's when\n * not given. Give both the same table.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, supported, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n Row: ({ guard }) =>\n and(...compileWhere(guard.query, binding, input, `${name}.${guard.name}`)),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,I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Y,SAAS,GAC/B,OAAO,OAAO,oBACZ,IAAI,MAAM,mBAAmB,KAAK,oDAAoD,CACxF;EAEF,OAAO,OAAO,QACZ,OAAO,QAAQ,QAAQ,IAAI,IAAI,IAAI,SACjC,OAAO,IACL,OAAO,SAAS,OAAO,IAAI,IAAI,GAAI,SAAS,IAC5C,cAAa,CAAC,MAAM,SAAS,CAC/B,CACF,IACA,YACE,OAAO,IAAI;GACT,WAAW,QAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,GAAG,OAAO,QAAQ,SAAS,CAAC;GAC1E,QAAO,UACL,IAAI,kBAAkB,EACpB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAChE,CAAC;EACL,CAAC,CACL;CACF;CACF,OAAO,OAAO,YACZ,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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-
|
|
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-BnP9_Uca.mjs";
|
|
2
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { n as Interaction, r as attached, t as Attaching } from "./attach-
|
|
2
|
-
import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-
|
|
3
|
-
import { n as MaySchema, t as May } from "./may-
|
|
4
|
-
import { n as me, t as ME } from "./me-
|
|
5
|
-
import { n as providedFrom } from "./origin-
|
|
1
|
+
import { n as Interaction, r as attached, t as Attaching } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Bl1UgEpM.mjs";
|
|
3
|
+
import { n as MaySchema, t as May } from "./may-DzCAt_5M.mjs";
|
|
4
|
+
import { n as me, t as ME } from "./me-BYpuVqJE.mjs";
|
|
5
|
+
import { n as providedFrom } from "./origin-igJoiz74.mjs";
|
|
6
6
|
import { Context, Effect, Match, Option, Schema } from "effect";
|
|
7
|
-
import { Expr, Query, evaluate } from "foldkit-entity";
|
|
8
|
-
|
|
7
|
+
import { Expr, Operators, Query, evaluate } from "foldkit-entity";
|
|
8
|
+
// src/index.ts
|
|
9
9
|
/**
|
|
10
10
|
* Who may do what, declared once on the domain.
|
|
11
11
|
*
|
|
@@ -115,7 +115,8 @@ const Guards = {
|
|
|
115
115
|
};
|
|
116
116
|
const isPrincipal = Schema.is(Schema.Option(principal));
|
|
117
117
|
const asJson = Schema.encodeSync(Schema.toCodecJson(principal));
|
|
118
|
-
const implement = (bodies) => {
|
|
118
|
+
const implement = (bodies, implementation = {}) => {
|
|
119
|
+
const operators = implementation.operators ?? Operators.kernel;
|
|
119
120
|
const missing = principalNames.filter((guard) => !Object.hasOwn(bodies, guard));
|
|
120
121
|
const extra = Object.keys(bodies).filter((guard) => !principalNames.includes(guard));
|
|
121
122
|
if (missing.length > 0 || extra.length > 0) throw new Error(`[foldkit-guard] ${name}.implement: ${[missing.length > 0 ? `no body for ${missing.join(", ")}` : "", extra.length > 0 ? `${extra.join(", ")} is not a principal guard` : ""].filter((part) => part !== "").join("; ")}`);
|
|
@@ -127,8 +128,8 @@ const Guards = {
|
|
|
127
128
|
return Effect.isEffect(decided) ? decided : Effect.succeed(decided);
|
|
128
129
|
},
|
|
129
130
|
RowGuard: (rowGuard) => Effect.succeed(row !== void 0 && Option.match(principal, {
|
|
130
|
-
onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row]).length === 1,
|
|
131
|
-
onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row]).length === 1
|
|
131
|
+
onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row], { operators }).length === 1,
|
|
132
|
+
onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row], { operators }).length === 1
|
|
132
133
|
}))
|
|
133
134
|
});
|
|
134
135
|
};
|
|
@@ -143,6 +144,7 @@ const Guards = {
|
|
|
143
144
|
};
|
|
144
145
|
const policy = {
|
|
145
146
|
set: name,
|
|
147
|
+
operators,
|
|
146
148
|
decide,
|
|
147
149
|
readable: (entity, principal) => Effect.map(decidingFor(entity, principal, "Read").row(entity), ({ condition }) => condition),
|
|
148
150
|
readMembers: (entity, principal, members) => decidingFor(entity, principal, "Read").members(entity, members),
|
|
@@ -175,7 +177,6 @@ const Guards = {
|
|
|
175
177
|
});
|
|
176
178
|
}
|
|
177
179
|
};
|
|
178
|
-
//#endregion
|
|
179
180
|
export { Condition, Guards, Interaction, ME, May, MaySchema };
|
|
180
181
|
|
|
181
182
|
//# sourceMappingURL=index.mjs.map
|