Guard / foldkit-guard/server

GuardServer

namespace · packages/guard/src/server.ts:129

const GuardServer = { me, filter, memory, writer, mutation, validate }

In the guides

Members

GuardServer.me

function · packages/guard/src/server.ts:139

me<User, R>(
  entity: MeEntity,
  policy: Policy<User, R>,
): EntitySource<Option.Option<User>, R>

Guards.me's Source: the one row, me, as the asker is, with may answered by policy. signedIn is whether the server answered as someone; key is their key. Any other id is no row.

ts
RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })

GuardServer.filter

function · packages/guard/src/server.ts:187

filter<User, R>(
  entity: AnyEntity,
  policy: Policy<User, R>,
): (
  principal: Option.Option<User>,
  fields: readonly string[],
) => Effect.Effect<ReadPlan, never, R>

An EntitySource.filter for entity: each requested member with a Read rule is decided per record, omitted or redacted where the rule refuses. The fields a rule reads are read too, so it can be decided.

ts
RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })

GuardServer.memory

function · packages/guard/src/server.ts:267

memory<User>(
  policy: Policy<User>,
  entities: ReadonlyArray<AnyEntity>,
): {
  readable: (
    principal: Option.Option<User>,
    row: (
      entity: string,
      id: string,
    ) => Option.Option<Readonly<Record<string, unknown>>>,
  ) => Effect.Effect<MemoryReadable>
  filter: {
    [k: string]: (
      principal: Option.Option<User>,
      fields: readonly string[],
    ) => Effect.Effect<ReadPlan, never, never>
  }
}

RemoteServer.memory's readable and filter for entities, the Entities as Guards.attach returned them. A row's Read is decided per stored row, an inherited Read by looking the related row up; an Entity not listed is read by everyone. A Read rule that reads another row (a path, an exists) is refused here: each stored row is judged alone, and only a statement judges such a rule (GuardDrizzle.visible).

GuardServer.writer

function · packages/guard/src/server.ts:380

writer<E extends AnyEntity, User, R, RW>(
  entity: E,
  policy: Policy<User, R>,
  writer: EntityWriter<Option.Option<User>, RW>,
  options?: {
    readonly revision?: keyof E['fields'] & string
    readonly children?: ReadonlyArray<AnyEntity>
  },
): EntityWriter<Option.Option<User>, R | RW>

