PackagesauthMenu

@intelligo-dev/auth

Multi-tenant authentication on Better-Auth: sign-up, workspaces, invitations and role-based access control.

Install

Terminal
pnpm add @intelligo-dev/auth better-auth drizzle-orm react zod

better-auth, drizzle-orm, react and zod are peers: the guards read the Better-Auth instance and the database client the application already has, and the verification and reset emails render with React.

What it owns

Sessions and accounts, organizations as workspaces, membership roles (owner / admin / member), invitations, platform-admin impersonation, and the guards every transport starts with: requireAuth, requireWorkspace, requireRole, requirePlatformAdmin.

The team, workspace, profile and onboarding services live here too, behind ports the composition root binds — auth never imports billing.

Use

TypeScript
import { requireWorkspace } from "@intelligo-dev/auth";

const { user, workspace, membership } = await requireWorkspace();

A guard that refuses throws an AuthGuardError; isAuthGuardError(error) narrows it and error.code picks the status: unauthenticated (no session, 401), no_workspace (signed in, member of no workspace) or forbidden (lacking the role, 403).

impersonateUser checks that the caller is a platform admin and that the target is not one before it swaps the session. Products call startImpersonation from @intelligo-dev/admin, which adds the audit event and the mandatory reason.

hasSessionCookie(request) from @intelligo-dev/auth/edge is for an optional optimistic redirect in a consumer’s proxy.ts. It reads cookie presence only and is never authorization; the scaffold does not use it.

The same entry point carries the way back after signing in. The scaffold’s proxy.ts calls recordRequestedPath(request), which writes the path of every request into a header it always overwrites; a server layout reads it with requestedPath(headers, locales) and redirects with withNext("/login", path). The header’s name is REQUESTED_PATH_HEADER, for a proxy of your own that sets it without the helper. safeReturnPath(value) is the check every ?next= passes before it is followed: a path on this site, or null.

Platform admin is a row (users.role), not an environment variable. The allowlist in PLATFORM_ADMIN_EMAILS is promoted into that column on first use, so the plugin and the guard cannot disagree. The allowlist counts a verified address only; on a machine that verifies none, intelligo admin grant <email> writes the column directly, and intelligo admin revoke <email> takes it away.

Workspaces and memberships change through the team and workspace services, which apply the plan’s limits and the deletion hook around Better-Auth’s organization plugin; the plugin’s own mutating endpoints answer 404 over HTTP (SERVICE_ONLY_ORGANIZATION_PATHS). Whatever the plan allows, one person owns at most five workspaces until the composition root calls setWorkspaceCeiling(n); workspaces a person was invited into do not count. getWorkspaceCeiling() reads the ceiling in force, for a page that says how many are left, and DEFAULT_WORKSPACE_CEILING is the five. The workspace made at signup is named “’s Workspace” until the composition root calls setPersonalWorkspaceName((user) => …); it runs outside any request, so it cannot read the user’s locale. A test that composes a fresh root puts both back with clearWorkspaceCeiling() and clearPersonalWorkspaceName(). getUserInvitations() returns each of the caller’s pending invitations with who sent it (inviterName, inviterEmail) and its productFields. An invitation can carry a product’s own fields (inviteMember({ email, role, productFields }), a few short strings — what the member is to the workspace, say); they are copied onto the membership when it is accepted and read back with memberProductFields({ workspaceId, userId }). Behind proxies, AUTH_IP_HEADERS (headers to read the client address from, in order) and AUTH_TRUSTED_PROXIES (CIDRs) let the auth rate limiter tell clients apart.

Deleting an account (createProfileService().deleteAccount) schedules it: it is refused while the user is the only owner of a workspace other people belong to, and the workspaces they own alone are deleted with it. Until the grace period ends — ACCOUNT_DELETION_GRACE_DAYS, 30 by default — signing in leads to a restore screen (getPendingDeletion, restoreAccount); every other guard treats that session as signed out. After it, purgeDeletedAccounts, called from the maintenance route, deletes the account and erases the user from the memory audit.

@intelligo-dev/auth/testing is for an app’s integration tests. createTestWorkspace(prefix) signs two users up through Better-Auth and has the second join the first one’s workspace by invitation; asActor(actor, fn) runs a call as one of them. leaks(outcome, victim, args) lists what of another workspace’s is in an answer, and fingerprintRows(workspace) hashes every row reachable from a workspace, in every table that names one, so a test can assert that nothing moved. dropTestWorkspaces removes them.

