Skip to content

Sessions and access ​

Designed, not built. This page is the design for who is connected, what each connection may see and change, and what a device keeps per user. It is built with the protocol, server and client slices, and changes some of what is built (appendix H); the appendices hold the detail.

Twinstate pushes shared state to many connections and keeps work on the device, so it cannot leave access to "each request checks its viewer" the way a request/response API can. Three rules cover it:

  1. The context is who is connected, nothing more; everything else is data. A connection's context is its claims: the user's id, and anything the session itself carries (a role in a token). A plan, a membership or a profile is a record, which syncs, which handlers read in their turn, and which policies read too.
  2. Every field says who may read it and who may write it; every record says who may know it exists, create it and remove it. No default, and no exception for single-user apps: a field without both policies does not compile, so a new field is always a decision.
  3. Policies are plain functions of the context, the record, and the records they read, shared with the client, run by the server on every delivery and every client write. What a policy reads is tracked, so its answer is re-checked whenever any of it changes.

Connecting ​

ts
// server: who is connecting, or refuse the connection
createTwinServer(twin, {
  connect: async ({ hello, request }) => {
    const cookie = sessionCookie(request.headers.cookie);
    if (!cookie) return { ctx: guest }; // no session at all: your guest object (below)
    const session = await sessions.verify(cookie); // your auth
    if (session?.expired) return refuse('expired'); // refreshable: the app refreshes and reconnects
    if (!session?.valid) return refuse('signedOut'); // unknown or revoked: refused, never a guest
    return {
      ctx: { userId: idOf(user).parse(session.userId), signedIn: true }, // who (tx.ctx)
      connection: { sessionId: session.id, expiresAt: session.expiresAt }, // this connection (tx.connection)
    };
  },
  scope: (ctx) => (ctx.userId ? [ctx.userId] : []),
  // store, handlers, …
}).serve(wsServerTransport({ server: http, origins: ['https://app.example.com'] })); // origins required

// client: whose device data this is
createTwinClient(twin, { scope: me ? [me.id] : [], transport, onIncompatible });

connect returns two things:

  • ctx, who is connected: read by policies and handlers (tx.ctx), the same in every session and tab of one user whose sessions carry the same claims, and covered by the reconnect fingerprint. It is plain JSON (the compiler checks) and small: the user's id, and what the session itself carries.
  • connection, this connection's own details: free-form, for your matches and handlers (tx.connection), plus expiresAt, the one key Twinstate reads: it closes the connection then, as expired. Policies never see it, so a refreshed session is the same context, and nothing on the device resets.

A guest is whatever your app makes it: the context's shape is yours, and Twinstate only passes it to your policies and handlers. The recommended shape is a guest object rather than null, as policy libraries such as Pundit advise:

ts
type Ctx = { userId: Id<'user'>; signedIn: true } | { userId: 'guest:'; signedIn: false }; // an id no record can hold: ids never contain ':'
const guest: Ctx = { userId: 'guest:', signedIn: false }; // no cast: it is its own type
// `ctx.signedIn && …` narrows `ctx.userId` to `Id<'user'>`

Pitfall: guests and null. In JavaScript null === null is true, so a guest with userId: null passes any policy that compares it with a field that is also null (record.voter === ctx.userId). Postgres has no such trap: there, comparing two NULLs is never true. An id that can never match a record's makes every identity comparison false for guests, with nothing to remember; a rule that must exclude guests in other ways reads ctx.signedIn.

refuse(reason) is for a connection that must not get in, and it receives nothing but refused.

ctxconnectionrecords
the user's id; what the session carries (a role in a token, an SSO group)sessionId, expiresAt, the deviceeverything else: plans, memberships, teams, profiles (name, bio, birthday)

The session's own changes are the only context changes, and they come from outside Twinstate, so the app reports them:

whenthe app callswhat happens
the session gains a new role or groupserver.refresh(match)connect runs again for those connections; an equal context changes nothing, a new one re-projects what they hold; one that throws, refuses or yields another scope(ctx) refuses the connection (scopeMismatch for the last)
access must end now (logged out elsewhere, banned)server.disconnect(match, reason)the connection is refused and closed

