Authentication — sessions, tokens, SSO
Complete guide to implementing authentication in ObjectStack using plugin-auth with Better-Auth
Authentication Guide
Complete guide to implementing authentication in ObjectStack applications using the @objectstack/plugin-auth package powered by Better-Auth.
Table of Contents
- Overview
- Installation
- Basic Setup
- Authentication Methods
- OAuth Providers
- Advanced Features
- Client Integration
- API Reference
- Best Practices
- MSW/Mock Mode
Overview
The @objectstack/plugin-auth package provides enterprise-grade authentication and identity management for ObjectStack applications. It's built on top of Better-Auth, a modern authentication library, and seamlessly integrates with ObjectStack's kernel architecture.
Key Features
- ✅ Email/Password Authentication - Traditional username/password login
- ✅ OAuth Providers - Google, GitHub, and more
- ✅ Session Management - Automatic session handling with configurable expiry
- ✅ Password Reset - Email-based password reset flow
- ✅ Email Verification - Email verification workflow
- ✅ Multi-Factor Authentication - TOTP two-factor, plus org-wide enforced MFA with a grace period and a Console enrollment/remediation flow (ADR-0069)
- ✅ Magic Links - Passwordless authentication
- ✅ Organizations - Multi-tenant support
- ✅ ObjectQL Integration - Native ObjectStack data persistence (no ORM required)
Enterprise hardening (ADR-0069) — configured from Setup → Authentication, each setting backed by real runtime enforcement:
- ✅ Password policy - Complexity (min character classes), history (no-reuse), expiry, and breached-password rejection via Have I Been Pwned (k-anonymity)
- ✅ Account lockout & rate-limiting - Per-account lockout after N failed sign-ins (admin Unlock action) and per-IP throttling
- ✅ Enforced MFA - Org-wide
require_mfawith a configurable grace period; the session is gated from data access until the user enrolls - ✅ Session controls - Idle timeout, absolute lifetime cap, and concurrent-session limit per user
- ✅ IP allowlist - Restrict authenticated access to CIDR ranges
- ✅ Enterprise SSO - Admin-managed OIDC and SAML 2.0 trust list (see Social & Enterprise SSO)
See Enterprise Authentication Hardening for the full settings reference.
Architecture
The plugin uses a direct forwarding architecture where all authentication requests are forwarded to Better-Auth's universal handler. This ensures:
- Full compatibility with all Better-Auth features
- Minimal custom code to maintain
- Easy updates when Better-Auth releases new features
- Type-safe API access via
await authManager.getApi()
CLI device flow
os login uses a browser-based device flow in interactive terminals. The
CLI requests a one-time code from POST /api/v1/auth/device/code, opens the
Console approval page at /_console/auth/device?user_code=..., and polls
POST /api/v1/auth/device/token until the user approves access. Device codes
expire after the server-configured TTL (the CLI assumes a 10-minute / 600s
default). The device flow requires plugins: { deviceAuthorization: true } in
your AuthPlugin configuration.
Under --json this command is the CLI's one declared NDJSON exception: it
emits the verification-URL record before you authorize and the result record
afterwards, one compact JSON document per line, so stdout must be parsed line by
line rather than with a single JSON.parse. See
the CLI reference.
The email/password path is still supported for CI and non-interactive shells:
os login --email user@example.com --password secretNew accounts can be created with:
os register
os register --email user@example.com --name "Jane Doe" --password secretInstallation
Install the plugin in your ObjectStack project:
pnpm add @objectstack/plugin-authBetter-Auth is a direct runtime dependency of the plugin, not a peer dependency,
so the command above installs it for you — you never add better-auth yourself.
Basic Setup
1. Environment Variables
Set up your authentication secret in .env:
# Required: Secret for session token encryption
OS_AUTH_SECRET=your-super-secret-key-min-32-chars
# Optional: open-source Google login
# You can also configure these in Setup → Authentication.
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# Optional: lock auth settings from env. Env wins over Setup UI values.
OS_AUTH_SIGNUP_ENABLED=false
OS_AUTH_GOOGLE_ENABLED=true
# Optional: what a new user joins (ADR-0093 D1). `auto` (default) binds every
# new user to the default organization (except a sign-up admitted by its
# invitation alone whose address is unverified: under the `invite_only`
# audience posture, one admitted by the invitation it presents; under
# `email_domain`, one off the allowlist that an invitation addressed to it
# admitted. It joins by accepting); `invite-only` grants membership only
# through an explicit act — creating a workspace, accepting an invitation, an
# admin adding them, or SSO just-in-time provisioning.
# Also configurable in Setup → Authentication → Membership.
OS_AUTH_MEMBERSHIP_POLICY=invite-onlyImportant: Never commit
OS_AUTH_SECRETto version control. Use a strong random string (minimum 32 characters).
2. Plugin Configuration
Add the plugin to your kernel configuration:
import { ObjectKernel } from '@objectstack/core';
import { ObjectQLPlugin } from '@objectstack/objectql';
import { DriverPlugin } from '@objectstack/runtime';
import { InMemoryDriver } from '@objectstack/driver-memory';
import { AuthPlugin } from '@objectstack/plugin-auth';
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
import { createRestApiPlugin } from '@objectstack/rest';
const kernel = new ObjectKernel();
// AuthPlugin depends on the ObjectQL engine for data persistence,
// so register ObjectQLPlugin and a driver first.
await kernel.use(new ObjectQLPlugin());
await kernel.use(new DriverPlugin(new InMemoryDriver(), 'memory'));
// HTTP server (optional — auth works without it in MSW/mock mode)
await kernel.use(new HonoServerPlugin({
port: 3000,
}));
// Data API — serves /api/v1/data/:object with full CRUD behind the gate
// stack. Without it this minimal stack has no data routes: the HTTP server
// plugin is a transport adapter and its legacy built-in data surface is
// deprecated and off by default (#4073). The authenticated fetch further
// down this page reads /api/v1/data/task through this plugin.
await kernel.use(createRestApiPlugin());
// Authentication plugin
await kernel.use(new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
}));
await kernel.bootstrap();That's it! Your authentication endpoints are now available at /api/v1/auth/*.
MSW/Mock Mode: AuthPlugin does not require an HTTP server. When HonoServerPlugin is absent, the plugin gracefully skips route registration and still registers the
authservice. See MSW/Mock Mode below for details.
3. ObjectQL Data Persistence
The plugin automatically uses ObjectQL for data persistence. No additional database configuration is required - it works with your existing ObjectQL setup.
The plugin creates the following auth objects (using ObjectStack sys_ protocol names):
sys_user- User accounts (mapped from better-auth'susermodel)sys_session- Active sessions (mapped from better-auth'ssessionmodel)sys_account- OAuth provider accounts (mapped from better-auth'saccountmodel)sys_verification- Email/phone verification tokens (mapped from better-auth'sverificationmodel)
Note: better-auth uses hardcoded model names (
user,session, etc.). The ObjectQL adapter automatically maps these tosys_-prefixed protocol names viaAUTH_MODEL_TO_PROTOCOL. Client-side API routes (/api/v1/auth/*) are not affected — they do not expose object names.
These objects are managedBy: 'better-auth' (an identity-owned lifecycle bucket): generic user-context CRUD through the /data API is suppressed — a fail-closed identity write guard (ADR-0092/0103) rejects direct writes so password hashing, session validation, and verification flows can't be bypassed. better-auth's own writes run under a system context and pass through. Mutate these records through the sign-in, invitation, and security flows above, never by writing the objects directly.
Authentication Methods
Email/Password Authentication
Sign Up
// Client-side (using @objectstack/client)
import { ObjectStackClient } from '@objectstack/client';
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000'
});
const result = await client.auth.register({
email: 'user@example.com',
password: 'securePassword123',
name: 'John Doe'
});
console.log('User created:', result.data.user);
console.log('Access token:', result.data.token);Sign In
const session = await client.auth.login({
type: 'email',
email: 'user@example.com',
password: 'securePassword123'
});
console.log('Logged in:', session.data.user);Sign Out
await client.auth.logout();Get Current Session
const session = await client.auth.me();
console.log('Current user:', session.data.user);First-run bootstrap status
GET /api/v1/auth/bootstrap-status answers one question — is the admission gate's
bootstrap window open, i.e. does this system have no human user yet? Service
rows (such as the legacy usr_system row) do not count.
const res = await fetch('http://localhost:3000/api/v1/auth/bootstrap-status');
const { hasOwner } = await res.json(); // → { "hasOwner": true }It is public and unauthenticated by design: a client has to be able to ask it
before anyone has credentials. That is also why it returns nothing but the
boolean — it is a routing signal, not an information endpoint. The Console's root
route uses it to choose between /login (normal) and /setup (first-run owner
creation); client.auth.bootstrapStatus() is the SDK method that builds it.
It fails open: if no data engine is wired, or the count query throws, it
answers { "hasOwner": true } so a client falls through to the ordinary login
flow rather than offering to create an owner when one may already exist.
This route is unauthenticated, so treat hasOwner: false as a hint to render a
setup screen — never as authorization. First-run owner creation is enforced
server-side by the sign-up path, not by this probe.
Password Management
Request Password Reset
// Direct API call
const response = await fetch('http://localhost:3000/api/v1/auth/request-password-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com'
})
});The request answers { status: true } the same way for any address. The reset
mail is sent after the response; a send that fails is logged on the server and
never changes the answer.
Reset Password with Token
const response = await fetch('http://localhost:3000/api/v1/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: 'reset-token-from-email',
newPassword: 'newSecurePassword456'
})
});A completed reset ends every existing session of the account — the emailed link
and the phone OTP reset alike, the same as an administrator's forced reset — so
the user signs in again with the new password. It is not a setting: the former
emailAndPassword.revokeSessionsOnPasswordReset key is retired, and a
configuration that still carries it, at any value, is refused at boot — delete
the key.
Any change to a user's password ends every other reset link and texted reset
code still outstanding for that user: a completed reset, the user's own
POST /api/v1/auth/change-password, an administrator's
POST /api/v1/auth/admin/set-user-password and a first password set through
POST /api/v1/auth/set-initial-password. An ended link or code answers exactly
what one that was never issued answers (400 INVALID_TOKEN at
reset-password); a link or code requested after the change works as usual.
A change to a user's password also ends the following, issued before it:
- an email-change link, and a verification link on a deployment that signs
its holder in when it verifies
(
emailVerification.autoSignInAfterVerification: true), answer what a link that was never issued answers atGET /api/v1/auth/verify-email(401 INVALID_TOKEN, or theerror=INVALID_TOKENredirect to its callback). With auto sign-in off, a verification link signs nobody in, and it still verifies the address; - a magic link answers what a link that was never issued answers at
GET /api/v1/auth/magic-link/verify(theerror=INVALID_TOKENredirect) and opens no session; - a sign-in code texted by
POST /api/v1/auth/phone-number/send-otpanswers what a code that was never sent answers atPOST /api/v1/auth/phone-number/verify(400 OTP_NOT_FOUND) and opens no session; - a second-factor challenge opened by a password sign-in answers what a challenge that was never opened answers;
- an MCP access token is refused at the MCP endpoint. Where the app's
authorization still stands — a password change, or an administrator's
set-user-passwordwithrevokeSessionsAndKeys: false— the app gets a new token with its refresh token, as it does when a token expires; a reset ends the authorization itself (below).
The person asks for a new link, code or challenge, which works as usual. A
door that ends the account's sessions — a completed reset, change-password
with revokeOtherSessions: true (the session it installs is kept) and the
one-step invitation acceptance — ends every session opened before its
password write, and a password sign-in during which the password changes is
refused with what a wrong password answers.
The change's moment is the last time the account's local password was
written, so an administrator's set-user-password counts too. An account's
first password counts when it is set onto an account that was already there:
through either reset door, an administrator's set-user-password, the one-step
invitation acceptance of an existing account, or set-initial-password. It
does not count when the password is created in the same request as its
account, as at a sign-up with a password, an administrator's create-user or a
one-step invitation acceptance that creates the account, however long the
steps between the two take. A password created outside such a request (written
straight to the store), or before this release, counts as a change at its
creation. An email-change or verification link carries its issue time in whole
seconds, so one minted in the same second as the change is refused as well.
An MCP access token carries its issue time in milliseconds, signed into it by
the server, so for an app the user granted access to through the consent step,
one minted after the change in the same second is admitted; a token without
that value (minted before this release), or one whose value cannot be placed,
keeps the whole-second refusal. An app admitted without a consent step keeps
the whole-second refusal for every token.
What a password reset ends, and what a change keeps
A completed password reset — the emailed link (POST /api/v1/auth/reset-password)
or the texted code (POST /api/v1/auth/phone-number/reset-password) — ends,
beside the account's sessions, what the account added before it:
- API keys. Every API key the account owns that is not revoked — its
revokedflag false or unset — is revoked, and the next call with it is refused as revoked (403 API_KEY_REVOKED). It is revoked as one its owner revoked from the API Keys list, so the owner may restore it there. - Linked sign-in accounts. Every sign-in account linked to the account other than its password — a social, OAuth or single sign-on link — is unlinked. The provider may be linked again the way it was linked the first time.
- Authorized apps. Where the OAuth provider is enabled, every app authorized to the account loses its authorization: the account's consents, refresh tokens and stored access tokens are deleted, so the app asks the person to authorize it again. An MCP access token, which is signed rather than stored, is refused on its next request, because the MCP endpoint reads on every request the authorization it was issued under and when the account's password last changed.
- Device sign-ins. Where device authorization is enabled, a device sign-in approved for the account and not yet collected by its device is ended.
- OAuth applications it registered. Every OAuth application the account registered (it is the application's owner) that is not disabled is disabled, as a platform administrator's Disable action disables one: the provider issues it no token, client-credentials tokens included, answers its tokens inactive at introspection, and the MCP endpoint refuses every token it holds, whoever authorized it. A platform administrator can enable it again; its owner cannot. An application another account registered is not touched.
- SCIM credentials it minted. Every SCIM provisioning credential the
account minted that is still active is revoked, as Revoke Credential
revokes one: its bearer is refused from the next SCIM request on. A revoke
is one-way, so provisioning through that connection waits until a platform
administrator mints a new credential. Each revoke writes the
sys_audit_logrow Revoke Credential writes, naming the account as the one who revoked it. A credential another administrator minted, for the same connection or another, is not touched. - Passkeys. This build offers no passkey sign-in, so there are none to end.
A reset keeps the single sign-on providers the account registered and its
two-factor enrolment. Once it has ended the rest, it sends the account's
address auth.password_reset_notice: how many API keys, linked sign-in
accounts and authorized apps it ended, each OAuth application it disabled and
each SCIM credential it revoked by name, and the single sign-on providers and
the second factor it kept, so the owner can check them. The notice is
best-effort: one that cannot be sent never fails the reset. It is a built-in
auth template, overridable like the others.
A reset that does not complete ends nothing; a key minted after the reset works as usual. A completed reset that cannot end one of these — a record that cannot be read or written, a linked account a host hook keeps, an account it cannot name — still ends every other kind: an application that cannot be disabled leaves no API key, linked account or credential in place. Once it has tried them all it answers an error and sends no notice. The new password stands, and its change time and password history are recorded all the same; resetting again ends what remains.
A password change through POST /api/v1/auth/change-password, which proves
the current password, ends none of these: an authorized app keeps its
authorization and gets a new MCP access token with its refresh token, issued
after the change. It disables no application and revokes no SCIM credential.
When the account still holds an API key that is neither revoked nor past its
own expiry, a linked sign-in account, an authorized app, an OAuth application
it registered that is not disabled or a SCIM credential it minted that is
still active and not past its own expiry after the change, the account's
address is sent
auth.password_changed_notice, naming each one, through the email service
every auth mail goes through. The notice is best-effort: one that cannot be
sent never fails the change. It is a built-in auth template, overridable like
the others.
An administrator's forced reset with revokeSessionsAndKeys on and the
operator's os user set-password end the API keys, the linked sign-in
accounts, the authorized apps and the device sign-ins, disable the OAuth
applications the account registered and revoke the SCIM credentials it
minted, as Set / Reset a Password describes. The
forced reset records each SCIM credential it revokes in sys_audit_log
against the administrator who ran it; os user set-password, which runs as
no signed-in user, records none. They send no notice: each tells the one who
ran it what it ended.
What a ban, a deactivation or a removal ends
An account that is disabled or removed keeps nothing running in its name. A
platform administrator's ban (POST /api/v1/auth/admin/ban-user), the identity
provider deactivating or deleting the person through SCIM (active: false,
DELETE /Users/{id}), and an administrator's delete
(POST /api/v1/auth/admin/remove-user) each end what a password reset ends of
the account's registrations:
- OAuth applications it registered are disabled, as a reset disables them. A platform administrator can enable one again.
- SCIM credentials it minted are revoked, one-way, as a reset revokes
them. Each revoke writes the
sys_audit_logrow Revoke Credential writes, naming the administrator who banned or removed the account, or, for a deactivation, the directory connection (actorsvc:scim:CONNECTION_ID, nouser_id). - AI service accounts it is accountable for stop: a ban suspends each one
with the reason
Accountable owner banned by an administrator, a deactivation withAccountable owner deactivated by the directory. An administrator's delete of a person who is still accountable for an AI service account is refused (400 VALIDATION_FAILED, the account needs an accountable owner): name a new owner first (set-owner), then delete.
The single sign-on providers the account registered are kept, as a reset keeps them. An unban or a re-activation restores none of it: a platform administrator enables an application again, a new credential is minted for a connection, and an administrator resumes an AI service account once its owner is active again or a new owner is named. A timed ban leaves the AI service accounts suspended after the ban expires.
How each door answers:
- Ban. The response's
data.revokedreports what was ended beside the ban —{ serviceAccounts, ownedApps, scimCredentials, failed, complete }, counts only, as the forced reset reports its own — and the ban'ssys_audit_logrow carries the same counts. The ban has landed by then, so a step that cannot finish does not undo it:completeisfalse, and banning the user again ends what remains. - Delete. The answer is
{ success: true, revoked: { ownedApps, scimCredentials } }. The registrations are ended inside the delete's unit of work, before the user is deleted; when one cannot be ended, the delete is refused with503 SERVICE_UNAVAILABLEand nothing is changed. - Deactivation. It never fails the SCIM request. A credential it revoked is
reported once in the server log at
error, naming the credential and the remedy; one it could not end is reported aterrortoo, and the next SCIM write that leaves the user inactive ends what remains.
Known trade: a SCIM credential belongs to the administrator who minted it. When that administrator is banned, deactivated or removed, the credential is revoked and provisioning through its connection pauses until another administrator mints a new one. Rotate the connection's credential to another administrator first (see SCIM Connection Credentials) to avoid the pause.
Setting a first local password
POST /api/v1/auth/set-initial-password sets an initial local password for a
signed-in user who has no credential account yet — the account was onboarded
through SSO, through the cloud OAuth provider, or imported with
passwordPolicy: 'none'. It gives that user an email/password way in to this
system without the SSO round-trip.
const response = await fetch('http://localhost:3000/api/v1/auth/set-initial-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // a valid session identifies WHO is asking
body: JSON.stringify({ newPassword: 'firstLocalPassword123' })
});Two refusals are deliberate and are what separate this from a password reset:
- No session → refused. The route never takes a user id from the body; the session is the only thing that says whose password is being set.
- A credential already exists → refused. Use
POST /api/v1/auth/change-passwordin that case, so the current password is verified first. This endpoint is only for the no-password-yet state, which is why it can accept a new password without one.
The Console reaches it from Profile → Password when hasLocalPassword()
reports no credential.
SSO-only mode: IdP-provisioned users get no local password
With SSO-only mode on (ssoOnlyMode, or OS_AUTH_SSO_ONLY=true), the server
gives a user whose sys_user.source is idp_provisioned no local password, at
every door that sets one: POST /api/v1/auth/set-initial-password, an
administrator's POST /api/v1/auth/admin/set-user-password (the Set
Password action), and the two resets, POST /api/v1/auth/reset-password and
POST /api/v1/auth/phone-number/reset-password. Each answers
409 RESOURCE_CONFLICT with a message that names SSO-only mode, and writes
nothing; the user signs in through the identity provider.
- Break-glass stays reachable. A platform administrator may set their own local password at any of these doors. An administrator setting one for another IdP-provisioned user, another administrator included, is refused.
- The resets judge only a credential they would accept. A reset token or a
texted code that does not match answers exactly as it does with SSO-only mode
off. If the reset record or the user's identity source cannot be read, the
reset answers
503 SERVICE_UNAVAILABLEand sets nothing. - The two resets answer in the auth library's flat body,
{ "code": "RESOURCE_CONFLICT", "message": "…" }, the shape their other refusals (an invalid token, an invalid code) take. The two set doors answer the platform's{ "success": false, "error": { "code", "message" } }envelope. - Unchanged: environment-native users at every door, SSO-only mode off, and
a local password a user already holds — it still signs in, and
POST /api/v1/auth/change-passwordstill changes it. On a cloud-managed environment the cloud-managed rules answer first. - A cloud-managed environment sets no local password for anyone. There
(
OS_CLOUD_MANAGED=1),POST /api/v1/auth/set-initial-passwordrefuses every signed-in caller,POST /api/v1/auth/admin/set-user-passwordrefuses every target, and the self-service reset doors (POST /api/v1/auth/reset-password,POST /api/v1/auth/phone-number/reset-password, and therequest-password-resetdoors that send their link or code) refuse every request, with409 RESOURCE_CONFLICT, whatever the user's identity source and a platform administrator included. Everyone signs in through the hosting organisation's identity provider, so a hosted environment has no local break-glass administrator. A password set before is not removed here. Self-hosted deployments keep the rules above.
Email Verification
Send Verification Email
const response = await fetch('http://localhost:3000/api/v1/auth/send-verification-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
});Verify Email
// User clicks link in email with token
const response = await fetch(`http://localhost:3000/api/v1/auth/verify-email?token=${token}`);Phone-Number Authentication (SMS OTP)
Phone numbers are a first-class sign-in identifier (better-auth phoneNumber
plugin). Opt in per deployment:
OS_AUTH_PHONE_NUMBER_ENABLED=true # or auth.plugins.phoneNumber in configThe plugin adds sys_user.phone_number (unique) and phone_number_verified.
Phone-only employees are created by the admin create-user / import routes with
an undeliverable placeholder email (u-<random>@placeholder.invalid) — never
by OTP self-signup.
Phone + password sign-in
Always available once the plugin is on:
const response = await fetch('http://localhost:3000/api/v1/auth/sign-in/phone-number', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phoneNumber: '+8613800000000', password: 'password123' })
});OTP sign-in and self-service reset (requires SMS delivery)
The OTP surface opens only when a deliverable SMS service is configured
(services.sms, Setup → Settings → SMS Delivery). Without one — no SMS
service wired, or only the log transport in production — send-otp answers
400 with code: "SMS_SERVICE_REQUIRED" and a message naming the fix, while
request-password-reset keeps answering {status:true} (it never reveals
whether a number is registered) and sends nothing. The public config advertises real
availability as features.phoneNumberOtp, which is what the Console login UI
gates its "Sign in with verification code" mode and the SMS reset branch on.
// Sign-in / verification: request a code, then verify (creates a session —
// for an account with an enrolled second factor, the two-factor challenge
// instead, exactly as password sign-in answers)
await fetch('/api/v1/auth/phone-number/send-otp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phoneNumber: '+8613800000000' })
});
await fetch('/api/v1/auth/phone-number/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phoneNumber: '+8613800000000', code: '123456' })
});
// Self-service password reset over SMS
await fetch('/api/v1/auth/phone-number/request-password-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phoneNumber: '+8613800000000' })
});
await fetch('/api/v1/auth/phone-number/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phoneNumber: '+8613800000000', otp: '123456', newPassword: 'NewPass123!' })
});Abuse hardening ships with the feature (SMS is a paid channel):
- Per-number admission guard (always on): 60s cooldown + 5 sends per
rolling hour per number, shared across the sign-in and reset flows and —
in a cluster — across nodes via the shared KV. Rejected requests get an
honest
429with the retry window and never invalidate an already delivered code. Tune viaAuthManagerphoneOtp(cooldownSeconds/maxPerHour/allowedAttempts/expiresIn/otpLength). - Wrong-code attempts are capped at 3 (
allowedAttempts), then the code is invalidated. - Per-IP rate limiting: the plugin ships a
/phone-number/*default (10/min), and theauthsettingsrate_limit_max/rate_limit_window_secondstighten all four OTP endpoints. - OTP codes never reach logs — the SMS service logs masked numbers and
statuses only;
request-password-resetalways answers{status:true}so it cannot be used as an account-existence oracle.
The identity import endpoint's invite policy also supports phone-only rows
when SMS is deliverable: the created account receives a credential-free
invitation SMS and the employee completes first sign-in via phone OTP, then
sets their own password.
SMS text customisation & localisation
The OTP and invitation bodies are localised, and built-in English and Chinese
texts are always available. A sys_notification_template row for
(auth.phone_otp | auth.phone_invite, channel 'sms', locale), authored under
Setup → Notification Templates, replaces the built-in text. No such row ships
with the platform: one exists only once someone authors it.
An auth SMS belongs to no organization of its own, so the row is read in the
organization the send resolves to, tenancy.defaultOrgId():
- Under the
singleposture that is the Default Organization, so the Default Organization's row is used. - Under
isolatedandgroupit resolves to no organization: no row is read and the built-in text is sent, so one organization's row never decides the text another organization's user receives.
Both bodies pick their language the same way: the recipient's own
sys_user.locale when their account has one, and the deployment default
(localization.locale setting) otherwise — the account is matched on its
phone_number, so a number no account carries takes the deployment default
too. For the invitation SMS the account normally does exist, because the
identity import endpoint creates it and only then sends the message. Whichever
locale that names is then resolved with a zh-CN → zh → en fallback chain;
holes are {{code}}, {{appName}}, {{minutes}} (OTP) and {{appName}},
{{loginUrl}} (invitation — {{baseUrl}}, the bare origin, is still
interpolated for tenant templates written against the older text). Template
lookups are best-effort — an outage falls back to the built-in text and never
blocks an OTP send.
OAuth Providers
Configuration
Enable OAuth providers in your plugin configuration:
new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
// socialProviders is a record keyed by provider id (forwarded to better-auth).
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
},
})Note: Use the
socialProvidersrecord above. The legacyproviders: [...]array still type-checks but is not wired up at runtime — onlysocialProvidersis forwarded to better-auth, so aprovidersarray produces no working OAuth.
Zero-config Google (env only)
You can enable Google sign-in without any code by setting GOOGLE_CLIENT_ID and
GOOGLE_CLIENT_SECRET (and leaving OS_AUTH_GOOGLE_ENABLED unset or not false).
The plugin auto-registers Google as a social provider from these environment
variables. Use the explicit socialProviders record for other providers or to
override the env-derived configuration.
OAuth Flow
1. Initiate OAuth Login
// Recommended: use the client SDK, which posts to /sign-in/social and redirects.
// `callbackURL` defaults to the current page (window.location.href) — the SDK
// can't know your app's mount path, so it returns you where you started. Pass
// an explicit `callbackURL` to land elsewhere.
await client.auth.signInWithProvider('google');
// Equivalent direct API call: POST /sign-in/social returns a redirect URL.
const response = await fetch('http://localhost:3000/api/v1/auth/sign-in/social', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
provider: 'google',
callbackURL: window.location.href,
}),
});
const data = await response.json();
window.location.href = data.url ?? data.data.url;2. Handle Callback
Better-Auth automatically handles the OAuth callback at /api/v1/auth/callback/google and redirects the user back to your application with a session.
When the provider's email matches an existing local account that is not linked to this
provider yet, the sign-in links to that account only if its email is verified. Otherwise
the callback redirects with error=account_not_linked. The platform identity provider
(objectstack-cloud) is the one exception, and an unlinked provider never re-links
itself. See Linking to an existing account.
A sign-in that would create a new account through a social provider is judged by the
deployment's audience posture. Under email_domain, and under open while email
verification is in force (the default; only the deployment can declare it off), the
account is created only when the provider reports the address verified. Otherwise the
sign-in is refused 403 SELF_REGISTRATION_CLOSED (the callback redirects with
error=SELF_REGISTRATION_CLOSED), as it is under invite_only, and nothing is written:
no account, no session, no membership. A pending invitation addressed to the person does
not change this, because it is matched by the same address; once the provider verifies
the address, the next sign-in is admitted. The rule covers every provider in
socialProviders, a provider added later included. Identity providers an operator
registers (oidcProviders entries and SSO providers) are not affected, and neither is
the first account of a fresh install.
Enterprise Authentication Hardening (ADR-0069)
Beyond the core flows above, @objectstack/plugin-auth ships an enterprise
hardening layer. Every toggle is configured from Setup → Authentication and
is wired to real runtime enforcement (ADR-0049 — no setting ships without the
code that reads it). Changes take effect immediately; no restart is required.
Password policy
| Setting | Effect |
|---|---|
password_reject_breached | Reject passwords found in the Have I Been Pwned corpus (k-anonymity range check — the password is never sent in full). |
password_require_complexity / password_min_classes | Require a minimum number of character classes (upper / lower / digit / symbol). |
password_history_count | Block reuse of the last N passwords. |
password_expiry_days | Force a password change after N days; expired sessions are gated until the password is rotated. |
Anti-abuse (lockout & rate-limiting)
| Setting | Effect |
|---|---|
lockout_threshold | Lock an account after this many consecutive failed sign-in attempts. Counts both stages: wrong passwords and wrong two-factor codes. |
lockout_duration_minutes | How long a lockout lasts, at either stage. Admins can clear it early with the Unlock action on the user record, which releases both stages. |
rate_limit_max / rate_limit_window_seconds | Per-IP request throttle on auth endpoints. |
The two stages keep separate counters — sys_user.failed_login_count for the
password check, sys_two_factor.failed_verification_count for the second factor —
so a locked password stage and a locked second factor are independent states. Each
counter resets on a success at its own stage, and the admin Unlock Account
action clears both at once.
The password-stage counter and lock belong to the account, not to the text
typed into the sign-in form. Both live on the sys_user row that the sign-in's own
credential check resolves the address to. So every refused sign-in on that account
counts toward its one lock, whichever spelling of the address it used. A lock refuses
every sign-in that resolves to the account, the correct password included, and a
successful sign-in under any spelling clears the counter.
Every password sign-in door (email and password, phone number and password) counts
toward that one lock and checks it before the password, and a locked account is
refused, with the answer password sign-in gives, on every door that ends in a session
for it: one-time codes, sign-in links, an address-change confirmation opened without a
session, the second-factor step, sign-in through an identity provider (social, generic
OAuth, enterprise SSO) and the device grant, so the lock also reaches an account that
has no password.
Setting lockout_threshold to 0 disables the password-stage lockout only.
Two-factor verification keeps a built-in limit of 10 attempts per 15 minutes,
because it is the last check before a session is issued. Two-factor verification
additionally caps attempts at 5 per challenge, which is not configurable: a
threshold above 5 simply forces the attacker to restart the sign-in flow more
often before the account-level lock engages.
Multi-factor (enforced MFA)
| Setting | Effect |
|---|---|
mfa_required | Require MFA org-wide; saving it on also turns two-factor enrollment on, and the save is refused while OS_AUTH_TWO_FACTOR=false pins enrollment off. An organization can require it on its own (require_mfa) only while two-factor enrollment is on; a requirement stored while enrollment is off is not enforced, which GET /api/v1/auth/config reports as features.twoFactor: false. |
mfa_grace_period_days | Grace window for existing users to enroll. After it elapses, the session is allowed to sign in but gated from data access until TOTP is enrolled — the Console surfaces a remediation overlay that walks the user through enrollment. |
Sessions
| Setting | Effect |
|---|---|
session_idle_timeout_minutes | Expire a session after inactivity. |
session_absolute_max_hours | Hard cap on total session lifetime regardless of activity. |
max_concurrent_sessions_per_user | Cap simultaneous sessions; the oldest is revoked (expired in place) when the cap is exceeded. |
Network
| Setting | Effect |
|---|---|
allowed_ip_ranges | Restrict authenticated access to one or more CIDR ranges or exact addresses, IPv4 or IPv6 (203.0.113.0/24, 2001:db8::/32, 192.0.2.7). An entry that is neither is refused when you save it. The address judged is the one the server establishes, by the same rule as the inbound rate limiter: a forwarded header only when the stack declares server.trustProxy (its trusted-network form { networks: [...] } believes it only from the proxies it names, read from the right past them), the connection's peer address otherwise. Behind a reverse proxy, declare server.trustProxy, or the allow-list judges the proxy's own address; true is sound only behind a proxy that overwrites X-Forwarded-For, never one that appends to it. A request whose address cannot be established is refused with 403 IP_NOT_ALLOWED, like one outside the ranges. last_login_ip records the same address. A save that leaves out your own address is refused, and clearing the field applies at once: see Saving, clearing and lockout recovery. |
How enforcement works. Password expiry (an administrator-forced password change included) and enforced MFA share a single session-validation gate.
customSessionstamps the session user with anauthGateposture, and every transport seam that resolves a caller from the session consults it through the one shared decision in@objectstack/core(evaluateAuthGateand its helpers): the REST server, the runtime dispatcher (which also serves the MCP HTTP endpoint), and every route family that a plugin or service mounts directly on the host server and that resolves its own caller, at the family's own door. A gated session gets403with the gate's own code (PASSWORD_EXPIRED,PASSWORD_RESET_REQUIREDfor an administrator-forced change, orMFA_REQUIRED) at whichever of them serves the request.API keys answer for the account, not for the password. Each code has a scope.
MFA_REQUIREDholds the account: an API key whose owner owes MFA enrollment is refused with the same403 MFA_REQUIREDand message on every face that admits keys.PASSWORD_EXPIREDandPASSWORD_RESET_REQUIREDhold password sign-in only, so the owner's API keys keep working. The refusal is not a revocation: the same key works again the moment its owner enrolls. By default a request is judged by the credential that admitted it, so a session cookie sent beside an API key never answers for the key. The storage routes are the exception: there a gated session is refused whatever else the request carries. The auth endpoints (sign-in, change-password, two-factor enrollment and sign-out among them) and a short allow-list kept with that decision (health and discovery among them) still pass, so the user can remediate. Platform administration is not part of that exemption: the platform-admin actions refuse a gated session with the same403, a platform administrator's included. This is why a non-compliant user can sign in but can't read or change data, or administer the platform, until they fix the issue.An API key authenticates only as an owner who exists. A key whose owner has no user record is answered on every face that admits keys exactly as a key that does not exist (the generic
401 UNAUTHENTICATED), a session sent beside it never answers for it, and the server logs the refused key's row id and owner id. The remedy is a new key minted by an existing user; revoke the old key in Setup → API Keys.
Saving, clearing and lockout recovery
These rules apply to allowed_ip_ranges.
-
An entry the server cannot read is refused. Each entry is an IPv4 or IPv6 address, or an address followed by
/and a prefix length written in decimal digits: one or two digits, from 0 to 32, for IPv4, and one to three digits, from 0 to 128, for IPv6. Any other entry is refused with400 SETTINGS_VALIDATION, whatever address you save from, and nothing is stored. The field error names the entries, also listed inconstraint.invalidEntries. This check runs before the address check below, on every write, including writes made inside the server. AnallowedIpRangeslist the deployment declares in its own auth configuration is held to the same rule and refused at startup. An entry the server cannot read matches no address at sign-in. If a stored list orOS_AUTH_ALLOWED_IP_RANGESalready holds one, the server logs it at startup with the entry named, and only the list's other entries admit anyone. -
A value that is not text is refused. The field holds its entries as text, one per line or comma-separated. A value written in another form, such as a JSON list, a number or an object, names no list: through the API or by a write inside the server, it is refused the same way, with
constraint: { type: 'textarea' }, and nothing is stored. A value of another form stored before this check admits no address at sign-in, and the server logs it at startup. Save the list as text, or clear it. -
A save that would lock you out is refused. When you save the field, the server checks the new list against the address your own request comes from. It finds that address by the same rule as the gate (
server.trustProxydecides whether the forwarded headers count). If no entry matches it, the save is refused with400 SETTINGS_VALIDATIONand nothing is stored. The check sits on the settings API save,PUT /api/settings/auth, which Setup → Authentication calls, so any HTTP client gets the same answer. The message names your address, says the list would refuse your own next sign-in, and asks you to add your address or its range, or to save from an address the list matches. It ends with the recovery steps below. It is written in your language (English, Chinese, Japanese or Spanish). The field error indetails.fieldsalso carries your address asconstraint.clientAddress. If the server cannot establish your address at all, any non-empty list is refused, because the gate would refuse you too. Only a change is checked: saving the list already in force again is not refused. Writes made inside the server (boot, seed, migrations) carry no request, so no address is checked for them. -
Setup shows your address before you save. Under the field, Setup → Authentication shows the address the server judges for your request, read from
GET /api/v1/auth/admin/client-address(platform administrators only), which answers{ clientAddress, trustProxy }: the note says whether that address came from the forwarded headers of a proxy the server trusts (server.trustProxy) or from the connection itself, which behind a proxy it does not trust is the proxy's own address, and whenclientAddressisnullit says instead that no non-empty list can be saved. -
Clearing takes effect at once. Empty the field and save. No restart is needed: the gate goes back to the list the deployment itself declares (
allowedIpRangesin its auth configuration, for example set by anauth:configurehandler), or to no restriction when it declares none. A clear is never refused. -
If you are already locked out, recover in four steps:
- Start the server with
OS_AUTH_ALLOWED_IP_RANGESset to an empty value (OS_AUTH_ALLOWED_IP_RANGES=). Environment variables are read at startup, so a restart is needed. An empty value is not the same as an unset variable: any value that is set, the empty string included, is an env override in force. It wins over the stored list, and an empty list means no restriction. - Sign in.
- Clear the stored list: send
PUT /api/settings/authwith{ "allowed_ip_ranges": null }. While the variable is set the field is locked, so Setup → Authentication shows it read-only and any other save to it is refused with409 SETTINGS_LOCKED; a clear (null) is the one write the lock lets through. It clears the stored value and changes nothing in force: the answer still reads the empty value from the environment. - Remove the variable and restart. With the stored list cleared, nothing brings it back: the gate applies the list the deployment declares, or no restriction.
Removing the variable without step 3 brings the stored list back at the next restart, and locks you out again.
- Start the server with
Advanced Features
Two-Factor Authentication (2FA)
ObjectStack wires the better-auth two-factor (TOTP) plugin at the backend layer. The endpoints below let you build an opt-in 2FA experience in a custom account UI; for organization-wide enforced MFA, see Enterprise Authentication Hardening — the Console ships an enrollment/remediation flow for that path.
A complete opt-in 2FA UX still needs to handle:
- enrollment (
/two-factor/enable), - TOTP confirmation (
/two-factor/verify-totp), - the
twoFactorRedirectresponse returned by password sign-in — and by the one-time-code and link doors too (/phone-number/verify,/magic-link/verify, and/verify-emailwhen it signs the user in): an account with an enrolled second factor is signed in by no one-time code or sign-in link alone, and its session is issued only after the second factor, and - backup-code recovery.
/two-factor/enable always issues a secret that must be confirmed — including
on re-enrollment. Calling it on an account that already has 2FA active replaces
the stored secret and marks the enrollment unconfirmed, so the new secret is
not accepted at the sign-in challenge (400 TOTP_NOT_ENABLED) and totp is
not offered in twoFactorMethods until /two-factor/verify-totp succeeds with
the live session. The replaced secret stops working as soon as enable returns,
so a re-enrollment UI must run the confirmation step in the same session, and
must show the backup codes from that response — they are the recovery path if
the authenticator was never captured.
For custom account UIs, enable the backend plugin in configuration:
new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
plugins: {
twoFactor: true, // Enable backend two-factor endpoints
}
})Enable 2FA for User
const response = await fetch('http://localhost:3000/api/v1/auth/two-factor/enable', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
password: currentPassword,
}),
});
const { totpURI, backupCodes } = await response.json();
// Display totpURI as a QR code and show backupCodes once.Verify 2FA Code
const response = await fetch('http://localhost:3000/api/v1/auth/two-factor/verify-totp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: '123456' // Code from authenticator app
})
});Passkeys (WebAuthn)
Not yet implemented. Passkey/WebAuthn support is not currently wired into
AuthPlugin. Theplugins: { passkeys: true }flag is accepted but no passkey plugin is registered, so/passkey/*endpoints are not available. Since nothing is behind it,GET /api/v1/auth/configstopped reporting afeatures.passkeysflag in protocol 17 (#7481) — there is no capability for a client to detect. This section will be updated once passkey support ships.
Magic Links
Enable passwordless magic link authentication:
new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
plugins: {
magicLink: true, // Enable magic links
}
})Server-side only, for now. The endpoints below work whenever
plugins.magicLinkis on, but no shipped login UI drives them — soGET /api/v1/auth/configstopped advertising afeatures.magicLinkflag in protocol 17 (#7481): a served flag no client reads told deployers a sign-in option existed that users could never reach. Call the endpoints from your own UI. The flag returns alongside the built-in magic-link login screen (objectui#4179).
Send Magic Link
const response = await fetch('http://localhost:3000/api/v1/auth/sign-in/magic-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com'
})
});Verify Magic Link
// User clicks link in email
const response = await fetch(`http://localhost:3000/api/v1/auth/magic-link/verify?token=${token}`);A sign-in link alone never signs in an account with an enrolled second factor:
verification answers it with the same twoFactorRedirect challenge password
sign-in gives, and no session is issued until the second factor is verified
(/two-factor/verify-totp, or a backup code) — on the callbackURL redirect
lane as well. Accounts with no enrolled factor are signed in by the link as
before.
Phone-Number Sign-In
Enable phone numbers as a first-class sign-in identifier (better-auth
phone-number plugin). Opt-in — off by default:
new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
plugins: {
phoneNumber: true, // Enable phone sign-in
}
})With the CLI serve command, OS_AUTH_PHONE_NUMBER_ENABLED=true flips the
same flag. The plugin adds sys_user.phone_number (unique) and
sys_user.phone_number_verified; the login UI discovers the capability via
features.phoneNumber on GET /api/v1/auth/config.
Sign In with Phone + Password
const response = await fetch('http://localhost:3000/api/v1/auth/sign-in/phone-number', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phoneNumber: '+8613800000000',
password: 'password123'
})
});OTP Flows (Require an SMS Service)
The OTP surfaces — POST /phone-number/send-otp + POST /phone-number/verify
(sign-in / verification) and POST /phone-number/request-password-reset +
POST /phone-number/reset-password (self-service reset) — only work when an
SMS service is wired (@objectstack/service-sms registers the sms kernel
service). Without one, send-otp fails loudly — 400 with
code: "SMS_SERVICE_REQUIRED" — instead of silently dropping
the code; phone sign-in is then password-based only (an admin sets the
password — see Admin User Management below). OTP requests are rate-limited
per phone number to prevent SMS-pumping abuse.
Placeholder Emails for Phone-Only Accounts
better-auth requires a unique email per user, so accounts created with only a
phone number get a generated placeholder address of the form
u-<random>@placeholder.invalid. These are never deliverable (.invalid is
an RFC 2606 reserved TLD), never derived from the phone number (so exports
and logs can't leak it), and every auth mail callback (password reset,
invitation, magic link) refuses them with a PLACEHOLDER_EMAIL error.
Organizations (Multi-Tenant)
Enable organization/team support:
new AuthPlugin({
secret: process.env.OS_AUTH_SECRET,
baseUrl: 'http://localhost:3000',
plugins: {
organization: true, // Enable organizations
}
})Membership tiers are a closed list
sys_member.role is better-auth's own column and the one place ObjectStack
keeps that vocabulary (ADR-0090 D3's single boundary exception). It holds
exactly five values — owner, admin, delegated_admin, member, external — and
your stack cannot add to them.
external is for a portal user (a supplier's or a customer's person) who joins
the organization without joining its staff. It is held alone, never beside
another tier. Its holder reads only its own identity rows, does not receive the
member defaults (member_default or an app's isDefault set), is never placed
in a business unit, and reaches application data only through the positions and
permission sets granted to it explicitly.
That is deliberate (ADR-0108). A membership tier answers what is your standing
in this organization, which decides what you can reach: delegated_admin,
for instance, is the tier that may reach /organization/invite-member without
being an org admin. What you may do with records is a
position, and every position assignment carries
an audit stamp (granted_by), a validity window, and a scope check that a tier
never had.
To invite someone straight into a position, put it in the invitation's placement rather than its membership tier:
POST /api/v1/auth/organization/invite-member
{
"email": "new.hire@example.com",
"role": "member",
"businessUnitId": "bu_field_sales",
"positions": ["sales_rep"]
}The tier stays member; the capability rides in positions. Placement is
authorized at issuance against the issuer's adminScope, so a delegated admin
can use it inside their own subtree — where the tier route was open to org
admins only. On acceptance the positions become real sys_user_position rows.
Earlier releases registered every declared position and permission-set name as
a valid membership tier, so naming one directly in the invitation was accepted.
That path is removed: because every value stored in the tier column is
projected into current_user.positions, it granted capability with none of the
controls above. Naming a position as an invitation's tier is now refused with
ROLE_NOT_FOUND. Use positions as shown.
One limit still bounds invitations as a provisioning path: they never hand out
more authority than the issuer has. An issuer below admin grade may invite
as plain member only, and no invitation may confer a tier above the issuer's
own.
Attaching an existing user to an organization
POST /api/v1/auth/organization/add-member attaches an existing account to
an organization directly — no invitation, no email round-trip.
POST /api/v1/auth/organization/add-member
{
"userId": "usr_01HZX…",
"organizationId": "org_beta"
}The body also carries the membership tier, under better-auth's own column name
for it — the same field the invitation example above sends (see Membership
tiers are a closed list). It accepts a
single tier name or an array of them. snake_case spellings are accepted
alongside camelCase for the identifiers (user_id, organization_id,
team_id), so a value pasted straight out of the record grid works.
organizationId may be omitted, in which case the membership lands in the
calling admin's active organization. teamId is optional and has no such
fallback: omit it and the member simply joins no team.
This is an ObjectStack mount, not a better-auth route
better-auth declares addMember as a server-only API with no HTTP path of
its own — measured on the then-installed 1.7.1, where addMember builds its
endpoint with no path argument while every sibling in the same module
(/organization/remove-member, /organization/list-members,
/organization/leave, …) passes one. So the vendor's documentation does not
list this URL, and an audit that enumerates better-auth's mounted surface will
not find it there either. ObjectStack mounts it ahead of the
catch-all and wraps the vendor's server-only endpoint; the vendor's own checks
(already-a-member, membership limit, team resolution, hooks) are not
reimplemented.
The admit set is platform admin only. An organization owner or organization
administrator is refused 403 PERMISSION_DENIED, and that is deliberate under
ADR-0068: standing inside an organization is not standing on the platform.
Attaching someone to an organization without their consent is a
platform-operator action, and the vendor endpoint performs no authorization of
its own precisely because it was built to be called only from trusted server
code.
Refusals, with both halves of the ADR-0112 envelope:
| Status | code | When |
|---|---|---|
401 | UNAUTHENTICATED | No session. Checked before the body, so an anonymous caller with a malformed body still gets 401. |
403 | PERMISSION_DENIED | Signed in, but not a platform admin — including organization owners and administrators. |
501 | NOT_IMPLEMENTED | The organization plugin is off (auth.plugins.organization). Checked before the body: a payload nit is not worth reporting for a capability the deployment does not have. |
400 | INVALID_REQUEST | Missing userId, or a missing/empty membership tier. |
400 | USER_NOT_FOUND | No account with that userId. |
400 | USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION | The account already holds a membership in that organization. |
400 | NO_ACTIVE_ORGANIZATION | organizationId was omitted and the calling admin has no active organization to fall back to. |
403 | ORGANIZATION_MEMBERSHIP_LIMIT_REACHED | The organization is at its membership limit (better-auth's membershipLimit, default 100). |
The last five are the vendor's own verdicts, forwarded verbatim rather than re-adjudicated.
On a walled deployment this is the only way to attach an existing user
Under a walled tenancy posture the other paths do not reach:
- Create User joins only the account it is creating — to the administrator's current organization (see Create a User Directly). It never attaches an account that already exists.
- Hand-writing the membership row is not available:
sys_memberis managed by better-auth and generic CRUD on it is suppressed under the ADR-0010 lock. - Invitations need an email round-trip, which phone-number-only accounts cannot complete.
That leaves this route. An administrator who does not know it exists reasonably concludes the platform cannot attach an existing user to an organization at all.
Deleting an organization
POST /api/v1/auth/organization/delete with { "organizationId": "org_beta" }
is better-auth's endpoint. Before better-auth writes anything, the platform
refuses a delete it must not run:
| Status | code | When |
|---|---|---|
403 | PERMISSION_DENIED | The target is the Default Organization and the caller is its last administrator. |
409 | DELETE_RESTRICTED | The organization still owns records. dependents lists each table and its row count. |
503 | SERVICE_UNAVAILABLE | A read the decision depends on failed. Nothing was deleted, so retry. |
A caller better-auth refuses itself (no session, not a member, a membership
tier without the organization: ['delete'] permission) gets better-auth's
answer and no count.
A host check of its own. A host that must refuse a delete for its own
reasons, such as a subscription that will charge again, sets
organizationDeleteGate on the AuthPlugin (or AuthManager) options:
new AuthPlugin({
organizationDeleteGate: async ({ organizationId, session, acceptLanguage }) => {
if (!(await billing.hasActiveSubscription(organizationId))) return undefined; // go ahead
return {
status: 409,
body: {
code: 'DELETE_RESTRICTED',
message: 'The organization has a subscription that will charge again.',
userMessage: 'Cancel the subscription first.', // in the request's language
},
};
},
});- When it is asked. Once per delete, last, only for a delete that the checks above would let through. A request the auth mount refuses first (the IP allow-list, two credentials naming different accounts) never reaches it.
- What it receives.
organizationIdis the id better-auth parsed from the JSON body (a body it does not parse, it answers415without asking), so the host reads no request body itself.sessionis the caller:userId, plusactiveOrganizationIdandimpersonatedBywhen the session has them.acceptLanguageis the request'sAccept-Languageheader. - What it answers.
undefinedornulllets the delete go ahead. A refusal is answered exactly as given: itsstatus(400to499) and itsbody, which needscodeandmessage;userMessageand any other field pass through as given. Nothing is deleted. - Fail-closed. A check that throws, or answers anything else, is answered
503 SERVICE_UNAVAILABLEnamingorganizationDeleteGate, and nothing is deleted. The host's error text is not sent to the client.
Admin User Management
Platform admins get email-independent account management on the Users list
— the create_user / set_user_password actions there drive these
endpoints. Creating a user needs plugins: { admin: true } (forced on when
SCIM is enabled); setting a password works with or without it. All
three routes are gated server-side on the session's isPlatformAdmin — the
PLATFORM_ADMIN standing of ADR-0095 D3 — with the legacy better-auth role
scalar of admin still accepted as a back-compat fallback; the
platform_admin name in positions is not read. They drive the better-auth
pipeline, so created accounts get a real scrypt-hashed credential and can sign
in immediately.
Create a User Directly
const response = await fetch('http://localhost:3000/api/v1/auth/admin/create-user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'new.user@example.com', // and/or phoneNumber (requires plugins.phoneNumber)
name: 'New User',
generatePassword: true, // or pass an explicit `password`
mustChangePassword: true // default true
})
});
// → { success, data: { user, organizationId?, membershipCreated, temporaryPassword? } }Which organization the user joins. Under a walled posture (group /
isolated) the new user joins the calling administrator's current
(active) organization as member, in the same step as the account — the
organization the administrator has switched to in the console. There is no
organization choice: to add someone to another organization, switch to it
first. An administrator with no current organization is refused with
400 NO_ACTIVE_ORGANIZATION and no user is created. Under the single posture
(a degraded wall included) the user joins the default organization, as every
user an administrator creates does (Membership).
The join is better-auth's addMember, the same act as Add Member, inside
the account's transaction: an organization at its membership limit refuses the
call with that verdict, and no user is created. It applies under
membershipPolicy: 'invite-only' too. Raising the new member above member
stays a separate, audited step on the organization's Members list.
A generated temporary password is returned once in the response (the
Users-list action reveals it in a one-shot dialog) and is never persisted or
logged. While mustChangePassword is set, the user is blocked with
403 PASSWORD_RESET_REQUIRED on every protected route until they complete a
password change. It is the same gate as password expiry, under its own code,
and like expiry it holds password sign-in only: the user's API keys are not
held by it. Nor is an administrator's impersonation session, which is minted
from the administrator's own session and is not the user's password sign-in:
an administrator can impersonate the user to verify their access before the
user has changed the password, while the user's own sign-in stays blocked.
Enforced MFA (MFA_REQUIRED) holds the account, so it still holds an
impersonation session of that user.
Set / Reset a Password
POST /api/v1/auth/admin/set-user-password accepts
{ userId, newPassword } or { userId, generatePassword: true } plus the
same mustChangePassword flag. It also provisions a credential account for
SSO-onboarded users who never had a local password.
The forced reset also carries revokeSessionsAndKeys, on by default: it
ends every session of the user, revokes every API key they own that is not
revoked (its revoked flag false or unset), unlinks
every sign-in account linked to the user other than the password, and, where
the OAuth provider is enabled, ends every app authorized to the user (its
consents, refresh tokens and stored access tokens are deleted, so the app asks
to be authorized again and an MCP access token is refused on its next request)
and, where device authorization is enabled, every device sign-in approved for
the user and not yet collected. It also disables every OAuth application the
user registered and revokes every SCIM credential the user minted, as a
self-service reset does; an application another account registered and a
credential another administrator minted are not touched, and the user's
single sign-on providers and two-factor enrolment are kept. A suspected
compromise leaves no live credential behind. Pass revokeSessionsAndKeys: false for a routine reset,
which ends none of these; as after any password change, an MCP access token
issued before it is refused and the app gets a new one with its refresh token. The response reports what was ended
(revoked: { sessions, apiKeys, signInAccounts, authorizedApps, ownedApps, scimCredentials, failed, complete },
ownedApps counting the applications disabled and scimCredentials the
credentials revoked; the ledger row carries the same counts), and revoked keys
stay revoked after the password change. The operator's os user set-password
ends the same, reading the authorized apps, device sign-ins, registered
applications and minted credentials the project database holds, and reports
each count.
Bulk Import Users
POST /api/v1/auth/admin/import-users accepts the same payload shapes as the
generic data import (rows[] / csv / xlsxBase64, dryRun), but writes
every row through better-auth so the accounts are login-capable:
passwordPolicy: 'auto'(default) — decides per row: a row with a deliverable channel (a real email + a wired email service, or a phone + a wired SMS service) is invited (no shared secret leaves the server); a row with no deliverable channel (placeholder email, phone-only without SMS, or an email row when no email service is wired) falls back to a temporary password. This keeps the temporary-password blast radius to only the rows that genuinely can't be reached, and — unlikeinvite— it never fails the request for missing infrastructure (undeliverable rows just degrade). The per-row outcome is reported asrows[].delivery(email/sms/temporary), with a batch breakdown onsummary.delivery.passwordPolicy: 'invite'— force the invite path for every row: a real email gets a set-your-password email (requires an email service), a phone-only row an invitation SMS (requires a wired SMS service + phone-OTP first sign-in). Rows that aren't reachable are failed per-row (never downgraded) — pick this when a temporary-password fallback is unacceptable.passwordPolicy: 'temporary'— force the no-infrastructure path (no email, no SMS) for every row: per-row generated temporary passwords, returned once in the response, withmustChangePasswordenforced.passwordPolicy: 'none'— identity only: accounts are created without a credential record. Users first sign in through a channel (phone OTP, magic link, or a password-reset link) and the Console detects the missing password (hasLocalPassword()) and offersPOST /api/v1/auth/set-initial-password.mode: 'insert' | 'upsert'withmatchBy: 'email' | 'phone'. Upsert updates only touch profile fields (name,image,phone_number,role) — a re-imported file can never modify an existing user's email or reset their password.- A
positionscolumn assigns positions: position machine names, several separated by;(an array on a JSON row) — the same columnimport-sso-usersreads. Each is assigned after every row has landed, as asys_user_positiongrant written under the importing admin's own access, so it passes the checks Setup applies when you assign a position there (the position must exist, and you must be allowed to assign it). A position that does not exist or is refused is reported on its row and the user is still created:rows[].positionsis an array with one entry per named position and its outcome (assigned,already_assigned,unresolved, orrefusedwith the refusal'scode), andsummary.positionscounts them. A cell that is not a list of names (a number or an object on a JSON row) assigns nothing, and that row'srows[].positionsis the string'unreadable', not an array — check for it before reading the entries. It counts once undersummary.positions.unresolved, and the user is still created. The import only adds positions; it never removes one a user holds. Permission sets come with the position (a position carries its sets); a direct grant stays a Setup step. - When a file's positions cannot be judged at all, the users are still
created and only the positions are refused: every named position is
reported
refusedon its row, with codeNOT_IMPLEMENTEDwhen the server cannot assign positions during an import, orPERMISSION_DENIEDwhen your own access cannot be resolved. A dry run never assigns positions, and reportssummary.positionsas zeros. - Which organization the rows join follows Create a User Directly:
under a walled posture (
group/isolated) every imported user joins your current organization asmember, each row in the same step as its account, so thepositionscolumn validates against that organization. A row the organization refuses (its membership limit, say) is failed on its row with that refusal's code, and that user is not created: no account, no temporary password, no invitation. The other rows still land. A row that matches an existing user onupsertjoins too; if the join is refused, the row fails and its profile update is not applied. With no current organization the whole import is refused with400 NO_ACTIVE_ORGANIZATIONand no user is created — a dry run included, so the preview tells you before you import. Switch to the organization the people belong to first. Under thesingleposture nothing changes: users join the default organization. - Synchronous only, at most 500 rows per request (password hashing is CPU-bound); split larger files into batches. Imports are not undoable.
In the Console, platform admins reach this from the Users list → Import
toolbar button (shown when the admin plugin is enabled). The import wizard
uploads a CSV/Excel file, maps columns, previews with a dry-run, and — for any
rows that resolve to a temporary password (all of them under temporary, only
the unreachable ones under auto) — reveals the generated passwords once with a
download, splitting files above 500 rows into batches automatically.
Adding people on a cloud-managed environment
On a cloud-managed environment (OS_CLOUD_MANAGED=1) people sign in through
the identity provider of the organisation that hosts the environment, so
create-user and import-users answer 409 RESOURCE_CONFLICT there. Two
doors add a person ahead of their first sign-in instead. Neither needs the
admin plugin, and both are platform-admin gated:
POST /api/v1/auth/admin/add-sso-usertakesemail,name, and optionallypositions,permissionSets(lists of machine names) andmanager(the manager's email address). It answers201, or200withalreadyPendingwhen the person was already added and has not signed in yet.POST /api/v1/auth/admin/import-sso-userstakescsv(columnsemail,name,positions,permission_sets,manager_id; lists separated by;,manager_idholding the manager's email address) orrows, at most 500 rows. Each row is judged and written on its own, so a bad row fails with its own message and the good rows land. The answer carries asummaryand one result per row.
Both doors, and remove-sso-user below, also take an optional
organizationId. A console action forwarded to the auth mount carries the
caller's active organization there, so the key is admitted only when it
equals the organization the caller's session is working in. A different
organization gets 400 INVALID_REQUEST naming both organizations; a
non-string or empty value gets 400 INVALID_REQUEST saying the key must be
the id of the organization you are working in (a non-string value is checked
before the session, so this is the answer even when the session has no
organization); a string organization from a caller whose session works in no
organization gets 400 NO_ACTIVE_ORGANIZATION naming the organization sent. Every refusal
comes before anything is written or any host is told. The value never
widens or chooses scope: the organization a person joins is always read from
the session.
The person is stored pending (sys_user.source reads idp_pending): no
password, and no session until they sign in through the hosting
organisation's identity provider. Every password door refuses a pending
person (set-user-password, set-initial-password, the email and phone
reset), and so does every other way to open a session. Their first sign-in
through the platform identity provider attaches to the row and the source
becomes idp_provisioned; only that provider clears the pending state, and a
sign-in through any other one leaves the person pending. Their positions, permission sets and manager apply
from the moment they are added, so seed data and approval flows can name them
before they sign in. Off a managed environment both doors answer 409.
On a cloud-managed environment the organisation that hosts it decides who is a
member and at which membership tier, so every organization door that writes or
deletes a membership row (the six below: removing a member, changing a member's tier
with Make Owner included, leaving, accepting an invitation, creating an
organization, which makes the caller its owner, and deleting one, which ends
every membership in it) answers 409 RESOURCE_CONFLICT there and changes
nothing, and their seven actions are hidden. The one exception is
POST /api/v1/auth/organization/add-member, which admits exactly a platform
administrator, adding a membership, so the operator can restore one the
environment lost. The administrator names the membership tier in the request
body, where it is required (a request without it is refused 400), and
ObjectStack passes it to better-auth unchanged. A signed-in caller who is not a platform
administrator is refused 403 PERMISSION_DENIED, and a caller with no session
is answered 401 UNAUTHENTICATED. The other
organization doors write no membership row (teams, invitations, the active
organization, the organization's own fields) or only read, and answer as before.
POST /api/v1/auth/organization/remove-member
POST /api/v1/auth/organization/update-member-role
POST /api/v1/auth/organization/leave
POST /api/v1/auth/organization/accept-invitation
POST /api/v1/auth/organization/create
POST /api/v1/auth/organization/deleteSigning in does not lock the manager: a platform administrator still changes
it with Set Manager (POST /api/v1/auth/admin/set-user-manager). That
endpoint refuses only a person a SCIM directory holds, whose manager is changed
in the directory.
A host can be told about people as they come and go: the environmentUserHost
option of the auth plugin is called after a person is added, and before a
person is deactivated (admin/ban-user), reactivated (admin/unban-user) or,
while still pending, removed (admin/remove-sso-user).
It is never called inside a database transaction. Each event names the
administrator who acted, the administrator at the keyboard when the session
is an impersonation (impersonatedBy), and, when the acting administrator
holds a linked objectstack-cloud account, their cloud user id from that
account. None of these is read from the request.
A host can refuse by throwing EnvironmentUserHostRefusal with a 409 (for
example, an organization owner or admin, who is removed in the console) or a
403 (for example, DEVELOPER_ORGANIZATION_MEMBER_LIMIT_REACHED). The door
answers with that status, code and sentence: a refused deactivation or
reactivation writes nothing, and a refused add takes that person back out
(on an import, that row alone fails). Any other host failure refuses a
deactivation with 503 and writes nothing, since only the host can say
whether the person is an organization owner or admin. It never undoes or
blocks an add or a reactivation: the answer carries host: { notified: false, reason }. Adding a person who is still pending again tells the host again
and changes nothing else: positions, permission sets or a manager sent with
it are listed on the answer as notApplied; set them on the person's record.
A pending person who never signs in, for example one added with a mistyped
address, can be removed: POST /api/v1/auth/admin/remove-sso-user takes
{ userId } (and the optional organizationId described above), removes
the person with their positions, permission sets and membership, and cancels
their invitation at the host. The host is asked first, through its
userRemoved member; a host without that member is asked
through userDeactivated for the pending person instead, which means the same
thing, but a host should implement userRemoved. A host's refusal leaves the
person as they are. A host that cannot be reached refuses the removal too,
with 503 and nothing removed, as it refuses a deactivation: the door calls
the host once and keeps no record to ask again from, so try again once the
host is back. A person who is not pending (they have signed in, or were not
added this way) is refused with 409: deactivate them instead. That holds at
the removal itself: the person is checked again inside the removal's unit of
work and the delete carries source: 'idp_pending', so a person whose first
sign-in lands while the host is asked is not removed either, and the answer
says the host was already told. Because sys_user has cascading lookups, the
engine deletes the row by id after walking them, so a first sign-in that
commits in that narrow window is not yet refused. A record that
still points at the person through a lookup that restricts deletes refuses the
removal with that lookup's own answer, and nothing is removed; when the host
had already cancelled the invitation of a person who is still pending and not
deactivated, the door sends the invitation again through userAdded, once,
and the answer says whether that worked. A removal that committed writes one
sys_audit_log row naming the administrator (action: 'delete', metadata
{ event: 'user.admin_removed_pending', hostNotified }); a refused one writes
none. Like the add doors, it is platform-admin gated and answers 409 off a
managed environment.
A deactivated person is never sent an invitation: adding a deactivated pending
person again calls no host and answers host: { notified: false, reason: 'deactivated' }; reactivating them is what tells the host again.
Each door calls the host once and keeps no record of the call. Delivering it
durably, and keeping each person's invitation status, is the host's job: a
host may queue and retry a call it could not complete. A call can reach a host
more than once (adding a person who is still pending again tells the host
again), so a host should treat a repeat as harmless, and should cancel an
invitation by the event's userId, never by its email address, which an
administrator may have typed wrong and may type again for someone else.
admin/ban-user and admin/unban-user work without the admin plugin: on a
deployment without it the ban is written by the platform, and a banned user is
refused a session with the same 403 BANNED_USER answer the admin plugin
gives. A ban or an unban that committed writes one sys_audit_log row naming
the administrator (action: 'update', metadata { event, hostNotified }, the
event user.admin_banned or user.admin_unbanned); a refused one writes none.
A ban's row also counts what it ended beside the ban (suspendedServiceAccounts,
revokedOwnedApps, revokedScimCredentials, revocationComplete; see
What a ban, a deactivation or a removal ends).
The reason and expiry are on the row plugin-audit records for the user's change.
SCIM Connection Credentials
With SCIM enabled (OS_SCIM_ENABLED=true, or plugins.scim), an identity
provider such as Okta or Entra ID provisions users through
/api/v1/auth/scim/v2/* with a bearer credential the platform issues. Only a
platform administrator mints or revokes one, through the same gate as the
routes above; anyone else is refused 403 PERMISSION_DENIED (401 when
signed out).
curl -X POST http://localhost:3000/api/v1/auth/admin/scim/mint-credential \
-H 'Content-Type: application/json' -H "Authorization: Bearer $ADMIN_SESSION" \
-d '{ "connectionId": "okta-prod", "label": "rotation 2026-Q4" }'
# → { success, data: { credentialId, connectionId, token, tokenHint, expiresAt } }connectionId(required) names the connection every provisioned resource is scoped to: at most 246 characters, so the connection's audit actorsvc:scim:<connectionId>fits the audit log's 255. Optional:label,expiresAt(a future ISO date-time),provisioningDomainId, andorganizationId(the organization that owns the credential row; the Default Organization when omitted).- The
tokenis shown once, in this response only (Cache-Control: no-store). Only a keyed one-way digest of it is stored; it is not readable through the data API, the audit log or the logs afterwards. Paste it into the identity provider's SCIM settings as the bearer token. tokenHintis the token's last four characters. It is stored on the credential row astoken_hint, so the credentials list shows which bearer a row is; it is not a secret on its own. Credentials minted before the hint existed show none, and none can be added: the token is not stored.- While SCIM is off the mint is refused
503 SERVICE_UNAVAILABLE: a credential nothing can verify is not issued.
POST /api/v1/auth/admin/scim/revoke-credential with { "credentialId": "…" }
switches that credential off: the identity provider's next SCIM request with it
is refused 401. An unknown credential answers 404 RESOURCE_NOT_FOUND, one
already revoked 409 RESOURCE_CONFLICT. Revocation works whether or not SCIM is
on. To rotate, mint a second credential for the same connectionId, move
the identity provider to it, then revoke the old one; both authenticate until
you do. Each credential's last_used_at records when it last authenticated a
SCIM request (at most once a minute; a refused request records nothing), and
its token_hint tells the two rows apart: the old one is safe to revoke once
its last_used_at stops advancing while the new one's does. Each mint and each revoke writes one sys_audit_log row naming the
administrator and the connection, never the credential.
A credential records the administrator who minted it (user_id). A completed
password reset of that administrator's account, whether self-service, an
administrator's forced reset with revokeSessionsAndKeys on, or
os user set-password, revokes every credential the account minted that is
still active, as this revoke does, and writes the same sys_audit_log row for
each, naming the account for a self-service reset and the administrator for a
forced one (os user set-password writes none) (What a password reset ends,
and what a change keeps). A ban,
a deactivation or a removal of that administrator's account revokes them the
same way (What a ban, a deactivation or a removal ends).
Provisioning through the connection waits until a platform administrator mints
a new credential; another administrator's credential for the same connection
keeps working, so a connection with two credentials is not paused.
When the identity provider deactivates a user
A SCIM active: false, or a SCIM DELETE /Users/{id}, disables the account
with a ban that the platform records as the identity provider's. A password
sign-in (POST /api/v1/auth/sign-in/email) by that account is refused 403
like any banned account's, with one field added:
{
"code": "BANNED_USER",
"message": "You have been banned from this application. Please contact support if you believe this is an error.",
"details": { "cause": "scim_deactivated" }
}- An administrator's ban answers the same
403 BANNED_USERwith nodetails. Branch oncodeanddetails.cause, never onmessage: the message is the same for both, and the wording a person reads is the client's to choose. scim_deactivatedmarks exactly the bans the identity provider lifts when it sendsactive: trueagain. An administrator's ban that a deactivation arrived on top of keeps the administrator's reason, and answers as an administrator's ban. A ban whose reason readsDeactivated via SCIM, the reason the directory's ban records, is the directory's whoever wrote it: the directory's next active write lifts it and removes the user's local password.- A deactivation, or a
DELETE /Users/{id}, also revokes every API key the user owns (revoked_reason: scim_deactivated). A re-activation re-arms none of them, and no one can restore them: the owner's Restore and a platform administrator's are both refused403 PERMISSION_DENIED. The person creates a new key under Account → Developer → API Keys and replaces the old one wherever it is configured. - It also suspends every AI service account the user is accountable for, with
the reason that the directory deactivated its owner. Nothing is revoked: the
account's keys are refused while it is suspended. A re-activation does not
resume it, and
resumerefuses while the owner is still deactivated; once the owner is re-activated, or a new owner is named, an administrator resumes it (see AI service account). - It also disables every OAuth application the user registered and revokes
every SCIM credential the user minted, recorded against the connection; a
re-activation restores none of them, and a credential it revoked is reported
once in the server log at
error(What a ban, a deactivation or a removal ends). - It also removes the user's local password. So does a connection
decommission that leaves the user with no active source: that is a
deactivation too. With the password gone the user reads as
directory-managed (
sys_user.sourceisidp_provisioned), so the rules for IdP-provisioned users apply, the SSO-only mode refusals included. A re-activation by the identity provider restores access through its sign-in only: theactive: truethat lifts the deactivation removes any local password the user holds at that moment, one set while the user was deactivated included, so a re-activation restores no credential from before it. If that removal cannot be completed, the re-activation fails and the user stays deactivated until the identity provider retries. The user holds a local password again only once one is set on purpose after the re-activation. No migration or backfill runs: a user deactivated before this rule shipped keeps their local credential until the directory next writes that user. An administrator's unban removes nothing. - The cause is told only after the password verified: a wrong password is the
ordinary
401 INVALID_EMAIL_OR_PASSWORD, whatever the account's state. It names no connection, provider or other account. - It is added on
/sign-in/emailonly; other sign-in methods answer the plainBANNED_USER.
A connection's groups grant permission sets through the same group mappings an SSO provider's sign-in uses; see Grant permission sets from IdP groups.
Client Integration
Using @objectstack/client
The official ObjectStack client has built-in auth methods:
import { ObjectStackClient } from '@objectstack/client';
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000'
});
// Register
await client.auth.register({
email: 'user@example.com',
password: 'password123',
name: 'John Doe'
});
// Login (auto-sets token)
await client.auth.login({
type: 'email',
email: 'user@example.com',
password: 'password123'
});
// Now all subsequent requests include the auth token
const tasks = await client.data.find('task', {});
// Logout (clears token)
await client.auth.logout();
// Get current user
const session = await client.auth.me();
// Refresh token
await client.auth.refreshToken('refresh-token-value');Direct API Calls
All endpoints are available at /api/v1/auth/*:
// Example: Login
const response = await fetch('http://localhost:3000/api/v1/auth/sign-in/email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com',
password: 'password123'
})
});
const data = await response.json();
// better-auth returns the bearer token at the top level of a direct
// `/sign-in/email` response (the client SDK re-wraps it under `data`).
const token = data.token;
// Use token in subsequent requests
const protectedResponse = await fetch('http://localhost:3000/api/v1/data/task', {
headers: {
'Authorization': `Bearer ${token}`
}
});API Reference
Authentication Endpoints
All endpoints are available under /api/v1/auth/*:
Email/Password
POST /api/v1/auth/sign-in/email- Sign in with email and passwordPOST /api/v1/auth/sign-up/email- Register new userPOST /api/v1/auth/sign-out- Sign out current user
Session
GET /api/v1/auth/get-session- Get current user sessionGET /api/v1/auth/bootstrap-status- Public, unauthenticated first-run probe:{ "hasOwner": boolean }, telling a client whether the admission gate's bootstrap window is still open — i.e. whether this system has no human user yet (details)
Password Management
POST /api/v1/auth/request-password-reset- Request password reset emailPOST /api/v1/auth/reset-password- Reset password with tokenPOST /api/v1/auth/set-initial-password- Set a first local password for a signed-in user who has no credential yet (SSO-onboarded accounts). Session required; refuses when a password already exists (details)
Email Verification
POST /api/v1/auth/send-verification-email- Send verification emailGET /api/v1/auth/verify-email- Verify email with token
OAuth
POST /api/v1/auth/sign-in/social- Start OAuth flow (body{ provider, callbackURL }; returns a redirect URL)GET /api/v1/auth/callback/[provider]- OAuth callback handler
Two-Factor Authentication
POST /api/v1/auth/two-factor/enable- Start 2FA enrollment for the current userPOST /api/v1/auth/two-factor/verify-totp- Verify a TOTP code
Magic Links
POST /api/v1/auth/sign-in/magic-link- Send magic link emailGET /api/v1/auth/magic-link/verify- Verify magic link
Phone Number (requires plugins.phoneNumber)
POST /api/v1/auth/sign-in/phone-number- Sign in with phone + passwordPOST /api/v1/auth/phone-number/send-otp- Send a sign-in/verification OTP (requires an SMS service; rate-limited)POST /api/v1/auth/phone-number/verify- Verify an OTPPOST /api/v1/auth/phone-number/request-password-reset- Request an OTP-based password reset (requires an SMS service)POST /api/v1/auth/phone-number/reset-password- Complete an OTP-based password reset
Admin User Management (platform-admin gated)
POST /api/v1/auth/admin/create-user- Create a login-capable account (optional one-time temporary password + forced change)POST /api/v1/auth/admin/set-user-password- Set/reset a user's password (also provisions a credential for SSO-onboarded users)POST /api/v1/auth/admin/import-users- Bulk import users (CSV/JSON/XLSX;auto(default, per-row invite-or-temporary) /invite/temporary/nonepassword policy; ≤500 rows, dry-run supported)POST /api/v1/auth/admin/unlock-user- Clear a brute-force lockout earlyPOST /api/v1/auth/admin/ban-user- Ban a user (blocks sign-in and revokes live sessions; the user's API keys are refused at every door while the ban holds; their OAuth access tokens are refused at the MCP endpoint and read as not valid at/oauth2/userinfoand/oauth2/introspect, and the token endpoint issues them no new token; a ban with an expiry stops binding once it expires. Neither the keys nor the OAuth tokens are revoked. It also suspends every AI service account the user is accountable for, disables every OAuth application the user registered and revokes every SCIM credential the user minted, answering the counts underdata.revoked; see What a ban, a deactivation or a removal ends)POST /api/v1/auth/admin/unban-user- Lift a ban, restoring the account's ability to sign in and its API keys (each key is still judged by its own lifecycle: a key left unused past the inactivity window during the ban answers as inactive, and needs replacing). It resumes no AI service account, enables no OAuth application and restores no SCIM credential the ban endedPOST /api/v1/auth/admin/add-sso-user- Add one pending person who signs in only through the hosting organisation's identity provider (cloud-managed environments only)POST /api/v1/auth/admin/import-sso-users- Add pending people from a CSV or JSON rows (cloud-managed environments only; ≤500 rows, per-row results)
create-user and import-users need plugins.admin (without it they answer 501 NOT_IMPLEMENTED). set-user-password, unlock-user, ban-user, unban-user, add-sso-user and import-sso-users answer with or without it.
Organization Membership (requires plugins.organization; platform-admin gated)
POST /api/v1/auth/organization/add-member- Attach an existing account to an organization with no invitation (details). An ObjectStack mount, not a better-auth route, and the only path that reaches this on a walled deployment.
For complete API documentation, see the Better-Auth API Reference.
Best Practices
Security
-
Use Strong Secrets: Generate a strong random secret for
OS_AUTH_SECRET(minimum 32 characters)# Generate a secure secret openssl rand -base64 32 -
HTTPS in Production: Always use HTTPS for authentication endpoints in production
new AuthPlugin({ baseUrl: process.env.NODE_ENV === 'production' ? 'https://api.example.com' : 'http://localhost:3000', }) -
Environment Variables: Never commit secrets to version control
# .env (not committed) OS_AUTH_SECRET=your-secret-here GOOGLE_CLIENT_ID=your-client-id -
Session Expiry: Configure appropriate session expiry times
new AuthPlugin({ secret: process.env.OS_AUTH_SECRET, baseUrl: 'http://localhost:3000', session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24, // Update every 24 hours } })
User Experience
- Email Verification: Require email verification for sensitive operations
- Password Requirements: Enforce strong password policies
- 2FA for Admin: Require 2FA only after your UI supports the full TOTP challenge and recovery flow
- OAuth Options: Provide multiple OAuth providers for convenience
Error Handling
try {
await client.auth.login({
type: 'email',
email: 'user@example.com',
password: 'wrong-password'
});
} catch (error) {
if (error.response?.status === 401) {
console.error('Invalid credentials');
} else {
console.error('Login failed:', error.message);
}
}ObjectStack Field Naming
The plugin uses ObjectStack's sys_ prefix convention for protocol object names and snake_case for field names, which is required by the ObjectStack protocol:
- Object names:
sys_user,sys_session,sys_account,sys_verification(protocol names) - Field names:
email_verified,created_at,user_id(snake_case)
better-auth internally uses camelCase model and field names (user, emailVerified, userId).
The plugin bridges this gap using better-auth's official modelName / fields schema customisation API:
// Declared in the betterAuth() config via AUTH_*_CONFIG constants:
user: { modelName: 'sys_user', fields: { emailVerified: 'email_verified', … } },
session: { modelName: 'sys_session', fields: { userId: 'user_id', expiresAt: 'expires_at', … } },
account: { modelName: 'sys_account', fields: { providerId: 'provider_id', issuer: 'issuer', accountId: 'account_id', … } },
verification: { modelName: 'sys_verification', fields: { expiresAt: 'expires_at', … } },better-auth 1.7 identifies an account by (issuer, accountId). issuer names the authority
that vouched for the id: an OIDC iss for federated logins, or a synthetic local:credential /
local:oauth:<providerId> for providers that carry none. Rows written before 1.7 have no issuer,
so the auth plugin stamps them once at boot; accounts from a federated IdP that is no longer
registered cannot be derived and are reported in the boot log instead of guessed.
The account id field's NAME changed twice inside the 1.7 line, so read it off the version you
run rather than off an older note. The 1.7.0-rc.2 pre-release renamed accountId →
providerAccountId; the stable 1.7.0 / 1.7.1 releases renamed it back to accountId,
keeping the new issuer. The account_id column is the same throughout — only the camelCase
key moved. On stable 1.7 the mapping above, and any internalAdapter.createAccount({ …, accountId }) call, must use accountId; the rc.2 spelling leaves the field unmapped and every
sign-up answers 500 Unknown field 'accountId' on object 'sys_account'.
The ObjectQL adapter factory (createObjectQLAdapterFactory) then uses better-auth's createAdapterFactory
which automatically transforms all data and where-clauses using these mappings — no manual
camelCase ↔ snake_case conversion is needed in the adapter.
Upgrade note: If you have custom adapters or plugins that reference auth objects by name, update them to use
sys_user,sys_session,sys_account,sys_verification(or import fromSystemObjectNameconstants).
MSW/Mock Mode
AuthPlugin is designed to work in both server and MSW/mock (browser-only) environments. This means you can develop and test authentication flows without running a real HTTP server.
How It Works
- Server mode (HonoServerPlugin active): AuthPlugin registers HTTP routes at
/api/v1/auth/*and forwards all requests to better-auth. - MSW/mock mode (no HTTP server): AuthPlugin gracefully skips route registration but still registers the
authservice. The dispatcher's/authdomain then bridges straight to that service'shandleRequest()— it has no mock fallback of its own, and answers501when theauthslot is empty (see below).
Minimal Configuration for Mock Mode
import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime';
import { ObjectQLPlugin } from '@objectstack/objectql';
import { InMemoryDriver } from '@objectstack/driver-memory';
import { AuthPlugin } from '@objectstack/plugin-auth';
const kernel = new ObjectKernel();
await kernel.use(new ObjectQLPlugin());
await kernel.use(new DriverPlugin(new InMemoryDriver(), 'memory'));
// AuthPlugin works without HonoServerPlugin — no HTTP server needed
await kernel.use(new AuthPlugin({
secret: 'INSECURE_DEV_ONLY_mock_secret_do_not_use_in_production',
baseUrl: 'http://localhost:5173',
}));
await kernel.bootstrap();⚠️ Warning: The secret above is for local development only. In production, always use a strong random secret from an environment variable (
process.env.OS_AUTH_SECRET).
No auth service? /auth/* answers 501 — it never fabricates a session
The dispatcher used to carry a mock fallback: with no auth service in the slot, sign-up/email, register, sign-in/email, login, get-session and sign-out all answered 200 with a made-up user and a 24-hour mock_token_* session — for any email and any password, which was never read.
That is removed (#4113). An unserved auth slot now answers:
501 Auth service not available — register @objectstack/plugin-auth to enable authenticationIt was never an authentication bypass — no session store backed that token, so the identity path still resolved anonymous and anonymous data access was still denied. The problem was that it told the client it had authenticated someone when it had not, while discovery simultaneously reported auth: unavailable and advertised no routes.auth. A capability the runtime does not have must not be advertised by pretending to serve it (ADR-0076 D12, ADR-0115).
A service registered in the slot but not implementing handleRequest from the IAuthService contract takes the same 501.
If you were relying on the mock for a browser-only or MSW build: mock at the HTTP client layer, or with an MSW handler in your own test setup, which is what the console does. Load AuthPlugin (it needs no HTTP server — see above) and the real service answers instead.
Next Steps
- See Security Guide for authorization and permissions
- See Client SDK Guide for client-side integration
- See API Reference for complete API documentation
- Visit Better-Auth Documentation for advanced features
Examples
Complete working examples are available in the repository: