Invitations
The invitations plugin, @noctcore/auth/invitations, sends an invitation to an address and lets its owner accept it, either into the account they already have or into a new one. Like the core, it has no HTTP endpoints: its flows live under auth.invitations, and your routes call them. What an accepted invitation means (a seat, a role, a team) is yours to decide in onAccept; the plugin does not scope data. Why each rule is there: Invitations in Learn. This guide builds on A Node server with Redis and Prisma, and the example wires it to the membership guards.
What it guarantees
Section titled “What it guarantees”- The token is a bearer secret, kept like one. 256 random bits from the CSPRNG, mailed once, stored only as its SHA-256. A leaked table holds no usable link. The hash uses no key, so rotating your
secretleaves pending invitations working. Only invitations created before 0.6 are voided by a rotation: they were stored as an HMAC under a key derived fromsecret, and the plugin finds them through a fallback lookup under that old hash until they expire (30 days after the upgrade at most). After a rotation each of those answersinvalid_token(unknown_tokenin the audit trail); revoke and invite again. - One invitation, one accept. Accepting spends the invitation through the store’s atomic
consume: of many concurrent accepts, from any number of browsers, exactly one runsonAccept. The conformance suite checks it for every store, against Postgres and Redis for the shipped ones. - Only the invited address, verified.
acceptneeds a session whose account’s address is verified and equals the invited one, both normalised. WithacceptWithoutSessionon,session: nullis accepted too, and the account is the one holding the invited address, under the same rule. An unverified account, the kind an attacker registers ahead of the victim, never collects the invitation, and nothing is spent. - No second factor is skipped.
acceptissues no session, with or without one passed in.registercreates only a new account and issues its session through the core’s one seam withvia: 'invitation', so the two-factor plugin refuses it when the app requires a factor. - Creating is never open. The plugin refuses to start without
authorize, andcreate,listandrevokeask it with the acting user read from the user store. Accepting asks it again for the inviter (unless you turnrecheckInviteroff), so an invitation from someone who lost the right, or the account, is withdrawn instead of accepted. - Nobody learns which addresses have accounts from
create. It never reads the invited address from the user store: its answer, its mail and its store calls are the same for every address. Junk, unknown and expired tokens all getinvalid_token. - Invitations cannot flood a mailbox. One live invitation per scope and address: a repeat writes nothing and sends no mail. Creates are also limited per address (across scopes), per inviter and per IP.
What it does not do
Section titled “What it does not do”It does not scope your data and does not define roles: onAccept and authorize are where your rules live. It does not hide everything from the holder of a live token: register answers email_in_use when the address already has an account, so that person can sign in and use accept instead. It gives the same answer, and spends nothing, while the address is held for the owner of an email change away from it that can still be reverted (Email change); otherwise an invitation could give that address a new account and leave the revert nowhere to go back to. The answer is the same but the timing is not: a held address costs three store reads (the account, the hold, then the holder) where a taken one costs one, and only the holder of the invitation token can observe it, a token mailed to the held address. That holder is normally the owner of the mailbox; a forwarded link tells its reader as much. And it sends one mail per invitation: there is no resend, so revoke and create again.
The store
Section titled “The store”The plugin needs an InvitationStore: PrismaInvitationStore from @noctcore/auth-prisma (copy the AuthInvitation model from its prisma/auth.prisma and migrate) or RedisInvitationStore from @noctcore/auth-redis, where every key expires with its invitation. MemoryInvitationStore from @noctcore/auth/testing is for tests. On Postgres, expired rows stay until they are replaced, accepted or revoked; sweep them with a deleteMany on expiresAt if the table grows.
Your own store must pass invitationStoreConformance (see Writing a store adapter): consume removes and returns a row in one step, and create refuses a second live invitation for the same scope and address, also under concurrency.
Wiring the plugin
Section titled “Wiring the plugin”import { createAuth, type Mailer } from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';import { invitations } from '@noctcore/auth/invitations';import { PrismaInvitationStore, prismaStores } from '@noctcore/auth-prisma';import { redisStores } from '@noctcore/auth-redis';import { Redis } from 'ioredis';import { prisma } from '../node-server/db';import { mayManage, members } from '../membership/auth';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
/** The roles an invitation may hand out; `mayManage` decides who may give which. */const ROLES = new Set(['member', 'admin', '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: [ invitations({ store: new PrismaInvitationStore({ client: prisma, invitation: prisma.authInvitation }), // The membership guide's role ceiling, read from the store on every // call: owners and admins may invite, list and revoke, only with a role // the app knows, and only an owner may invite an owner. authorize: async ({ user, scope, payload }) => { const actor = await members.findMember(scope, user.id); const role = payload?.['role'];
if (!actor || (payload !== undefined && !ROLES.has(role ?? ''))) return false;
return mayManage(actor.role, undefined, role); }, // What accepting means here: a seat with the invited role. onAccept: async ({ user, invitation }) => { await members.addMember({ scope: invitation.scope, userId: user.id, role: invitation.payload['role'] ?? 'member', }); }, // The token in the fragment: it never reaches a server log or a Referer header. url: (token) => `https://app.example/invite#${token}`, }), ], });}
export type AppAuth = ReturnType<typeof buildAuth>;authorize reuses mayManage, the role ceiling from the membership guards guide, so an invitation can never hand out a role the inviter could not give by a role change.
| Option | Default | |
|---|---|---|
store |
required | |
authorize |
required | ({ user, scope, action, email?, payload? }) => boolean. action is create, list or revoke; email and payload are set for create and for the inviter check on accept. Only true allows; throwing refuses. |
onAccept |
required | ({ user, invitation, created, meta }) => void. Runs after the invitation is spent. A throw reaches the caller and the invitation stays spent: send a new one. |
url |
required | (token) => string, the link in the mail. Must be absolute and carry the token in the path or the fragment; a token in the query string is refused at startup. Serve the page with Referrer-Policy: no-referrer. |
ttl |
'7d' |
At most 30 days. |
recheckInviter |
true |
Ask authorize again for the inviter on accept. |
acceptWithoutSession |
false |
Let accept take session: null: the link alone then joins the account holding the invited, verified address, and signs nobody in. See Accepting without a session. Anything but true or false is refused at startup. |
perAddress |
3 per day | Invitations one address receives, across scopes, keyed by a keyed hash of the address. |
perInviter |
20 per hour | |
perIp |
10 per minute | Creates, accepts and registrations per client IP, counted together. |
The mail is the invitation event: to, scope, inviterId, url and expiresAt, and no userId, because the address may have no account (see Mail). Write the same mail for every address.
The routes
Section titled “The routes”import { toPublicError, type RequestMeta, type StoredSession } from '@noctcore/auth';import type { AppAuth } from './auth';
type Session = StoredSession<Record<string, never>>;
interface Reply { readonly status: number; readonly body: unknown;}
/** The status each invitation refusal is sent with. */const STATUS: Record<string, number> = { forbidden: 403, invalid_token: 400, email_in_use: 409, rate_limited: 429,};
function refusal(result: Parameters<typeof toPublicError>[0]): Reply { return { status: STATUS[result.code] ?? 400, body: toPublicError(result) };}
/** POST /orgs/:orgId/invitations { email, role } */export async function invite( auth: AppAuth, session: Session, orgId: string, body: { email: string; role: string }, meta: RequestMeta,): Promise<Reply> { const result = await auth.invitations.create({ session, scope: orgId, email: body.email, payload: { role: body.role }, meta, });
if (!result.ok) return refusal(result);
// `invitation` is null when one is already pending for this address: nothing was sent. return { status: 202, body: { invitation: result.value.invitation } };}
/** POST /invitations/accept { token }, from the page at /invite, signed in. */export async function accept( auth: AppAuth, session: Session, token: string, meta: RequestMeta,): Promise<Reply> { const result = await auth.invitations.accept({ session, token, meta });
return result.ok ? { status: 200, body: { scope: result.value.scope } } : refusal(result);}
/** POST /invitations/register { token, password }, from the page at /invite, signed out. */export async function register( auth: AppAuth, token: string, password: string, meta: RequestMeta,): Promise<Reply & { readonly sessionToken?: string }> { const result = await auth.invitations.register({ token, password, meta });
if (!result.ok) return refusal(result);
// Set the session cookie from `sessionToken` the way your login route does. return { status: 201, body: { scope: result.value.invitation.scope }, sessionToken: result.value.session.token, };}| Flow | Answers | Refusals |
|---|---|---|
create({ session, scope, email, payload?, meta }) |
{ invitation }, or { invitation: null } when one is already pending |
invalid_email (or email_not_ascii under the ascii email policy), forbidden, rate_limited |
list({ session, scope, meta }) |
the scope’s live invitations | forbidden |
revoke({ session, scope, id, meta }) |
forbidden (also for an unknown id) |
|
accept({ session, token, meta }) |
the invitation | invalid_token, forbidden, rate_limited. session may be null only with acceptWithoutSession on; otherwise forbidden |
register({ token, password, meta }) |
{ invitation, session } |
invalid_token, email_in_use, the password policy’s codes, rate_limited, and any refusal of the session (for example second_factor_required) |
The page at your url reads the token from the fragment. A signed-in visitor posts it to your accept route; a signed-out one chooses between signing in (then accept) and creating an account (register), or, with acceptWithoutSession on, accepts straight away. register checks the password against the policy before it looks up the address, marks the new address verified (the token proved the mailbox; if your user store refuses the mark, through the Prisma store’s writeWhere say, or throws at it, the account goes on unverified and every hook sees emailVerified: false; a throw is logged as Marking an invited address verified failed), runs your afterRegister hooks, then onAccept, then issues the session. If the session is refused, the account and the membership already exist: the user signs in normally.
Every outcome writes an audit row: invitation.created, invitation.deduplicated, invitation.revoked, invitation.accepted (with created in data, and withoutSession: true for an accept with no session), invitation.refused (the reason names which check failed), and register.created for an account made by register.
Accepting without a session
Section titled “Accepting without a session”By default the page at your url sends a signed-out visitor to sign in before accepting. Turn acceptWithoutSession on and your accept route can pass session: null instead: the token, which only the invited mailbox received, then joins the account that holds the invited address. The rules stay the same: that address must be verified (an unverified account is refused with forbidden and nothing is spent), the inviter is checked again, and no session is issued, so the visitor still signs in normally afterwards and a second factor is never skipped. An address with no account answers forbidden and leaves the invitation for register. A locked-out account is attached too: the accept checks no password and issues no session, so a lockout does not stop it.
The trade-off is that the mailbox alone now decides, without the account’s password: anyone who reads a forwarded or leaked link can attach the account to the inviting organisation. Keep the token in the fragment and accept only on a POST from a click, so a mail scanner that fetches the link accepts nothing. Leave the option off if joining an organisation should need the account holder’s own sign-in.
Moving an account to another organisation
Section titled “Moving an account to another organisation”Nothing in the plugin ties an account to one organisation: accepting into an account that already belongs to another one works like any accept. Whether that adds a second seat or moves the account is your onAccept: an app with one organisation per account removes the old membership there and adds the new one. If your sessions carry the organisation (in a session attribute, say), end them after a move so no session keeps the old one, for example with the membership plugin’s revokeSessionsOnChange or your own call to revoke the user’s sessions. With acceptWithoutSession on, such a move happens on the strength of the mailbox alone; decide whether that is acceptable for your app before turning it on.
When the inviter changes
Section titled “When the inviter changes”Revoking all of a user’s sessions deletes the invitations that user sent, and where it reaches depends on the reason. A role change or removal by the membership plugin (only with revokeSessionsOnChange on) names its organisation, so only the invitations to that organisation go. Sign out everywhere, a password reset or change, and any reason your app adds name none, so the inviter’s invitations to every organisation go. A sign-out, ending one session, “sign out other sessions”, turning on two-factor (which signs out the other devices), an eviction and an email verification keep them all: the user still controls their account, and nothing about their right to invite changed. On accept, the inviter is read from the user store and asked authorize again with the invitation’s scope, address and payload; a deleted inviter or a refusal withdraws the invitation and answers invalid_token.