TypeScript
import {
  asActor,
  createTestWorkspace,
  leaks,
} from "@intelligo-dev/auth/testing";

const mine = await createTestWorkspace(`mine-${Date.now()}`);
const theirs = await createTestWorkspace(`theirs-${Date.now()}`);
const outcome = await asActor(mine.owner, () => listOrders(theirs.workspaceId));
expect(leaks(outcome, theirs, [theirs.workspaceId])).toEqual([]);

headersOf(actor) gives the request headers of an actor, for a call that takes them. activeWorkspaceOf(actor) answers the workspace a guard resolves for them, and setActiveWorkspace(actor, workspaceId) changes it and checks that it changed. testWorkspaceIds(workspace) lists the ids a test workspace was made with, the ones another tenant must never be answered with. settledFingerprint(workspace) is fingerprintRows read until two readings agree, for a tenant whose creation started work in the background; VOLATILE_COLUMNS and EXCLUDED_TABLES name what a fingerprint leaves out, each with its reason. Every account is signed up with TEST_PASSWORD, and totpCode(secretOrUri) gives the code an authenticator app would show, for a test that signs in through the second step.

Adding to the instance

The Better-Auth instance is the framework’s, built on first use. A product adds to it from its composition root, before anything is served:

TypeScript
import { configureAuth } from "@intelligo-dev/auth";

export const auth = configureAuth({
  session: { expiresIn: 60 * 60 * 24 * 30 },
  passwordRule: (password) =>
    password.length < 14 ? "A password is at least 14 characters." : null,
});

plugins and tables add Better-Auth plugins and the tables behind their models, session is laid over the framework’s lifetime, user.additionalFields adds fields, and hooks.before runs after the framework’s own rules have passed the request. What is returned is the same instance with the plugins in its types. The framework’s plugins, its database hooks and the deletedAt field stay; a plugin that takes one of their ids is refused, and so is a call made after the instance has served a request in production. createIntelligoAuthClient({ plugins }) from @intelligo-dev/auth/client is the client half.

Passwords, sessions and the second step

The instance holds every new password to one rule, on sign-up, reset and change, whichever client sends it: passwordProblem(password) answers why a password is refused, or null. It asks for 8 to 128 characters with an upper-case letter, a lower-case one and a number; passwordRule above replaces it.

createAccountSecurityService() is the account’s own view of where it is signed in. listSessions() returns each session without its token, the caller’s first; revokeSession(id) ends one of the caller’s other sessions, looked up among their own; revokeOtherSessions() ends all but the one it is called from; twoFactorEnabled() says whether sign-in asks for a code.

Two-step sign-in is Better-Auth’s twoFactor plugin, one of the framework’s: a person sets an authenticator app up with their password and a first code, and sign-in then answers twoFactorRedirect until a code or a backup code is verified. authClient.twoFactor carries the calls. With PLATFORM_ADMIN_REQUIRE_2FA=true, requirePlatformAdmin() refuses an admin who has not turned it on.

The code is asked for at a password sign-in. A sign-in through Google, GitHub or a generic OAuth provider is not asked for it: the provider’s own second step is what covers that sign-in. The admin flag checks that the account has two-step sign-in on, not which way the session signed in, so a deployment that requires it of admins either has them use a provider that enforces a second step or offers them password sign-in only.

An admin acting as a user reads and changes nothing of this: the password, the email, the account’s deletion, its sessions and its second step answer 403 to an impersonated session.

A bootstrap that is retried

setWorkspaceCreatedHandler(fn) runs once when a personal workspace is created, in the background; a failure is logged. To have it retried, setWorkspaceCreatedDelivery(deliver) hands the created workspace to a queue of the product’s own, whose worker calls runWorkspaceCreated(payload), which throws when the handler fails so the queue runs it again. The handler must be safe to run twice for one workspace. If the queue cannot take the job, the handler runs once as it would without a delivery.

Entry points

  • @intelligo-dev/auth
  • @intelligo-dev/auth/client
  • @intelligo-dev/auth/edge
  • @intelligo-dev/auth/testing

npm · source