Auth / Auth and Guard

Sharing one principal type across client and server

Your guard set declares the principal schema, and foldkit-auth's principal callback returns a value matching it. That schema is the entire contract between the two packages (from examples/auth/src/domain.ts):

ts
import { Schema } from 'effect'
import { Entity, Expr } from 'foldkit-entity'
import { Guards } from 'foldkit-guard'

export const User = Schema.Struct({
  id: Schema.String,
  role: Schema.Literals(['admin', 'member']),
})
export type User = typeof User.Type

const NoteFields = Entity.define(
  'Note',
  Schema.Struct({ id: Schema.String, authorId: Schema.String, title: Schema.String }),
)

export const G = Guards.declare(
  'Notes',
  User,
  guard => ({
    isAdmin: guard.principal(),
    isAuthor: guard.row(NoteFields, p => Expr.eq(NoteFields.fields.authorId, p.id)),
  }),
  { key: user => user.id, unguarded: 'deny' },
)

export const Note = NoteFields.pipe(Guards.attach(G, { row: { Read: [G.isAuthor, G.isAdmin] } }))

Both browser and server import this shared domain file. isAdmin is declared here as a named predicate whose server implementation stays private, while isAuthor is a data expression (Expr) that compiles directly to SQL (see Expressions).

On the server, wire both into one endpoint (reduced from examples/auth/src/server.ts, where AppAuth, AppAuthLive, http, Users, and server come from your app's auth and server setup):

ts
import { Option } from 'effect'
import { AuthServer } from 'foldkit-auth/server'
import { RemoteServer } from 'foldkit-remote-server'
import { serveFetch } from 'foldkit-remote-server/fetch'

// Guard: server-only bodies for principal predicates.
const Policy = G.implement({
  isAdmin: principal => Option.exists(principal, user => user.role === 'admin'),
})

// Auth: look up the current User per request rather than trusting old claims.
const principal = (session: { readonly subjectId: string }) => Users.find(session.subjectId)

const resolving = { auth: AppAuth, http, principal, key: Policy.key }

export const remote = serveFetch({
  server,
  resolvePrincipal: AuthServer.resolver(resolving),
  headers: AuthServer.answered(resolving),
  layer: () => AppAuthLive,
})

serveFetch resolves the principal once per request and hands it to your server Sources, marking responses cache-control: no-store by default so user-specific answers stay private.