A match receives the connection, ({ ctx, connection }) => … (connection is always an object, {} when connect gives none), so server.disconnect(({ connection }) => connection.sessionId === sid, 'signedOut') ends one session everywhere. Two options cover a session store Twinstate cannot watch: revalidate: { every: '5m' } re-runs connect on a schedule, and revalidate: { mutations: true } before every mutation, so a write refuses a revoked session at once, as an HTTP request would. A record change needs none of this: policies read records directly.

Policies ​

ts
// policies.ts: shared, pure functions of one argument: { ctx, record, before, after, get }
export const signedIn = policy(({ ctx }) => ctx.signedIn);
export const author = policy(
  ({ ctx, record }: { ctx: Ctx; record: { authorId: Id<'user'> } }) =>
    record.authorId === ctx.userId,
);
export const readable = policy(
  (a: { ctx: Ctx; record: { public: boolean; authorId: Id<'user'> } }) =>
    a.record.public || author(a),
);
export const self = policy(
  ({ ctx, record }: { ctx: Ctx; record: { id: Id<'user'> } }) => record.id === ctx.userId,
); // records keyed by the user: their own only
// `account` is an instant kind whose `read` is `self`: each client receives only its own
export const paid = policy(
  ({ ctx, get }) => ctx.signedIn && get(account, ctx.userId)?.plan === 'paid',
);

// twin.ts
const post = kind(
  'post',
  {
    title: field(z.string()).read(everyone).write(author),
    body: field(z.string()).read(everyone).write(author),
    public: field(z.boolean().default(false)).read(everyone).write(author),
    votes: field(z.number().default(0)).read(everyone).write(nobody), // server-computed
    draftNotes: field(z.string().default('')).read(author).write(author), // others read null
    stats: field(z.number().default(0)).read(paid).write(nobody), // paid users only, read from their account
    authorId: field(idOf(user)).read(everyone).write(nobody),
  },
  {
    id: true,
    load: 'lazy',
    ops: ['create', 'update', 'remove'],
    read: readable, // who knows the post exists
    create: author, // the new post must name you as its author
    remove: author,
  },
);
operationchecked againstthe policy receives
read a recordthe record's read (does this viewer know it exists?), then each field's readrecord: the current one
createthe record's create, oncerecord: the new one, as proposed
updateeach changed field's write, and the record's optional update guardbefore and after, and record, which is before: a one-record policy (author) asks "are you the author now"
removethe record's remove, oncerecord: the one about to go

Every policy also gets ctx and get, all in one object, so a policy written for reading also works as a write. One that checks the result reads after, as an ownership transfer to one of the post's editors does:

ts
authorId: field(idOf(user)).read(everyone)
  .write(({ ctx, before, after }) =>
    before.authorId === ctx.userId && after.editorIds.includes(after.authorId)),

get reads other records, and its reads are tracked. Each get is recorded against the record it read, a miss included (a record created later re-checks it), so when the account's plan changes, every record whose policy read it is re-checked for every connection holding it, and the change reaches them like any other. Policies are pure and synchronous, so get reads only what the server always holds in memory: instant kinds, which the compiler checks (get takes no other kind). The lint rule that keeps effects pure rejects the clock, randomness and anything else from outside a policy's arguments. Access that depends on time is data: a scheduled commit flips published at publishAt, and the change reaches everyone like any other; a session's end is its connection's expiresAt.

Or copy a fact into the context, when it does not live in your data:

get in policies (the default)a fact in ctx
freshnessalways current, trackedcurrent until the session changes: server.refresh
where it livesrecords onlythe session or token
costa tracked read per evaluation; reads instant kinds onlynone per evaluation; the context must stay small
use forfacts in your data: plans, memberships, teams, ownershipfacts outside it: a role in a JWT, an SSO group

Removing a record takes its children and the records keyed by it with it, as in concepts (checked by its own remove only); what it refs stays, unless a handler removes it, each removal checked by that kind's own remove.

