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/dist/index.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
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-
|
|
1
|
+
import { n as Interaction, r as attached, t as Attaching } from "./attach-BZyVvs7H.mjs";
|
|
2
|
+
import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Dunujvzy.mjs";
|
|
3
3
|
import { n as MaySchema, t as May } from "./may-DK-2lomO.mjs";
|
|
4
|
+
import { n as me, t as ME } from "./me-DeSZOGt3.mjs";
|
|
5
|
+
import { n as providedFrom } from "./origin-CN6ThFTp.mjs";
|
|
4
6
|
import { Context, Effect, Match, Option, Schema } from "effect";
|
|
5
7
|
import { Expr, Query, evaluate } from "foldkit-entity";
|
|
6
8
|
//#region src/index.ts
|
|
@@ -23,6 +25,21 @@ const reserved = [
|
|
|
23
25
|
"inputOf",
|
|
24
26
|
"implement"
|
|
25
27
|
];
|
|
28
|
+
/** `policy` with `context` provided to every body it runs. */
|
|
29
|
+
const provided = (policy, context) => {
|
|
30
|
+
const run = (effect) => Effect.provide(effect, context);
|
|
31
|
+
const next = {
|
|
32
|
+
...policy,
|
|
33
|
+
decide: (guard, request) => run(policy.decide(guard, request)),
|
|
34
|
+
readable: (entity, principal) => run(policy.readable(entity, principal)),
|
|
35
|
+
readMembers: (entity, principal, members) => run(policy.readMembers(entity, principal, members)),
|
|
36
|
+
writable: (entity, principal, interaction) => run(policy.writable(entity, principal, interaction)),
|
|
37
|
+
writeMembers: (entity, principal, members, interaction) => run(policy.writeMembers(entity, principal, members, interaction)),
|
|
38
|
+
linkable: (entity, principal, relation, interaction) => run(policy.linkable(entity, principal, relation, interaction)),
|
|
39
|
+
provide: (more) => provided(next, more)
|
|
40
|
+
};
|
|
41
|
+
return providedFrom(next, policy);
|
|
42
|
+
};
|
|
26
43
|
const placeholdersOf = (fields) => {
|
|
27
44
|
const inputs = {};
|
|
28
45
|
for (const key of Object.keys(fields)) inputs[key] = Expr.input(`principal.${key}`, fields[key]);
|
|
@@ -37,6 +54,16 @@ const Guards = {
|
|
|
37
54
|
*/
|
|
38
55
|
may: May.member,
|
|
39
56
|
/**
|
|
57
|
+
* `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no
|
|
58
|
+
* one writes, with `signedIn`, the principal's `key`, and `may` for the
|
|
59
|
+
* interactions named here. Serve it with `GuardServer.me`.
|
|
60
|
+
*
|
|
61
|
+
* ```ts
|
|
62
|
+
* export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
me,
|
|
66
|
+
/**
|
|
40
67
|
* One application's guards, under `name` (its principal's Context key, and
|
|
41
68
|
* what the matrix prints). `principal` is a `Schema.Struct`: its fields are
|
|
42
69
|
* what a row guard reads, and its codec encodes a principal's values as
|
|
@@ -50,6 +77,7 @@ const Guards = {
|
|
|
50
77
|
* ```
|
|
51
78
|
*/
|
|
52
79
|
declare: (name, principal, build, options) => {
|
|
80
|
+
if (options.unguarded !== "allow" && options.unguarded !== "deny") throw new Error(`[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`);
|
|
53
81
|
const placeholders = placeholdersOf(principal.fields);
|
|
54
82
|
const specs = build({
|
|
55
83
|
principal: () => Object.freeze({ _tag: "PrincipalSpec" }),
|
|
@@ -113,7 +141,7 @@ const Guards = {
|
|
|
113
141
|
interaction
|
|
114
142
|
}), (decision) => decision === true), Option.isNone(principal), interaction);
|
|
115
143
|
};
|
|
116
|
-
|
|
144
|
+
const policy = {
|
|
117
145
|
set: name,
|
|
118
146
|
decide,
|
|
119
147
|
readable: (entity, principal) => Effect.map(decidingFor(entity, principal, "Read").row(entity), ({ condition }) => condition),
|
|
@@ -125,12 +153,15 @@ const Guards = {
|
|
|
125
153
|
onNone: () => ({}),
|
|
126
154
|
onSome: (user) => inputOf(user)
|
|
127
155
|
}),
|
|
156
|
+
key: options.key,
|
|
128
157
|
keyOf: (principal) => Option.match(principal, {
|
|
129
158
|
onNone: () => "visitor",
|
|
130
159
|
onSome: (user) => `user:${JSON.stringify(asJson(user))}`
|
|
131
160
|
}),
|
|
132
|
-
isPrincipal
|
|
161
|
+
isPrincipal,
|
|
162
|
+
provide: (context) => provided(policy, context)
|
|
133
163
|
};
|
|
164
|
+
return policy;
|
|
134
165
|
};
|
|
135
166
|
return Object.freeze({
|
|
136
167
|
...guards,
|
|
@@ -138,13 +169,13 @@ const Guards = {
|
|
|
138
169
|
schema: principal,
|
|
139
170
|
Principal: Context.Service(`foldkit-guard/Principal/${name}`),
|
|
140
171
|
key: options.key,
|
|
141
|
-
unguarded: options.unguarded
|
|
172
|
+
unguarded: options.unguarded,
|
|
142
173
|
inputOf,
|
|
143
174
|
implement
|
|
144
175
|
});
|
|
145
176
|
}
|
|
146
177
|
};
|
|
147
178
|
//#endregion
|
|
148
|
-
export { Condition, Guards, Interaction, May, MaySchema };
|
|
179
|
+
export { Condition, Guards, Interaction, ME, May, MaySchema };
|
|
149
180
|
|
|
150
181
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport {\n Expr,\n Query,\n evaluate,\n type AnyEntity,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /** The bodies of the principal guards: every one, and nothing else. */\n readonly implement: <R = never>(bodies: {\n readonly [K in PrincipalKeys<S>]: Body<User, R>\n }) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> => {\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(\n `principal.${key}`,\n fields[key] as unknown as Schema.Codec<unknown, unknown>,\n )\n }\n return Object.freeze(inputs) as Placeholders<User>\n}\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n readonly unguarded?: 'allow' | 'deny' | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => Object.freeze({ _tag: 'RowSpec', entity, body: body(placeholders) }),\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(bodies: Readonly<Record<string, Body<User, R>>>): Policy<User, R> => {\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row]).length === 1,\n onSome: user => evaluate(rowGuard.query, inputOf(user), [row]).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n )\n }\n return {\n set: name,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n }\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded ?? 'allow',\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAiHA,MAAM,kBAAwB,WAAqD;CACjF,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,OAAO,OAAO,KAAK,MACjB,aAAa,OACb,OAAO,IACT;CAEF,OAAO,OAAO,OAAO,MAAM;AAC7B;AAoBA,MAAa,SAAS;CACpB,GAAG;;;;;;CAMH,KAAK,IAAI;;;;;;;;;;;;;;CAcT,UAKE,MACA,WACA,OACA,YAIkD;EAElD,MAAM,eAAe,eAAqB,UAAU,MAAM;EAC1D,MAAM,QAAQ,MAAM;GAClB,iBAAiB,OAAO,OAAO,EAAE,MAAM,gBAAgB,CAAC;GACxD,MAAM,QAAQ,SAAS,OAAO,OAAO;IAAE,MAAM;IAAW;IAAQ,MAAM,KAAK,YAAY;GAAE,CAAC;EAC5F,CAAC;EACD,MAAM,SAAyC,OAAO,OAAO,IAAI;EACjE,KAAK,MAAM,CAAC,OAAO,SAAS,OAAO,QAAQ,KAAK,GAAG;GACjD,IAAK,SAAmC,SAAS,KAAK,GACpD,MAAM,IAAI,MACR,mBAAmB,KAAK,KAAK,MAAM,2CACrC;GAEF,OAAO,SAAS,MAAM,UAAU,MAAM;IACpC,qBACE,OAAO,OAAO;KAAE,MAAM;KAAkB,MAAM;KAAO,KAAK;IAAK,CAAC;IAClE,UAAU,EAAE,QAAQ,WAClB,OAAO,OAAO;KACZ,MAAM;KACN,MAAM;KACN,KAAK;KACL;KACA;KAEA,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,KAAK,MA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WAAW,CAAC,CAAC,SAAS,QAAQ,QAAQ;IACvE,UAAS,cACP,OAAO,MAAM,WAAW;KAAE,eAAe,CAAC;KAAI,SAAQ,SAAQ,QAAQ,IAAI;IAAE,CAAC;IAI/E,QAAO,cACL,OAAO,MAAM,WAAW;KACtB,cAAc;KACd,SAAQ,SAAQ,QAAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;GACF;EACF;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ,aAAa;GAChC;GACA;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Query,\n evaluate,\n type AnyEntity,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /** The bodies of the principal guards: every one, and nothing else. */\n readonly implement: <R = never>(bodies: {\n readonly [K in PrincipalKeys<S>]: Body<User, R>\n }) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> => {\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(\n `principal.${key}`,\n fields[key] as unknown as Schema.Codec<unknown, unknown>,\n )\n }\n return Object.freeze(inputs) as Placeholders<User>\n}\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => Object.freeze({ _tag: 'RowSpec', entity, body: body(placeholders) }),\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(bodies: Readonly<Record<string, Body<User, R>>>): Policy<User, R> => {\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row]).length === 1,\n onSome: user => evaluate(rowGuard.query, inputOf(user), [row]).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA8HA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAAqD;CACjF,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,OAAO,OAAO,KAAK,MACjB,aAAa,OACb,OAAO,IACT;CAEF,OAAO,OAA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Q,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { t as Attaching } from "./attach-BZyVvs7H.mjs";
|
|
2
|
+
import { t as May } from "./may-DK-2lomO.mjs";
|
|
3
|
+
import { Schema } from "effect";
|
|
4
|
+
import { Entity } from "foldkit-entity";
|
|
5
|
+
//#region src/me.ts
|
|
6
|
+
/**
|
|
7
|
+
* The visitor as an Entity: one row, `me`, answered for whoever asks. What a
|
|
8
|
+
* client knows about itself (signed in, as whom, what it may open) is read
|
|
9
|
+
* through Remote like any row, `may` included, so no rule runs on the client.
|
|
10
|
+
*/
|
|
11
|
+
/** The one row's id. */
|
|
12
|
+
const ME = "me";
|
|
13
|
+
const MeFields = Entity.define("Me", Schema.Struct({
|
|
14
|
+
id: Schema.String,
|
|
15
|
+
/** Whether the server answered as someone. */
|
|
16
|
+
signedIn: Schema.Boolean,
|
|
17
|
+
/** Who the server answered as: `declare`'s `key` of the principal. */
|
|
18
|
+
key: Schema.OptionFromNullOr(Schema.String)
|
|
19
|
+
}));
|
|
20
|
+
/**
|
|
21
|
+
* `Me` for guard set `G`: everyone reads their own row, no one writes it, and
|
|
22
|
+
* each interaction is answered in `may` as `G`'s bodies decide it for the
|
|
23
|
+
* asker (`May.can(me.may, OpenAdmin.key)`).
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* const OpenAdmin = Interaction.make('OpenAdmin')
|
|
27
|
+
* export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
const me = (G, options = {}) => MeFields.pipe(Attaching.attach(G, {
|
|
31
|
+
row: {
|
|
32
|
+
Read: [Attaching.anyone],
|
|
33
|
+
Write: []
|
|
34
|
+
},
|
|
35
|
+
...options.interactions === void 0 ? {} : { interactions: options.interactions }
|
|
36
|
+
}), May.member);
|
|
37
|
+
//#endregion
|
|
38
|
+
export { me as n, ME as t };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=me-DeSZOGt3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"me-DeSZOGt3.mjs","names":[],"sources":["../src/me.ts"],"sourcesContent":["/**\n * The visitor as an Entity: one row, `me`, answered for whoever asks. What a\n * client knows about itself (signed in, as whom, what it may open) is read\n * through Remote like any row, `may` included, so no rule runs on the client.\n */\nimport { Schema } from 'effect'\nimport { Entity } from 'foldkit-entity'\nimport { Attaching, type Attach } from './attach.js'\nimport { May } from './may.js'\n\n/** The one row's id. */\nexport const ME = 'me'\n\nconst MeFields = Entity.define(\n 'Me',\n Schema.Struct({\n id: Schema.String,\n /** Whether the server answered as someone. */\n signedIn: Schema.Boolean,\n /** Who the server answered as: `declare`'s `key` of the principal. */\n key: Schema.OptionFromNullOr(Schema.String),\n }),\n)\n\n/** `Me`'s Entity, with `may`. */\nexport type MeEntity = ReturnType<typeof May.member<typeof MeFields>>\n\n/**\n * `Me` for guard set `G`: everyone reads their own row, no one writes it, and\n * each interaction is answered in `may` as `G`'s bodies decide it for the\n * asker (`May.can(me.may, OpenAdmin.key)`).\n *\n * ```ts\n * const OpenAdmin = Interaction.make('OpenAdmin')\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\nexport const me = <Name extends string, User>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n options: {\n readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions']\n } = {},\n): MeEntity =>\n MeFields.pipe(\n Attaching.attach(G, {\n row: { Read: [Attaching.anyone], Write: [] },\n ...(options.interactions === undefined ? {} : { interactions: options.interactions }),\n }),\n May.member,\n )\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,KAAK;AAElB,MAAM,WAAW,OAAO,OACtB,MACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,UAAU,OAAO;;CAEjB,KAAK,OAAO,iBAAiB,OAAO,MAAM;AAC5C,CAAC,CACH;;;;;;;;;;;AAeA,MAAa,MACX,GAKA,UAEI,CAAC,MAEL,SAAS,KACP,UAAU,OAAO,GAAG;CAClB,KAAK;EAAE,MAAM,CAAC,UAAU,MAAM;EAAG,OAAO,CAAC;CAAE;CAC3C,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;AACrF,CAAC,GACD,IAAI,MACN"}
|
package/dist/media.d.mts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { C as PrincipalGuard, S as Policy } from "./attach-BVG6LsFf.mjs";
|
|
2
|
+
import { Effect, Layer, Option } from "effect";
|
|
3
|
+
import { UploadPolicy } from "foldkit-media/server";
|
|
4
|
+
//#region src/media.d.ts
|
|
5
|
+
export interface UploadPolicyConfig<User, E, R> {
|
|
6
|
+
/**
|
|
7
|
+
* Who is asking, from a request holding the upload's URL, method and
|
|
8
|
+
* headers, and no body. A failure means it could not tell (an untrusted
|
|
9
|
+
* origin, a session that ended), answered `401`; none is a visitor.
|
|
10
|
+
*/
|
|
11
|
+
readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>;
|
|
12
|
+
/** Who may upload: any one of these principal guards. Omitted, nobody. */
|
|
13
|
+
readonly Upload?: ReadonlyArray<PrincipalGuard<User>>;
|
|
14
|
+
/** Who may have an image named by URL described. Omitted, nobody. */
|
|
15
|
+
readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* An `UploadPolicy` deciding each route by `policy`'s principal guards for who
|
|
19
|
+
* `resolve` says is asking. A route admits when any one of its guards allows;
|
|
20
|
+
* a refusal's reason stays on the server, as every media refusal says only
|
|
21
|
+
* its kind. `policy` must need no service of its own: give it what its bodies
|
|
22
|
+
* need with `Policy.provide`, as the other seams take it.
|
|
23
|
+
*/
|
|
24
|
+
declare const uploadPolicy: <User, E, R>(policy: Policy<User>, config: UploadPolicyConfig<User, E, R>) => Layer.Layer<UploadPolicy, never, R>;
|
|
25
|
+
export declare const GuardMedia: {
|
|
26
|
+
readonly uploadPolicy: typeof uploadPolicy;
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export {};
|
|
30
|
+
//# sourceMappingURL=media.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":";;;;iBAkBiB,mBAAmB,MAAM,GAAG;;;;;;WAMlC,UAAU,SAAS,YAAY,OAAO,OAAO,OAAO,OAAO,OAAO,GAAG;;WAErE,SAAS,cAAc,eAAe;;WAEtC,cAAc,cAAc,eAAe;;;;;;;;;cAyBhD,eAAgB,MAAM,GAAG,GAAC,QACtB,OAAO,OAAK,QACZ,mBAAmB,MAAM,GAAG,OACnC,MAAM,MAAM,qBAAqB;qBAqBvB;gCAAA"}
|
package/dist/media.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Effect, Layer, Option } from "effect";
|
|
2
|
+
import { HttpServerRequest } from "effect/http";
|
|
3
|
+
import { UploadForbidden, UploadPolicy, UploadUnauthenticated } from "foldkit-media/server";
|
|
4
|
+
//#region src/media.ts
|
|
5
|
+
/**
|
|
6
|
+
* `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard
|
|
7
|
+
* set. Who is asking comes from the application's resolver, the one its
|
|
8
|
+
* Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has
|
|
9
|
+
* the shape), read from the request's headers alone, so the upload route
|
|
10
|
+
* still reads no byte before the policy has answered. Each route is decided by
|
|
11
|
+
* principal guards, since no row exists yet; a route not named is refused.
|
|
12
|
+
*/
|
|
13
|
+
const urlOf = (request) => URL.canParse(request.originalUrl) ? Option.some(new URL(request.originalUrl)) : HttpServerRequest.toURL(request);
|
|
14
|
+
const headersOnly = (request) => Option.map(urlOf(request), (url) => new Request(url, {
|
|
15
|
+
method: request.method,
|
|
16
|
+
headers: request.headers
|
|
17
|
+
}));
|
|
18
|
+
/**
|
|
19
|
+
* An `UploadPolicy` deciding each route by `policy`'s principal guards for who
|
|
20
|
+
* `resolve` says is asking. A route admits when any one of its guards allows;
|
|
21
|
+
* a refusal's reason stays on the server, as every media refusal says only
|
|
22
|
+
* its kind. `policy` must need no service of its own: give it what its bodies
|
|
23
|
+
* need with `Policy.provide`, as the other seams take it.
|
|
24
|
+
*/
|
|
25
|
+
const uploadPolicy = (policy, config) => Layer.effect(UploadPolicy, Effect.map(Effect.context(), (context) => ({ admit: (request, route) => Effect.gen(function* () {
|
|
26
|
+
const asked = yield* Option.match(headersOnly(request), {
|
|
27
|
+
onNone: () => Effect.fail(new UploadUnauthenticated({})),
|
|
28
|
+
onSome: Effect.succeed
|
|
29
|
+
});
|
|
30
|
+
const principal = yield* config.resolve(asked).pipe(Effect.mapError(() => new UploadUnauthenticated({})));
|
|
31
|
+
for (const guard of config[route] ?? []) if ((yield* policy.decide(guard, {
|
|
32
|
+
principal,
|
|
33
|
+
interaction: route
|
|
34
|
+
})) === true) return;
|
|
35
|
+
return yield* new UploadForbidden({});
|
|
36
|
+
}).pipe(Effect.provideContext(context)) })));
|
|
37
|
+
const GuardMedia = { uploadPolicy };
|
|
38
|
+
//#endregion
|
|
39
|
+
export { GuardMedia };
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=media.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media.mjs","names":[],"sources":["../src/media.ts"],"sourcesContent":["/**\n * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard\n * set. Who is asking comes from the application's resolver, the one its\n * Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has\n * the shape), read from the request's headers alone, so the upload route\n * still reads no byte before the policy has answered. Each route is decided by\n * principal guards, since no row exists yet; a route not named is refused.\n */\nimport { Effect, Layer, Option } from 'effect'\nimport { HttpServerRequest } from 'effect/http'\nimport {\n UploadForbidden,\n UploadPolicy,\n UploadUnauthenticated,\n type UploadRoute,\n} from 'foldkit-media/server'\nimport type { Policy, PrincipalGuard } from './index.js'\n\nexport interface UploadPolicyConfig<User, E, R> {\n /**\n * Who is asking, from a request holding the upload's URL, method and\n * headers, and no body. A failure means it could not tell (an untrusted\n * origin, a session that ended), answered `401`; none is a visitor.\n */\n readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>\n /** Who may upload: any one of these principal guards. Omitted, nobody. */\n readonly Upload?: ReadonlyArray<PrincipalGuard<User>>\n /** Who may have an image named by URL described. Omitted, nobody. */\n readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>\n}\n\n// The URL a request arrived at. On the web its `originalUrl` is whole; on a Node server it is a\n// path, and `toURL` rebuilds it from the `Host` header (else `http://localhost`).\nconst urlOf = (request: HttpServerRequest.HttpServerRequest): Option.Option<URL> =>\n URL.canParse(request.originalUrl)\n ? Option.some(new URL(request.originalUrl))\n : HttpServerRequest.toURL(request)\n\n// The URL, method and headers the resolver reads, and never the body: in a Worker,\n// `HttpServerRequest.toWeb` would hand back the request itself, stream and all.\nconst headersOnly = (request: HttpServerRequest.HttpServerRequest): Option.Option<Request> =>\n Option.map(\n urlOf(request),\n url => new Request(url, { method: request.method, headers: request.headers }),\n )\n\n/**\n * An `UploadPolicy` deciding each route by `policy`'s principal guards for who\n * `resolve` says is asking. A route admits when any one of its guards allows;\n * a refusal's reason stays on the server, as every media refusal says only\n * its kind. `policy` must need no service of its own: give it what its bodies\n * need with `Policy.provide`, as the other seams take it.\n */\nconst uploadPolicy = <User, E, R>(\n policy: Policy<User>,\n config: UploadPolicyConfig<User, E, R>,\n): Layer.Layer<UploadPolicy, never, R> =>\n Layer.effect(\n UploadPolicy,\n Effect.map(Effect.context<R>(), context => ({\n admit: (request: HttpServerRequest.HttpServerRequest, route: UploadRoute) =>\n Effect.gen(function* () {\n const asked = yield* Option.match(headersOnly(request), {\n onNone: () => Effect.fail(new UploadUnauthenticated({})),\n onSome: Effect.succeed,\n })\n const principal = yield* config\n .resolve(asked)\n .pipe(Effect.mapError(() => new UploadUnauthenticated({})))\n for (const guard of config[route] ?? []) {\n if ((yield* policy.decide(guard, { principal, interaction: route })) === true) return\n }\n return yield* new UploadForbidden({})\n }).pipe(Effect.provideContext(context)),\n })),\n )\n\nexport const GuardMedia = { uploadPolicy } as const\n"],"mappings":";;;;;;;;;;;;AAiCA,MAAM,SAAS,YACb,IAAI,SAAS,QAAQ,WAAW,IAC5B,OAAO,KAAK,IAAI,IAAI,QAAQ,WAAW,CAAC,IACxC,kBAAkB,MAAM,OAAO;AAIrC,MAAM,eAAe,YACnB,OAAO,IACL,MAAM,OAAO,IACb,QAAO,IAAI,QAAQ,KAAK;CAAE,QAAQ,QAAQ;CAAQ,SAAS,QAAQ;AAAQ,CAAC,CAC9E;;;;;;;;AASF,MAAM,gBACJ,QACA,WAEA,MAAM,OACJ,cACA,OAAO,IAAI,OAAO,QAAW,IAAG,aAAY,EAC1C,QAAQ,SAA8C,UACpD,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO,MAAM,YAAY,OAAO,GAAG;EACtD,cAAc,OAAO,KAAK,IAAI,sBAAsB,CAAC,CAAC,CAAC;EACvD,QAAQ,OAAO;CACjB,CAAC;CACD,MAAM,YAAY,OAAO,OACtB,QAAQ,KAAK,CAAC,CACd,KAAK,OAAO,eAAe,IAAI,sBAAsB,CAAC,CAAC,CAAC,CAAC;CAC5D,KAAK,MAAM,SAAS,OAAO,UAAU,CAAC,GACpC,KAAK,OAAO,OAAO,OAAO,OAAO;EAAE;EAAW,aAAa;CAAM,CAAC,OAAO,MAAM;CAEjF,OAAO,OAAO,IAAI,gBAAgB,CAAC,CAAC;AACtC,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,OAAO,CAAC,EAC1C,EAAE,CACJ;AAEF,MAAa,aAAa,EAAE,aAAa"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/origin.ts
|
|
2
|
+
const origins = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */
|
|
4
|
+
const originOf = (policy) => origins.get(policy) ?? policy;
|
|
5
|
+
/** Records `policy` as provided from `from`. */
|
|
6
|
+
const providedFrom = (policy, from) => {
|
|
7
|
+
origins.set(policy, originOf(from));
|
|
8
|
+
return policy;
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { providedFrom as n, originOf as t };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=origin-CN6ThFTp.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"origin-CN6ThFTp.mjs","names":[],"sources":["../src/origin.ts"],"sourcesContent":["/**\n * Which Policy another was provided from, so a seam built from one counts as\n * built from the other: `Policy.provide` keeps the bodies and rules, and\n * changes only the services they run with. `validate` checks that a seam's\n * rules are the declared ones; it does not check which services they were\n * given.\n */\nimport type { Policy } from './index.js'\n\nconst origins = new WeakMap<object, object>()\n\n/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */\nexport const originOf = (policy: Policy<any, any>): object => origins.get(policy) ?? policy\n\n/** Records `policy` as provided from `from`. */\nexport const providedFrom = <P extends Policy<any, any>>(policy: P, from: Policy<any, any>): P => {\n origins.set(policy, originOf(from))\n return policy\n}\n"],"mappings":";AASA,MAAM,0BAAU,IAAI,QAAwB;;AAG5C,MAAa,YAAY,WAAqC,QAAQ,IAAI,MAAM,KAAK;;AAGrF,MAAa,gBAA4C,QAAW,SAA8B;CAChG,QAAQ,IAAI,QAAQ,SAAS,IAAI,CAAC;CAClC,OAAO;AACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
1
|
+
import { r as attached } from "./attach-BZyVvs7H.mjs";
|
|
2
|
+
import { t as originOf } from "./origin-CN6ThFTp.mjs";
|
|
2
3
|
import { Option } from "effect";
|
|
3
4
|
//#region src/placed.ts
|
|
4
5
|
/**
|
|
@@ -24,7 +25,7 @@ const record = (registry) => ({
|
|
|
24
25
|
has: (built, policy, entity) => {
|
|
25
26
|
if (typeof built !== "function" && (typeof built !== "object" || built === null)) return false;
|
|
26
27
|
const placed = registry.get(built);
|
|
27
|
-
return placed !== void 0 && placed.policy === policy && placed.entities.has(entity.name) && placed.entities.get(entity.name) === guardsOf(entity);
|
|
28
|
+
return placed !== void 0 && originOf(placed.policy) === originOf(policy) && placed.entities.has(entity.name) && placed.entities.get(entity.name) === guardsOf(entity);
|
|
28
29
|
}
|
|
29
30
|
});
|
|
30
31
|
/** Row rules: `GuardDrizzle.visible`'s, and `GuardServer.memory`'s `readable`. */
|
|
@@ -36,4 +37,4 @@ const writeRules = record(/* @__PURE__ */ new WeakMap());
|
|
|
36
37
|
//#endregion
|
|
37
38
|
export { rowRules as n, writeRules as r, memberRules as t };
|
|
38
39
|
|
|
39
|
-
//# sourceMappingURL=placed-
|
|
40
|
+
//# sourceMappingURL=placed-CkyMqxFw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"placed-CkyMqxFw.mjs","names":[],"sources":["../src/placed.ts"],"sourcesContent":["/**\n * What each guard seam built, and for which Policy and Entities, so\n * `GuardServer.validate` can tell a Source that applies a guard set's rules\n * from one that only looks as if it does.\n */\nimport { Option } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport { attached, type Attachment } from './attach.js'\nimport type { Policy } from './index.js'\nimport { originOf } from './origin.js'\n\ninterface Placed {\n readonly policy: Policy<any, any>\n /** Each Entity's attachment as it was built from: none for one built before `attach`. */\n readonly entities: ReadonlyMap<string, Attachment | undefined>\n}\n\n/** An Entity's guards, by identity: the same attachment is the same rules. */\nconst guardsOf = (entity: AnyEntity) => Option.getOrUndefined(attached(entity))\n\nconst record = (registry: WeakMap<object, Placed>) => ({\n add: <F extends object>(built: F, policy: Policy<any, any>, entities: Iterable<AnyEntity>): F => {\n registry.set(built, {\n policy,\n entities: new Map([...entities].map(entity => [entity.name, guardsOf(entity)])),\n })\n return built\n },\n /**\n * Whether `built` applies `entity`'s guards from `policy`: built for it,\n * not for another Entity of its name, nor for it before its guards were\n * attached, which decides nothing.\n */\n has: (built: unknown, policy: Policy<any, any>, entity: AnyEntity): boolean => {\n if (typeof built !== 'function' && (typeof built !== 'object' || built === null)) return false\n const placed = registry.get(built)\n return (\n placed !== undefined &&\n originOf(placed.policy) === originOf(policy) &&\n placed.entities.has(entity.name) &&\n placed.entities.get(entity.name) === guardsOf(entity)\n )\n },\n})\n\n/** Row rules: `GuardDrizzle.visible`'s, and `GuardServer.memory`'s `readable`. */\nexport const rowRules = record(new WeakMap())\n\n/** Member and relation rules: `GuardServer.filter`'s. */\nexport const memberRules = record(new WeakMap())\n\n/** Write rules: `GuardServer.writer`'s. */\nexport const writeRules = record(new WeakMap())\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,YAAY,WAAsB,OAAO,eAAe,SAAS,MAAM,CAAC;AAE9E,MAAM,UAAU,cAAuC;CACrD,MAAwB,OAAU,QAA0B,aAAqC;EAC/F,SAAS,IAAI,OAAO;GAClB;GACA,UAAU,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,MAAM,CAAC,CAAC,CAAC;EAChF,CAAC;EACD,OAAO;CACT;;;;;;CAMA,MAAM,OAAgB,QAA0B,WAA+B;EAC7E,IAAI,OAAO,UAAU,eAAe,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO;EACzF,MAAM,SAAS,SAAS,IAAI,KAAK;EACjC,OACE,WAAW,KAAA,KACX,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,KAC3C,OAAO,SAAS,IAAI,OAAO,IAAI,KAC/B,OAAO,SAAS,IAAI,OAAO,IAAI,MAAM,SAAS,MAAM;CAExD;AACF;;AAGA,MAAa,WAAW,uBAAO,IAAI,QAAQ,CAAC;;AAG5C,MAAa,cAAc,uBAAO,IAAI,QAAQ,CAAC;;AAG/C,MAAa,aAAa,uBAAO,IAAI,QAAQ,CAAC"}
|
package/dist/server.d.mts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
|
-
import { S as Policy, l as InteractionKey } from "./attach-
|
|
1
|
+
import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BVG6LsFf.mjs";
|
|
2
2
|
import { Effect, Option } from "effect";
|
|
3
3
|
import { AnyEntity, AnyQuery } from "foldkit-entity";
|
|
4
4
|
import { EntitySource, EntityWriter, MemoryReadable, MutationOutcome, MutationRefused, MutationSource, ReadPlan, RemoteServerError, ServerDefinition } from "foldkit-remote-server";
|
|
5
5
|
import { MutationDescriptor, RemoteForbidden } from "foldkit-remote";
|
|
6
6
|
//#region src/server.d.ts
|
|
7
7
|
export declare const GuardServer: {
|
|
8
|
+
/**
|
|
9
|
+
* `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`
|
|
10
|
+
* answered by `policy`. `signedIn` is whether the server answered as
|
|
11
|
+
* someone; `key` is their `key`. Any other id is no row.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
me: <User, R>(entity: MeEntity, policy: Policy<User, R>) => EntitySource<Option.Option<User>, R>;
|
|
8
18
|
/**
|
|
9
19
|
* An `EntitySource.filter` for `entity`: each requested member with a Read
|
|
10
20
|
* rule is decided per record, omitted or redacted where the rule refuses.
|
package/dist/server.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],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;;EA6FhD,WAAW,MAAM,GAAC,QACR,OAAO,MAAM,IAAE;aAEZ,UAAU,cAAc;;aAExB;eACE;iBACE,SAAS;mBAEL;mBAA0B,OAAO;;;;aAIzC,QAAQ"}
|
package/dist/server.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as Condition } from "./condition-
|
|
3
|
-
import
|
|
1
|
+
import { o as readRowsRuled, r as attached, s as readRuled } from "./attach-BZyVvs7H.mjs";
|
|
2
|
+
import { t as Condition } from "./condition-Dunujvzy.mjs";
|
|
3
|
+
import "./me-DeSZOGt3.mjs";
|
|
4
|
+
import { n as rowRules, r as writeRules, t as memberRules } from "./placed-CkyMqxFw.mjs";
|
|
4
5
|
import { Effect, Match, Option, Schema } from "effect";
|
|
5
6
|
import { Query } from "foldkit-entity";
|
|
6
7
|
import { RemoteServer, RemoteServerError } from "foldkit-remote-server";
|
|
@@ -23,6 +24,36 @@ const refOf = (value) => {
|
|
|
23
24
|
});
|
|
24
25
|
};
|
|
25
26
|
const GuardServer = {
|
|
27
|
+
/**
|
|
28
|
+
* `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`
|
|
29
|
+
* answered by `policy`. `signedIn` is whether the server answered as
|
|
30
|
+
* someone; `key` is their `key`. Any other id is no row.
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
me: (entity, policy) => {
|
|
37
|
+
Option.map(attached(entity), ({ set }) => {
|
|
38
|
+
if (set !== policy.set) throw new Error(`[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`);
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
...RemoteServer.entity(entity, {
|
|
42
|
+
read: ({ ids, principal }) => Effect.succeed(ids.filter((id) => id === "me").map((id) => ({
|
|
43
|
+
id,
|
|
44
|
+
values: {
|
|
45
|
+
signedIn: Option.isSome(principal),
|
|
46
|
+
key: Option.match(principal, {
|
|
47
|
+
onNone: () => null,
|
|
48
|
+
onSome: policy.key
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
}))),
|
|
52
|
+
filter: GuardServer.filter(entity, policy)
|
|
53
|
+
}),
|
|
54
|
+
visible: rowRules.add(Object.freeze({ reads: "the asker’s own row" }), policy, [entity])
|
|
55
|
+
};
|
|
56
|
+
},
|
|
26
57
|
/**
|
|
27
58
|
* An `EntitySource.filter` for `entity`: each requested member with a Read
|
|
28
59
|
* rule is decided per record, omitted or redacted where the rule refuses.
|