Invites
Invite functions, the UserInvite table and model, invite extensions, durable invite resolution, and invite availability.
Overview
An invite brings a person into a tenant by email. inviteUserToTenant is the entry point. When the email already belongs to a user, it grants them membership directly. Otherwise it creates an invite row with a token, which the person redeems later. The kind field of the result tells the two outcomes apart.
The functions live in @antelopejs/interface-dms/invites. The UserInvite table and its model live in @antelopejs/interface-dms/db.
Invite a user
import { inviteUserToTenant } from "@antelopejs/interface-dms/invites";
const result = await inviteUserToTenant({
tenantId,
email: "[email protected]",
roleIds: ["role-editor"],
asTenantOwner: false,
sendEmail: true,
});
if (result.kind === "added") {
// an account with that email existed: membership granted, no token
return { userId: result.userId };
}
// no account yet: an invite row was created
return { inviteId: result.inviteId, token: result.token };
InviteUserToTenantOptions
| Option | Type | Description |
|---|---|---|
tenantId | string | Tenant the person is invited into. Required. |
email | string | Email to look up, and to invite when no account has it. Required. |
firstname | string | null | Invitee's first name, stored on the invite row and used to address the email. Defaults to null. |
lastname | string | null | Invitee's last name. Defaults to null. |
language | string | Language stored on the invite row. Defaults to "en". |
roleIds | string[] | Roles granted on join. Defaults to []. |
asTenantOwner | boolean | Grant tenant ownership on join. Defaults to false. |
sendEmail | boolean | Send the invitation email through sendAdminInviteEmail after the row is created. Defaults to false. |
awaitEmailDelivery | boolean | With sendEmail, wait for the email and report its outcome as emailDelivery, instead of sending it in the background. Defaults to false. |
inviterName | string | Name of the sender, shown in the invitation email. |
invitedBy | string | null | Id of the inviting user, stored on the invitation. |
extensions | InviteExtensionPayloads | Payloads keyed by the key of a registered invite extension. |
InviteUserToTenantResult
type InviteEmailDelivery = "sent" | "failed";
type InviteUserToTenantResult =
| { kind: "added"; userId: string }
| InvitedUserResult;
interface InvitedUserResult {
kind: "invited";
inviteId: string;
token?: string; // with sendEmail always; otherwise only for the call that created the invite row
emailDelivery?: InviteEmailDelivery; // only with sendEmail + awaitEmailDelivery
}
The whole call goes through changeTenantMembers, so it respects tenant lifecycle admission.
The "added" branch writes the membership the way applyTenantOwnership does, with roleIds and asTenantOwner (Tenancy). The member hooks fire and no token is generated. The branch then delivers the extensions payloads to their extensions at once, because no invitation exists to wait on. A delivery failure at that point is logged and not raised, since the user is already a member.
The "invited" branch creates the invite row the way createUserInviteToken does, then sends the email when sendEmail is set. By default the email goes out in the background. The call does not wait for delivery and does not fail when delivery fails.
Pass awaitEmailDelivery: true when someone waits for the answer and must learn that the email did not leave. The call then waits for the email and sets emailDelivery to "sent" or "failed". It still does not throw. The invitation is kept either way, so the caller can offer to resend it. The details of the failure, such as the provider's error, go to the server log only, so show the user a generic message. The DMS members Invite form and the Resend action on pending invitations both work this way.
const result = await inviteUserToTenant({
tenantId,
email: "[email protected]",
sendEmail: true,
awaitEmailDelivery: true,
});
if (result.kind === "invited" && result.emailDelivery === "failed") {
// the invite exists, but its email did not leave: say so, offer a resend
}
inviteUserToTenant does not throw on duplicates and runs no checks specific to a context. Decide in the caller what to answer when the person is already a member.
Create an invite token directly
createUserInviteToken is the lower-level function. It creates a row, and it never touches memberships or email.
import { createUserInviteToken } from "@antelopejs/interface-dms/invites";
const { inviteId, token } = await createUserInviteToken({
tenantId,
email: "[email protected]",
language: "en",
roleIds: [],
asTenantOwner: false,
});
CreateUserInviteTokenOptions has these fields:
| Option | Type | Description |
|---|---|---|
tenantId | string | Required. |
email | string | Required. Stored trimmed and lowercased. |
language | string | Required. |
roleIds | string[] | Required. |
asTenantOwner | boolean | Required. |
firstname, lastname | string | null | Optional. Default to null. |
invitedBy | string | null | Optional. Records the sender. null when nobody signed in sent it. |
extensions | InviteExtensionPayloads | Optional. |
replacementReason | "replaced" | "resent" | How to report the retirement of an invitation this one displaces. Defaults to "replaced". A resend passes "resent", which reissues the same invitation, so contributors do not undo what it carries. |
replacesInvite | UserInvite | The exact incarnation to replace, including a retained snapshot during a retry. |
CreateUserInviteTokenResult is { inviteId: string; token?: string }. The row stores only the SHA-256 digest of the token, so the token cannot be read back: only the call that created the row receives it. Keep it to build the link. To get a new link later, call reissueUserInvite(tenantId, invite, invitedBy?): it reissues the invitation under a fresh token, which retires its earlier link, and returns { inviteId, token }. A call that loses to a concurrent reissue reissues the winner in turn, so it always returns a token that works, and fails with HTTP 409 when the invitation was retired meanwhile.
An existing invite for the same email in the same tenant is retired through a durable decision. Completion invokes Hook.INVITE_DELETED for the old invitation, creates the replacement through Hook.INVITE_BEING_CREATED and Hook.INVITE_CREATED, and removes the old row. A failed completion can replay hooks with the same delivery identity. See Durable invite resolution and Hooks.
When concurrent calls for one email all find no invite, the tenant keeps one. A unique index on email and creationResolutionId refuses the second row. The call that loses returns the kept invite's inviteId, without a token, when it asked for the same content, and fails with HTTP 409 when it did not. With sendEmail, inviteUserToTenant reissues that invite under a new token before it emails it, since the call that created the row may have failed before sending.
inviteeDisplayName(firstname?, lastname?) joins the two names into the name the invite email uses, and returns undefined when the invite carries neither. inviteUserToTenant calls it for you. Call it yourself when you render your own invite screen from a stored row, so a nameless invite falls back the same way the email does.
Token constants
| Constant | Value | Meaning |
|---|---|---|
INVITE_TOKEN_LENGTH | 64 | Length of the generated token. |
INVITE_EXPIRY_DAYS | 7 | Days from creation to expiresAt. |
import {
INVITE_EXPIRY_DAYS,
INVITE_TOKEN_LENGTH,
} from "@antelopejs/interface-dms/invites";
The UserInvite table
Table user_invites in the dms-tenant schema, so invites are per tenant, like memberships. The table-name constant USER_INVITES_TABLE_NAME is exported next to it.
| Field | Type | Notes |
|---|---|---|
_id | string | Invite id. The create functions return it as inviteId. |
createdAt | Date | Creation time. Indexed across tenant instances. |
email | string | Stored trimmed and lowercased. Indexed across tenant instances. |
firstname | string | null | Invitee's first name, when the invite carried one. |
lastname | string | null | Invitee's last name, when the invite carried one. |
roles_ids | string[] | Related to Role, many. Roles to grant on redemption. |
language | string | Language the invite was issued in. |
token | string | SHA-256 hex digest of the secret handed to the invitee, never the secret itself. Indexed across tenant instances. |
asTenantOwner | boolean | Grant tenant ownership on redemption. |
expiresAt | Date | INVITE_EXPIRY_DAYS after creation. Indexed across tenant instances. |
creationResolutionId | string, optional | Set on a replacement. The replacement is actionable only after the resolution that created it completes. |
invitedBy | string | null, optional | Id of the user who sent the invitation or last resent it. null for an invitation created outside a signed-in request, such as an import or a module. |
extensions | InviteExtensionPayloads | null | Payloads attached through RegisterInviteExtension, keyed by extension key. Delivered when the invitee joins, and deleted with the row when they do not. |
The field is roles_ids, not roleIds. The membership field roleIds lives on TenantMember (Tenancy).
UserInviteModel
UserInviteModel extends BasicDataModel(UserInvite, USER_INVITES_TABLE_NAME):
| Method | Returns |
|---|---|
getByEmail(email) | Promise<UserInvite | undefined> |
getByToken(token) | Promise<UserInvite | undefined>. Takes the token a link carries and looks up its digest. |
getByTokenWithTenant(token) | Promise<{ invite: UserInvite; tenantId: string } | undefined> |
deleteByToken(token) | Deletes every row that carries the token's digest. |
getByEmail trims and lowercases its argument the same way the stored email is, so the casing a caller passes does not matter.
import { GetModel } from "@antelopejs/interface-database-decorators";
import { UserInviteModel } from "@antelopejs/interface-dms/db";
export async function hasExpiredInvite(tenantId: string, email: string): Promise<boolean> {
const invite = await GetModel(UserInviteModel, tenantId).getByEmail(email);
return invite !== undefined && invite.expiresAt.getTime() < Date.now();
}
getByTokenWithTenant reports the tenant the row came from. A redemption flow needs it, because the person who follows an invite link is not authenticated yet, so no tenant claim exists to bind the handle to.
Raw deletion, deleteByToken included, does not coordinate durable decisions or extension cleanup. For terminal actions, use the invite resolution contract below instead of direct model writes.
RegisterInviteExtension
RegisterInviteExtension<T>(options: InviteExtensionOptions<T>): () => void, from @antelopejs/interface-dms/invite-extensions, adds fields to the members invite form. The registration belongs to the module and is removed when the module stops. The returned function removes it earlier.
| Option | Type | Contract |
|---|---|---|
key | string | Required, non-empty namespace. It must not contain __, the separator between the key and a field id. Registration throws otherwise. |
component | FormBuilder | Required. The form whose fields join the invite modal. |
schema | ZodType<T, unknown> | Required. Validates the payload at submission and again at delivery. Its keys are the field ids of component, without the prefix. Callbacks receive the parsed output T. |
onAccept | InviteAcceptHandler<T> | Required. Called after the membership exists. |
onCleanup | InviteCleanupHandler<T> | Optional. Called on cancellation, replacement, expiry, or member removal, and never on acceptance. |
editable | boolean | Defaults to true. false shows the fields read-only on the edit form of a pending invitation. |
onUpdate | InviteUpdateHandler<T> | Called after a changed payload on a pending invitation is stored. A failure is logged and not raised to the caller. |
label | string | Heading of the contributed block. Defaults to the title of the form. |
description | string | Description of the contribution. |
placement | InviteExtensionPlacement | Optional side ("before", "after", "end"), anchorField, and numeric order. Defaults to the end, order 0. |
anchorField names a top-level field or field group of the invite form. Without an anchor, before places the contribution first, and after and end append it. Lower orders come first, and extension keys break ties. The key namespaces the form field ids. The stored InviteExtensionPayloads type is Record<string, InviteExtensionJson>, keyed by extension, where InviteExtensionJson is a JSON value that may be read-only.
Callback contracts
| Callback | Arguments | Return |
|---|---|---|
InviteAcceptHandler<T> | (payload: T, member: TenantMember, context: InviteExtensionContext) | MaybePromise<void> |
InviteUpdateHandler<T> | (payload: T, previous: T | undefined, context: InviteExtensionContext) | MaybePromise<void> |
InviteCleanupHandler<T> | (payload: T | undefined, context: InviteCleanupContext) | MaybePromise<void> |
InviteExtensionContext has tenantId, email, and optional deliveryId and inviteId. When an existing account is added directly, onAccept runs without an inviteId. previous is undefined when no old payload exists or the old payload no longer validates.
InviteCleanupContext has tenantId, reason: "invite-deleted" | "member-removed", and optional deliveryId, inviteId, email and userId. Invite cleanup sets inviteId. Member cleanup sets userId. Durable delivery may replay concurrently with the same deliveryId, so deduplicate external effects and scope the cleanup of invite resources to inviteId. The durable delivery guidance lists the operational obligations.
Durable invite resolution
The functions in @antelopejs/interface-dms/invite-resolution coordinate competing terminal actions. They do not authorize the caller. Prefer the higher-level invitation entry points, unless you implement a terminal action yourself.
| Function | Signature | Result |
|---|---|---|
loadInviteForAction | (tenantId: string, inviteId: string) => Promise<UserInvite | undefined> | Loads the exact invitation, or its durable snapshot after the live row is gone. |
assertInviteReady | (tenantId: string, invite: UserInvite) => Promise<void> | Rejects with HTTP 409 ($dms.refusals.invite.creation_pending) while the creation of a replacement is incomplete. |
decideInvite | (input: ResolveInviteInput) => Promise<InviteResolution> | Records one permanent terminal outcome before any effect. A conflicting reason or user rejects with HTTP 409, and so does conflicting replacement content. A new acceptance of an expired invitation also rejects with 409. |
completeInviteResolution | (resolution: InviteResolution) => Promise<void> | Enters tenant lifecycle admission through changeTenantMembers and replays the effects. A callback failure retains the snapshot for a retry. |
ResolveInviteInput contains tenantId, invite: UserInvite, reason: InviteResolutionReason, and optional userId and replacement: UserInvite. InviteResolutionReason is "accepted" | "cancelled" | "replaced" | "resent" | "expired". The API captures the extension keys itself, so callers do not supply them.
InviteResolution, from @antelopejs/interface-dms/db, is the stored decision and retry snapshot. Its fields are _id, tenantId, reason, nullable userId, invite, optional inviteToken, nullable replacement, extensionKeys, revision, membershipPhase, replacementPhase, completed and decidedAt. Both phase fields use InviteMembershipPhase ("pending" | "applying" | "applied"). Treat a resolution as a read-only result and pass it back to completion. Do not change the model to advance phases.
Custom producers of memberships or invitations must follow tenant lifecycle admission. Every competing terminal path must decide before it produces effects. A durable decision does not make external effects exactly-once, so callback implementations still own their idempotency.
Mark the invite action unavailable
RegisterInviteAvailability, from @antelopejs/interface-dms/invite-extensions, lets a module disable the Invite button of the members page while one of its conditions holds, such as a plan whose seats are all taken. The resolver is an InviteAvailabilityResolver. It runs once per request while the page layout is built, with a ComponentFilterContext that carries tenantId and user. It returns one of three values:
{ reason }disables the button and shows the reason next to it. A$-prefixed reason resolves as an i18n key.{ hidden: true }hides the button.undefinedleaves the button enabled.
Resolvers run in registration order, and the first one that refuses wins. A resolver that throws is logged and ignored.
import { RegisterInviteAvailability } from "@antelopejs/interface-dms/invite-extensions";
RegisterInviteAvailability(async ({ tenantId }) =>
(await hasFreeSeat(tenantId))
? undefined
: { reason: "$acme.seats.invite_unavailable" },
);
The resolver only shapes the UI. A module that must refuse the invitation itself does so from Hook.INVITE_BEING_CREATED and Hook.MEMBER_BEING_ADDED. The registration is lifted when the registering module stops, and the returned function removes it earlier.
Next steps
Hooks covers the invite and membership events these functions fire, and how to react to them.