everyone and nobody are built in. A client's whole turn passes or is rejected with the new built-in reason forbidden, with nothing applied; a mutation sent by server code (from: 'server', no client behind it) is not checked. serverOnly(schema) is the shorthand for a field no client ever reads or writes: it stands in for field(schema) with both policies at once, and, since that never varies per viewer, it is left out of client types rather than made nullable.

On the client ​

A field a viewer may not read arrives as null, typed T | null wherever its read policy is not everyone; fieldState tells hidden from empty:

ts
const p = useShared(postHandle); // a lazy root, through the handle its entry received
p.draftNotes ?? ''; // null for anyone but the author
fieldState(p, 'draftNotes'); // { hidden: true, pending: false }

On the device ​

Everything Twinstate keeps on a device lives under the registry's name and the client's scope. A scope's outbox is never deleted except on request (the cache still sweeps saved topics it no longer needs, as in the client):

ts
await client.settled(); // unsent work sent (or rejected)
client.close(); // keep this user's data, or…
await client.delete(); // …remove it (refused while work is unsent, unless { discard: true })

Appendices ​

A. Sessions: register, log in, resume, refresh, log out ​

Auth itself is the app's HTTP; Twinstate starts once there is a session. A different user is a different client.

ts
// outside React: one client per session; a new user closes the previous client
let current: { userId: string; client: TwinClient } | null = null;
function clientFor(s: Session): TwinClient {
  if (current?.userId !== s.userId) {
    current?.client.close();
    current = { userId: s.userId, client: createTwinClient(twin, { scope: [s.userId], transport, onIncompatible }) };
  }
  return current.client; // the same client on every render, StrictMode's double render included
}