writer with entity's write rules checked before each write lands, for RemoteServer.write. An update or a delete reads the row first under the writer's own read (its Source's read rule): a row the writer may not see is refused as one that is not there, and a delete of it changes nothing. Then the row's rule for the command must hold over the row, each member it sets must allow setting it, and each relation it points elsewhere must allow the unlink and the link. An update's row rule holds over the row as it would be after it too, so a write cannot move a row out of its writer's reach. Each of its member and Link rules holds over the row after with that one change undone (that member's value, or where that relation pointed, as before): the change must be allowed given everything else the write does, so one write cannot set together what each change alone would be refused, while a rule reading its own member ("only while a draft") still allows the change. An increment or a computed assignment to a member is that member's own change. An Unlink rule holds over the row before alone. A create's rules hold over the values it proposes, where a field the create leaves unset matches no guard, not even one for an empty value. A refusal is Forbidden, with the sentence an explain gave, or Unauthenticated for a visitor; the write never runs.

What the Entity sets from the write's context (Entity.sets: who asks, when) reaches a create or an update already set by RemoteServer.write, so a rule over it holds of the creator. A member rule over such a member judges the server's value like any other: declare none there.

revision names a field stored as a number, which the writer moves on by one with each write it lands. An update or a delete then lands only on the revision its rules were decided over (the writer's expect), so a change between the check and the write is never written over; it is decided again against the row as it now is, up to three times. A change that does not move the revision (a handler's, applyEdits', raw SQL) is not seen. Without revision, none is, and validate warns of an update, or a delete of an Entity the server updates (an insert has no row). An input that expects a revision the row read is not at is a Conflict, decided before any rule; an input may expect only the field the writer pins.

A delete that cascades (Relation.one(…, { onDelete: 'cascade' })) holds each row it takes to that row's own Delete rule, for the same person, in the statement that deletes (#348): one refused, and the whole delete is Forbidden, naming the Entity, and nothing is removed. A relation declared authorizedBy: 'parent' lets whoever may delete the row take the rows pointing at it through that relation unjudged. The rules of an Entity taken under its own are read from its guarded descriptor, given as children; one missing is refused where the writer is made.

An Update or Delete rule that reads another row (a path, an exists), and each such rule of a row a delete takes or unlinks, decides from a row a concurrent write can change. It is held to its writer's store as a data rule over other rows is (needs): RemoteServer.write refuses the write on a store that does not run the writers under one parent one at a time (Postgres at read committed with no parent lock), naming the guard. SQLite and D1 hold it, since the writer judges it in the statement that writes.

ts
RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })

GuardServer.mutation

function · packages/guard/src/server.ts:1142

mutation<User, R, RS, RM, Name extends string, Input, Output, Refused>(
  mutation: MutationDescriptor<Name, Input, Output, Refused>,
  guard: {
    readonly entity: AnyEntity
    readonly policy: Policy<User, R>
    readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey
    readonly id?:
      ((input: Input) => string | Option.Option<string>) | undefined
    readonly source: EntitySource<Option.Option<User>, RS>
    readonly fields?: ReadonlyArray<string> | undefined
  },
  run: (context: {
    readonly input: Input
    readonly principal: Option.Option<User>
    readonly requestId: string
    readonly row: Option.Option<Readonly<Record<string, unknown>>>
  }) => Effect.Effect<
    MutationOutcome<Output>,
    RemoteServerError | MutationRefused | RemoteForbidden,
    RM
  >,
): MutationSource<Option.Option<User>, R | RS | RM>

A handler's Source (RemoteServer.mutation's) with entity's rule for interaction checked before it runs. The row the input names (id) is read through source, which must apply the Entity's Read rules, and the rule must hold over it; a row its writer may not see is refused. With no id (a create), the rule must hold of who is asking alone, a field it reads matching no guard. run is given the row as read: its fields the rule reads, its id, and fields. A refusal is Forbidden, or Unauthenticated for a visitor; run never runs. What run writes is its own: check members it sets there. Each row of entity its answer carries is read back through source, so the answer shows its writer only what they may see, a row it hid from them as deleted.

A rule for interaction that reads another row (a path, an exists) is refused here, where the handler is made: this check reads one row and runs no statement. A declared write through GuardServer.writer is held to such a rule.

ts
GuardServer.mutation(ArchiveTodo, {
  entity: Todo, policy: Policy, interaction: Archive.key,
  id: input => input.id, source: source(Db.Todo),
}, ({ input, row }) => …)

GuardServer.validate

function · packages/guard/src/server.ts:1276

validate<User, R>(
  policy: Policy<User, R>,
  config: {
    readonly entities: ReadonlyArray<AnyEntity>
    readonly domain: {
      readonly registry: {
        readonly queries: ReadonlyMap<
          string,
          {
            readonly Result: unknown
            readonly body?: AnyQuery | undefined
          }
        >
      }
    }
    readonly server: ServerDefinition<any, any>
    readonly diagnostics?: ReportDiagnostic | undefined
  },
): void

Checks, at startup, that server applies the guards of entities, the Entities as Guards.attach returned them: each one's Source and each query listing it apply its row's Read rules (GuardDrizzle.visible, or GuardServer.memory), its Source applies its members' and relations' (GuardServer.filter), and each declared write of it lands through GuardServer.writer, all built from policy; and that no query's body filters or orders by a member with a Read rule, its own or one of a row it reaches through a path or an exists, which would answer for the value it hides. A hand-written Source over a guarded Entity would serve every row, and a bare writer would take every write; this throws instead, naming each. A handler (RemoteServer.mutation) writes what its code writes, which no check at startup can read. A write a change can come between, through a writer given no revision, is not refused but reported: UnpinnedWrites, a warning, to diagnostics.

ts
GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })