Membership guards
The membership plugin, @noctcore/auth/membership, guards the three admin actions every multi-user app has: adding a member, changing a member’s role, and removing one. Like the core, it has no HTTP endpoints: its flows live under auth.membership, and your routes call them. This guide builds on A Node server with Redis and Prisma.
What it guarantees
Section titled “What it guarantees”- Nobody acts on themselves. Every flow refuses
self_targetwhen the session’s user id is the target’s. Ids are compared, never email addresses. - The actor’s right comes from the store. Every flow first reads the acting session live from the store (a revoked, expired or idle session acts on nothing), then reads the acting user’s membership from the store, never from the session, and
canManagedecides on it. A demoted admin loses the right at once, even with a session that still claims the old role. - The last admin stays. A role change from an admin role to a non-admin one, or the removal of an admin, is refused with
last_adminwhen no other member of the scope holds an admin role. The store checks and writes in one atomic step, so two admins demoting or removing each other at the same moment leave one admin, never none. The conformance suite proves it under concurrency for every store, and the Prisma and Redis stores run it against Postgres and Redis. - Sessions are revoked only when you ask, and only for an attempted change. With
revokeSessionsOnChangeon, a role change to another role, or a removal, revokes every session of the member through the epoch fence, once before the write and once after, so a login racing the change either reads the new role or is refused when it mints its session. The first revocation runs before the store decides, so an attempt that passedcanManagebut that the store then refuses (last_admin, or a target that changed or left meanwhile) has still signed the member out: a failed attempt to remove the sole owner signs that owner out, and two admins demoting each other at once are both signed out. Adding a member and setting the role a member already holds never revoke anything, with or without the option (attack A068). - The guards fail closed. A member lookup that throws, an actor who is not a member of the scope, and a
canManagethat throws all refuse withforbidden. A refusal is a typed failure with a code; its reason is only in the audit row, never an exception carrying membership data.
What it does not do
Section titled “What it does not do”It does not ask the user before add: adding someone by user id is your app’s policy. Letting any user add anyone means any user can put anyone into a scope they own; an invitation the user accepts is the consent path (the invitations plugin, #26).
It does not scope your data. Filtering every query by organisation, and checking on every request that the signed-in user is a member of the organisation the request is about, stays in your app: the plugin only answers who is a member and with which role, and guards the changes. It also does not decide what each role may do in your app; adminRoles only names the roles that keep an organisation manageable.
The store
Section titled “The store”The plugin needs a MembershipStore: PrismaMembershipStore from @noctcore/auth-prisma (copy the AuthMember and AuthMemberScope models from its prisma/auth.prisma and migrate) or RedisMembershipStore from @noctcore/auth-redis. Memberships are account data, so on Redis keep them only with persistence on; Redis keeps them under ms:<scope> with no TTL. MemoryMembershipStore from @noctcore/auth/testing is for tests.
Your own store, on your own member table, must pass membershipStoreConformance (see Writing a store adapter). Its two guarded writes, changeRole and removeMember, must check the member’s current role and the other admins and write in one atomic step: a transaction that locks the scope, a single conditional statement, or a compare-and-set that retries. The Prisma store bumps a version on the scope’s AuthMemberScope row in the same transaction as the member write, so write memberships only through the store, or bump that version yourself.
Wiring the plugin
Section titled “Wiring the plugin”import { createAuth, type Mailer } from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';import { membership } from '@noctcore/auth/membership';import { PrismaMembershipStore, prismaStores } from '@noctcore/auth-prisma';import { redisStores } from '@noctcore/auth-redis';import { Redis } from 'ioredis';import { prisma } from '../node-server/db';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
/** Who belongs to which organisation. Write memberships only through this store. */export const members = new PrismaMembershipStore({ client: prisma, member: prisma.authMember, scope: prisma.authMemberScope,});
/** * The role ceiling, shared by every door that hands out or takes away a role * (membership here, invitations too): owners may do anything, admins manage * everyone but owners and never give the owner role, members manage nobody. */export function mayManage(actorRole: string, from: string | undefined, to: string | undefined) { return actorRole === 'owner' || (actorRole === 'admin' && from !== 'owner' && to !== 'owner');}
export function buildAuth(mailer: Mailer) { return createAuth({ stores: { ...prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken }), ...redisStores(redis, { prefix: 'auth:' }), }, password: { hasher: argon2id() }, secret: process.env.AUTH_SECRET ?? '', urls: { resetPassword: (token) => `https://app.example/reset-password#${token}` }, mailer, plugins: [ membership({ store: members, // The last owner or admin of an organisation can be neither demoted nor removed. adminRoles: ['owner', 'admin'], canManage: ({ actor, from, to }) => mayManage(actor.role, from, to), // Roles are read from the store on every call and not copied into // sessions, so there is nothing to revoke when one changes. Set // `revokeSessionsOnChange: true` if your session attributes carry roles. }), ], });}
export type AppAuth = ReturnType<typeof buildAuth>;| Option | Default | |
|---|---|---|
store |
required | |
adminRoles |
required | At least one role. The last member holding one of them in a scope can be neither demoted to another role nor removed. |
canManage |
the actor holds an admin role | ({ actor, action, userId, from, to }) => boolean. actor is the acting user’s membership, read from the store. from is the target’s role now (undefined when adding), to the role being given (undefined when removing). Throwing refuses. The default lets an admin act on an owner; the snippet above keeps the owner role to owners. |
revokeSessionsOnChange |
false |
Revoke every session of a member on an attempted change to another role, or a removal, including one the store then refuses (last_admin, a stale or missing target). Turn it on only if your app copies roles into session attributes or caches them per session: see Revocation. |
The routes
Section titled “The routes”import { toPublicError, type RequestMeta, type StoredSession } from '@noctcore/auth';import { members, type AppAuth } from './auth';
interface Reply { readonly status: number; readonly body: unknown;}
/** The status each membership refusal is sent with. */const STATUS: Record<string, number> = { self_target: 403, last_admin: 409, session_expired: 401, forbidden: 403,};
/** POST /orgs/:orgId/members/:userId/role { role } */export async function changeRole( auth: AppAuth, session: StoredSession<Record<string, never>>, orgId: string, userId: string, role: string, meta: RequestMeta,): Promise<Reply> { const result = await auth.membership.changeRole({ session, scope: orgId, userId, role, meta });
if (!result.ok) return { status: STATUS[result.code] ?? 400, body: toPublicError(result) };
// The member's next request is judged on the new role: roles are read from the store. return { status: 200, body: { member: result.value } };}
/** DELETE /orgs/:orgId/members/:userId */export async function removeMember( auth: AppAuth, session: StoredSession<Record<string, never>>, orgId: string, userId: string, meta: RequestMeta,): Promise<Reply> { const result = await auth.membership.remove({ session, scope: orgId, userId, meta });
if (!result.ok) return { status: STATUS[result.code] ?? 400, body: toPublicError(result) };
return { status: 204, body: null };}
/** Creating an organisation: its creator becomes the first owner, straight through the store. */export async function createOrganisation(orgId: string, creatorId: string): Promise<void> { await members.addMember({ scope: orgId, userId: creatorId, role: 'owner' });}The flows take the session your app validated, the scope id, the target’s user id and the request meta:
| Flow | Refusals | Revokes the target’s sessions |
|---|---|---|
add({ session, scope, userId, role, meta }) |
self_target, session_expired, forbidden |
never |
changeRole({ session, scope, userId, role, meta }) |
self_target, session_expired, last_admin, forbidden |
with revokeSessionsOnChange, when the role differs, even if the store then refuses the write |
remove({ session, scope, userId, meta }) |
self_target, session_expired, last_admin, forbidden |
with revokeSessionsOnChange, even if the store then refuses the write |
forbidden covers an actor who is not a member or whom canManage refuses, a target who is missing (or, for add, already a member), an empty role, a role that changed between the check and the write, and a lookup that failed; the audit row names which. Every change and every refusal writes an audit row (membership.added, membership.role_changed, membership.removed, membership.refused) with the actor as userId and the scope, target and roles in data.
The first member of a scope has nobody to add them: create the first owner straight through the store, as createOrganisation does above.
Revocation
Section titled “Revocation”The guards never need revocation: every call reads the acting user’s role from the store, so a demoted admin’s next action is judged on the new role while their session stays signed in. Turn on revokeSessionsOnChange when your app copies roles into session attributes, or caches them per session, and must not keep serving the old role.
It has a cost. The epoch fence is per user, so a revocation signs the member out on every device and in every organisation, and with the two-factor plugin on it also voids their trusted devices, so their next sign-in asks for a code. An admin of any organisation a user belongs to can therefore sign that user out everywhere, by a role change or a removal, and even by one the store refuses. The revocation reason your onSessionsRevoked hook sees is membership-changed, twice per change (before and after the write).
If the session store fails before the write, the call throws and nothing changed. If it fails after the write, the call throws and the change stands: every session the member held before the change was already revoked by the first bump, and only a login that ran between the two bumps can still be live. Finish with auth.context.revokeAllSessions(userId, 'membership-changed'); retrying the same changeRole does nothing, because the member already holds the role.