function App() {
  const { session } = useSession(); // your auth state
  if (!session) return <LoginScreen />; // register / log in: plain HTTP
  return (
    <TwinProvider client={clientFor(session)} key={session.userId}>
      …
    </TwinProvider>
  );
}
  • Register / log in: the auth endpoint sets the session cookie; the app creates that user's client; entries preload against it.
  • Resume: the stored user id picks the scope, so the cache and the outbox open offline; online, the cookie connects.
  • Refresh: with cookies, the connection carries expiresAt (from connect's connection); the server disconnects with refused('expired'), the app refreshes over HTTP and calls client.reconnect() (topics resume, nothing is refetched: the context, who is connected, is unchanged). With a token instead of a cookie, the client's hello is a function, read on every connect (hello: () => ({ token: session.token })), so refreshing the token and calling reconnect() sends the new one.
  • Log out:
ts
async function logout(client: TwinClient, wipe: boolean) {
  await client.settled(); // offline: offer "log out anyway" → delete({ discard: true })
  if (wipe) await client.delete();
  else client.close();
  await fetch('/logout', { method: 'POST' }); // clears the cookie; calls server.disconnect for its session
}
  • Switch account: the app's session changes, clientFor closes the previous client and starts one with the other scope.
  • Refused: useSyncStatus() reports { state: 'refused', reason }, typed from connect; nothing retries until the app calls reconnect().

B. CRUD, end to end ​

ts
// twin.ts: the mutations, in the registry
mutations: {
  createPost: mutation(
    z.strictObject({ id: idOf(post), authorId: idOf(user), title: z.string(), body: z.string() }),
    { effect: (d, a) => { d.create(post, a.id, { authorId: a.authorId, title: a.title, body: a.body }); } },
  ),
  editPost: patch(post, { fields: ['title', 'body', 'public', 'draftNotes'] }),
  removePost: mutation(z.strictObject({ id: idOf(post) }), { effect: (d, a) => { d.remove(post, a.id); } }),
},

// server: the handlers
handlers: {
  // create: post's `create` (author) runs once, so a forged authorId is forbidden
  createPost: async (a, tx) => { await tx.create(post, a.id, { authorId: a.authorId, title: a.title, body: a.body }); },
  // remove: post's `remove` (author) runs once; field policies do not
  removePost: async ({ id }, tx) => { await tx.remove(post, id); },
},

// client
const [create] = useMutation(twin.mutations.createPost);
create({ id: newId(post), authorId: me.id, title, body }); // the client knows who it is from its session
const p = useShared(postHandle); // read: projected by the policies
const [edit] = useMutation(twin.mutations.editPost);
edit({ id: p.id, patch: { title: 'New' } }); // update: each changed field's `write` (author): ok, or forbidden

The effect gets the author's id from its arguments, never from outside: an effect reads only its arguments and the draft. The server's create policy is what makes that argument trustworthy.

Writes across the floor: votes. Anyone signed in may vote on a post, but votes is write(nobody), so no client can set a count, and Bob's turn cannot change Alice's post. The better answer is to model it so the floor fits: a vote is a record of its own, owned by its voter, and the count is the server's own work (a mutation from: 'server', which no client stands behind, so no policy checks it). It also gives one vote per user, and undoing it, for free:

ts
const voterIsYou = policy(({ ctx, record }: { ctx: Ctx; record: { voter: Id<'user'> } }) =>
  record.voter === ctx.userId); // a guest's id matches no voter
const vote = kind(
  'vote',
  { post: field(idOf(post)).read(everyone).write(nobody), voter: field(idOf(user)).read(everyone).write(nobody) },
  { id: true, belongsTo: { kind: () => post, by: 'post', order: 'voter asc' }, ops: ['create', 'remove'],
    read: withParent, create: voterIsYou, remove: voterIsYou },
);

// in the registry: vote: mutation(z.strictObject({ id: idOf(post) }), { rejects: ['signedOut'] }),
vote: async ({ id }, tx) => {
  if (!tx.ctx.userId) return tx.reject('signedOut');
  await tx.create(vote, tx.childId(vote, id, tx.ctx.userId), { post: id, voter: tx.ctx.userId }); // one per voter
  tx.afterEveryCommit(() => server.mutate(twin.mutations.recount, { id })); // the count: the server's own work
},

When remodelling is not worth it, one write can skip the policies, visibly. The name is the warning, and the reason is required, so every such write is easy to find and explains itself in review (a lint rule flags one without a reason); only what runs inside it is unchecked:

ts
vote: async ({ id }, tx) => {
  if (!tx.ctx.userId) return tx.reject('signedOut');
  await tx.dangerouslySkipPolicies('vote counts are written for every voter', (s) =>
    s.update(post, id, (p) => { p.votes += 1; }));
},

It is Supabase's service role, or a database's SECURITY DEFINER function: the floor can be crossed, never silently. Prefer the first form; this one exists for the rare write that has no better shape.

A plan change is data. The paid policy read the account through get, so one write is all it takes: every record whose policy read it is re-checked, and paid content arrives:

ts
// the payment webhook; setPlan is a mutation `from: 'server'`
await server.mutate(twin.mutations.setPlan, { userId, plan: 'paid' }, { key: event.id });

C. Trees: embedded and child records ​

Each kind declares its record read; withParent means "wherever what holds it is visible". An edge into a kind with any other read is nullable.

ts
const owner = policy(
  ({ ctx, record }: { ctx: Ctx; record: { ownerId: Id<'user'> } }) => record.ownerId === ctx.userId,
);
const image = kind(
  'image',
  {
    url: field(z.string()).read(everyone).write(owner),
    private: field(z.boolean().default(false)).read(everyone).write(owner),
    ownerId: field(idOf(user)).read(everyone).write(nobody),
  },
  {
    id: true,
    embedded: true,
    ops: ['create', 'remove'],
    read: (a) => !a.record.private || owner(a),
    create: owner,
    remove: owner,
  },
);

body.images; // (Image | null)[]: image has a read of its own
body.comments; // a child list: what you may not see is left out

A nested value inside a field shares that field's policies; a part that needs its own is its own kind, so every layer of the tree decides for itself. When a record leaves a viewer (del), what it holds with withParent leaves with it; when it arrives (set), they arrive with it.

D. Delivery: projection and batching ​

Each change is checked per connection, before and after, and each turn reaches each connection as one message, its projection of the turn (a tick's turns are grouped per topic). For the post above:

a turn…the authora reader who keeps accessa reader who loses or gains access
edits title and bodyevery patchthe same patches—
edits only draftNotesthe patchnothing—
removes the postdeldel—
sets public: falsethe patch—loses: del
sets public: truethe patch—gains: the post (set), projected

A turn that changed only what a viewer may not read sends that viewer nothing at all, not even an empty message. The replay ring keeps the raw changes and projects them when sending.

On reconnect, a replay is only right if the client's data was projected under the context it has now. So ready carries a fingerprint of the context (signed by the server, revealing nothing; the connection's details are not in it), and the client keeps it with each topic's position. Since the context is only who is connected, it rarely differs. The same fingerprint resumes from the ring; a different one resets those topics under the new context: a lazy root no longer visible is answered absent, windows are recomputed, cached copies replaced. While connected, a context change needs no reset: the server holds both contexts and sends only what flipped.

E. Device data and scopes ​

  • The key is twinstate:<name>:<hash of scope>:; an internal index lists the scopes a device holds.
  • The client sends its scope in hello; if the server's scope(ctx) differs (another tab changed user under the same cookie), it is refused as scopeMismatch before any outbox entry is sent.
  • Changing the scope's shape is a migration of device data: open the old scope, settled(), delete().

F. Constraints, and what they buy ​

  • Policies read the context, the record, and what get gives them. A record's visibility then changes only when it changes, when what holds it changes (withParent), when a record a policy read changes, or when the context does, and re-projection is built around exactly those four triggers: "re-check (connection, record)". So the before/after rule is complete.
  • What tracking costs: the index is keyed by the record read. A policy reading the viewer's own account records one dependency per connection; one reading a record per checked record (get(team, doc.teamId)) records one per record it read, and a change to that team re-checks every document of it for every viewer, which is the visibility change itself. The facts policies read are instant kinds (account, team, membership), since get reads nothing else.
  • Instant kinds are held whole in the server's memory, and delivered per viewer: an instant kind whose read is self (an account) sends each client only its own records, so the snapshot budget counts what one viewer receives, while the server holds every user's. That suits small per-user and shared records (accounts, memberships, teams); a large or growing set is a lazy root read through windows, and many users on one server are what partitions are for (scalability).
  • The cost is one check per connection per restricted thing a change touches; connections with the same context share one projection.

G. Prior art ​

Per-table rules as a floor, with server code on top, is the common shape: Postgres row-level security (USING / WITH CHECK are our before/after), Firestore rules, InstantDB permissions (data, newData), Convex's RLS helper. Zero deprecated its rule language for server code with a context, which is why policies here are plain functions, not a language. GraphQL authorizes per node and returns null, as hidden fields do here.

H. What changes in what is built ​

  • Every field gets policies: field(schema).read(…).write(…), required, so every kind in concepts, the README and src/core changes; appendable chains on the same field (field(z.string().default('')).read(…).write(…).appendable()), and serverOnly(schema) stands alone, as both policies at once.
  • memoryOnly goes (its own breaking change): memory is a store like any other, so a kind kept in memory gets a memoryStore() adapter, and a part of a record that must not survive a restart (a reply's text while it streams) is its own kind, keyed by its parent and kept in memory.
  • Kinds gain record policies (read, create, remove, an optional update guard), which kind() today rejects as unknown options.
  • forbidden joins the built-in reasons, so no mutation may declare it.
  • Instant kinds are delivered per viewer: the startup snapshot holds what a viewer may read, so concepts.md's "every record on every device" becomes "every record a device may read", and the snapshot budget counts one viewer's projection.
  • New API: policy, field, everyone, nobody, withParent, fieldState, memoryStore, policies of one argument ({ ctx, record, before, after, get }); on the server connect (given hello and request, returning { ctx, connection? }), refuse(reason), scope, refresh, disconnect, revalidate, tx.ctx, tx.connection, tx.dangerouslySkipPolicies(reason, fn); on the client scope, hello (a function read on every connect, whose payload joins the protocol's hello frame next to the lock revision), settled, close, delete, reconnect, and useSyncStatus()'s refused state (with the app's reasons, and Twinstate's own scopeMismatch and expired).