@authtempo/compat-better-auth
v0.2.0
Published
Run an app written for Better Auth 1.7 on authtempo. The app keeps its code and its tables. A package alias points the Better Auth package names at this package.
Keywords
Readme
@authtempo/compat-better-auth
Run an app written for Better Auth 1.7 on authtempo. The app keeps its code and its tables. A package alias points the Better Auth package names at this package.
Supported Better Auth versions: >=1.7.7 <1.8.0.
The range starts at 1.7.7 because of the advisory GHSA-965c-763c-88jm. Better
Auth >=1.4.0-beta.18 <1.7.7 accepts the state of an OAuth sign-in as a magic
link, so an attacker can sign in as another user. The Better Auth system stays the
rollback target during the move, so the rollback system must run 1.7.7 or
later. The shim was read on the shapes of Better Auth 1.7.2 and on the API
key plugin of 1.7.5.
The range is BETTER_AUTH_RANGE, and inRange(version, range) reads it. A
new Better Auth minor gets a compat change in an authtempo minor. The range
never changes in a patch.
The alias
pnpm and npm, in the app's package.json:
{
"dependencies": {
"better-auth": "npm:@authtempo/[email protected]",
"@better-auth/drizzle-adapter": "npm:@authtempo/[email protected]",
"@better-auth/expo": "npm:@authtempo/[email protected]",
"@better-auth/passkey": "npm:@authtempo/[email protected]",
"@better-auth/api-key": "npm:@authtempo/[email protected]",
"@better-auth/sso": "npm:@authtempo/[email protected]",
"@better-auth/scim": "npm:@authtempo/[email protected]",
"@authtempo/core": "0.1.0",
"@authtempo/client": "0.1.0",
"@authtempo/handoff": "0.1.0",
"@authtempo/adapter-d1": "0.1.0",
"@authtempo/adapter-postgres": "0.1.0"
}
}yarn (classic and berry) reads the same npm: form. Both adapters are
required peers, also in an app that uses one database: the server entry
loads both. Neither has a runtime dependency.
Map only the names the app imports. A Better Auth package with no alias, for
example @better-auth/stripe, stays the real package, and betterAuth
refuses its plugin by id at construction.
| Import in the app | Answered by |
| --- | --- |
| better-auth | . |
| better-auth/plugins | ./plugins |
| better-auth/plugins/access | ./plugins/access (createAccessControl, role) |
| better-auth/plugins/organization/access | ./plugins/organization/access (defaultStatements, defaultAc, ownerAc, adminAc, memberAc, defaultRoles) |
| better-auth/react | ./react |
| better-auth/client | ./client |
| better-auth/client/plugins | ./client/plugins |
| better-auth/adapters/drizzle, @better-auth/drizzle-adapter | ./adapters/drizzle and . |
| better-auth/node | ./node |
| better-auth/api | ./api (APIError) |
| better-auth/next-js | ./next-js |
| @better-auth/expo | . (expo) |
| @better-auth/expo/client | ./client (expoClient) |
| @better-auth/passkey | . (passkey) |
| @better-auth/passkey/client | ./client (passkeyClient) |
| @better-auth/api-key | ./api-key (apiKey, plan 12k) |
| @better-auth/api-key/client | ./api-key/client (apiKeyClient, plan 12k) |
| @better-auth/sso | . (sso, plan 12d) |
| @better-auth/sso/client | ./client (ssoClient, plan 12d) |
| @better-auth/scim | . (scim, plan 12d) |
better-auth/api maps to ./api, which exports APIError only (plan 9b).
An import of another name from it, such as createAuthMiddleware, fails at
build: core has no request hooks (plan 9d). Wrap the handler instead (see
"Request hooks").
The package exports no other subpath. An import of better-auth/db or
better-auth/types fails at build. consumerc imports better-auth/db and
consumerb imports better-auth/types: remove those imports first.
Passwords from Better Auth
betterAuthPasswordHash verifies a Better Auth scrypt hash and rewrites it as
PBKDF2 on the first right sign-in. A legacy row verifies slower than a PBKDF2
row until that sign-in rehashes it. So during the migration window the
response time shows which accounts are not yet migrated. Each account loses
this tell at its first right sign-in.
At most two legacy derives run at once per isolate, also when the app chains
@authtempo/legacy-hashes before this seam: both use core's deriveGate.
The others wait, and no sign-in is refused.
requireEmailVerification: true maps to core's password.requireVerified
(plan 12b). A sign-up opens no session and answers { token: null, user }.
api.signUpEmail answers a taken address with the same shape and a new
synthetic user, as Better Auth does. The handler route and the client still
answer USER_ALREADY_EXISTS (409) for it. A right password of an unverified
address answers
EMAIL_NOT_VERIFIED (403). Core mails a new verify link at each unverified
sign-in, at most 3 per 15 minutes, also when sendOnSignIn is absent. An app
that leaves sendOnSignIn out now gets that mail, where Better Auth sends
none.
Storage: in place on the Better Auth tables
drizzleAdapter(db, { provider: "pg", schema }) and
betterAuthSchemaStorage({ dialect: "postgres", sql }) answer core's storage
port and the owned limiter over the app's existing Better Auth 1.7 tables.
Postgres needs a postgres.js client; with Drizzle that is
drizzle-orm/postgres-js. Other drivers are refused.
Run the migration once per deploy, before the first request:
await betterAuthSchemaStorage({ dialect: "postgres", sql }).migrate();migrations/postgres/ holds the text of each step that migrate() runs on Postgres, for the default table names. It is the record of each shipped step: read it before a migration, and do not run it by hand.
What the migration does (0001_compat_better_auth, append-only):
- It adds two tables,
ta_metaandta_limit, and no other table. A schema that already holds core's ownta_metaandta_limit(from@authtempo/adapter-postgresmigrations) makesmigrate()stop withrelation "ta_limit" already exists, and the migration changes nothing. Run the compat storage on a schema without core's tables. - It adds nullable
tacolumns for core fields with no Better Auth column:session.taLastSeenAt,account.taLinkedAt,verification.taPurpose,taValueHash,taConsumedAt,taData,passkey.taUpdatedAt,organization.taUpdatedAt,member.taUpdatedAt,invitation.taTokenHash,taAcceptedAt,taUpdatedAt. - It fills the date columns
session.taLastSeenAt,account.taLinkedAt, and the fourtaUpdatedAtcolumns for existing rows from the nearest Better Auth date (session.updatedAt, elsecreatedAt), cut to milliseconds. On Postgres these columns also get the defaultdate_trunc('milliseconds', now()), so a row that another writer adds later (an old replica during the deploy, the app's own SQL) has a value. Without a value core cannot read the row. The milliseconds matter: core reads dates with millisecond precision, and the organization owner guard compares the read value for equality. - The other
tacolumns stay null on rows that authtempo did not write. Core reads only verification rows with ataPurposeand invitations with ataTokenHash. - It adds the unique keys core needs:
verification (taValueHash),passkey (credentialID),member (organizationId, userId),invitation (taTokenHash), andaccount (issuer, accountId)when the table has no unique index on these two columns under any name (Better Auth 1.7 hasaccount_issuer_accountId_uidx). account.issueron both dialects: on Postgres it adds the column when it is missing (a table from before Better Auth 1.7, such as consumer-i's) and fills every row that has none fromproviderId. On D1 a static file cannot test for a column, so two files ship:migrations/d1/for 1.7 tables (it fills only) andmigrations/d1-before-1.7/(it adds the column and the unique index, then fills). Copy the one that fits the tables, as the D1 steps below say.- It stops with "every Better Auth date column must be timestamptz" when a date column has no time zone.
- It needs every table in the list, also when the plugin is off:
user,session,account,verification,organization,member,invitation,passkey. Create a missing table with Better Auth's own SQL for it. Core's claim rule deletes passkey rows on every app, and the sweep deletes invitations.
Migration 0002_compat_schema_v5 (plan 8b) moves schema_version to 5 and compat_better_auth to 2. It changes no table: core 5 adds API tokens, and this package does not hold them until its api-key plan. Core's routes under /tokens answer 404 here. tempo.api.tokens.* is not usable on this storage: create throws unknown_model, and the reads answer empty. migrate() runs both migrations. On D1, copy 0002_compat_schema_v5.sql after the 0001 file, for both variants and every naming: it touches ta_meta only. Without it the storage refuses to start with schema_mismatch.
Plan 12k: core's token routes work in the shim. Migration 0010 creates core's own ta_api_token, ta_organization_token, and ta_moved_token, the record of each moved key. So /tokens, /organizations/tokens, and tempo.api.tokens.* act on this storage (see "API keys").
What changes at cutover:
The
session.tokencolumn holds the SHA-256 hex of the token, never the raw token. Better Auth-era sessions end: every person signs in again once. App SQL that readssession.tokenreads a hash.Better Auth-era verification rows and invitations stay in the table and core never reads them. Send pending invitations again.
Users, Google, Apple, GitHub, LinkedIn, TikTok, WeChat, Microsoft, Discord, GitLab, X (
twitter), and Facebook accounts, credential passwords, organizations, members, and passkeys carry over. A password rehashes to PBKDF2 at its first sign-in.The
ta_metaandta_limittables go in the first schema of the search path, also when the Better Auth tables sit in another schema.A passkey counter above 2147483647 fails: Better Auth's
countercolumn isinteger.The session cookie is
__Host-tempo_session, notbetter-auth.session_token. Until 0.2.0 the shim also readtempo_session, the name of plan 9, and moved it to the new name. The shim reads the old name no more, so a browser that holds only the old cookie signs in again. App code, tests, and legal pages that name the old cookie must change. For example, consumer-i's site lists__Secure-better-auth.session_tokenin its cookie text (apps/site/test/legal.test.ts).socialProviders.microsoft(clientId,clientSecret,tenantId, defaultcommon),discord,gitlab(withissuer),twitter, andfacebookmap to core's presets (plan 12i Task 16). Each preset keeps the subject that Better Auth stored asaccountId, so the rows link on the first sign-in. Every other key of these providers is refused.Core trusts fewer provider addresses than Better Auth. A Microsoft address is verified only with the
xms_edov: trueclaim, and Better Auth also countsemail_verifiedand theverified_*_emaillists. A GitLab address is never verified in core, and Better Auth countsemail_verified. Take a person whose account has a password, at a first Microsoft or GitLab sign-in. Better Auth links by the address, and core answersemail_taken_unverified. Rows that Better Auth linked before keep linking by subject.Better Auth-era
accountrows of providers that the package does not map stay in the table. Core reads them as identities of their users, so a claim of the address deletes them as it deletes any identity other than the proving one. The factory refuses such a provider insocialProviders, and the reason depends on the provider id:slack: refused. Core's Slack subject is<team_id>:<user_id>, and a Better Auth Slack row holds the user id alone (ruling 22 of plan 12i). The row would not link at the first sign-in, and the person would get a second account, oremail_takenfor a verified address. Before you use core'ssocial.slackthrough core'screateAuth, rewrite each SlackaccountIdto<team_id>:<user_id>. The refusal text starts withnot mapped: core's Slack subject is team_id:user_id.- Any other id:
not mapped; add it through core's social.oidc or social.oauth2. On core'screateAuth, a list entry whosenameis the Better Auth provider id and whose subject is the id that Better Auth stored asaccountIdlinks these rows on the first sign-in.
A compat app that needs such a provider uses core's
createAuth, becausebetterAuth()takes no preset or list entry outside the ones it maps.The callback stays Better Auth's:
<baseURL><basePath>/callback/<provider>. On an httpsbaseURL, the shim gives each provider that URI as core'sredirectURIoverride (plan 12i Task 16), so nothing changes at the provider. A provider's ownredirectURIoption wins, and core checks that it has the origin ofbaseURL. Core takes an override on https only: on an httpbaseURL(local work), register<baseURL><basePath>/social/<provider>/callback.GitHub and LinkedIn accounts link on the first sign-in by the id Better Auth stored: the numeric GitHub id, and LinkedIn's OpenID
sub. LinkedIn'ssubstays the same only while the client id stays the same.socialProviders.tiktok(clientKey,clientSecret) andsocialProviders.wechat(clientId,clientSecret) map to core'stiktokEntryandwechatEntry(plan 12i Task 22). Their accounts link by the id Better Auth stored: the TikTokopen_id, and the WeChatunionid, elseopenid. The two entries have no address, so core keeps the placeholder address of a Better Auth-era user unverified and never links by it. WeChat'slangandplatformTypeare refused. The TikTok callback stays Better Auth's (see above), and the API host stays the WeChat callback domain. The storage reads Better Auth's TikTok and WeChat placeholders (<id>@tiktok.placeholder.invalid) as no address, so they never count as proved (see "Sign-in plugins").A credential row (
providerIdcredential) with a nullaccount.passwordanswersschema_mismatch, so sign-in and reset for that address answer 500. Better Auth 1.7.2 never writes that row. Give the row a hash or delete it before cutover. A plan 9b input.
On D1, drizzleAdapter(db, { provider: "sqlite" }) needs drizzle-orm/d1, and
betterAuthSchemaStorage({ dialect: "d1", db: env.DB }) takes the binding.
The one D1 step: copy the compat file into the app's migrations_dir, and
rename it to the app's next migration number, for example
0007_compat_better_auth.sql after 0006_.... Then run
wrangler d1 migrations apply. wrangler applies the files in name order. A
number lower than the Better Auth table migration makes every new database
(CI, a preview database, --local) fail at the compat file with
no such table.
- Better Auth 1.7 tables: copy
node_modules/@authtempo/compat-better-auth/migrations/d1/0001_compat_better_auth.sql. - Tables from before Better Auth 1.7 (no
account.issuercolumn): copy the file of the same name frommigrations/d1-before-1.7/. - Every app: then copy each later file of the same directory (
0002_compat_schema_v5.sqlto0015_compat_schema_v18.sql), in order, and give each the next number. - Tables with other names: write the 0001 file from
storage.migrationSql()orstorage.migrationSql("before-1.7"). Write the 0006 file fromcompatMigration0006Sql("sqlite", storage.names), not from the shipped file. The shipped 0006 addstaSecretVersionto Better Auth's defaultverificationtable, so on other names it fails withno such table. Write the 0007 file fromcompatMigration0007Sql("sqlite", storage.names)for the same reason: the shipped 0007 addstaFreshAtto the defaultsessiontable. Write the 0009 file fromcompatMigration0009Sql("sqlite", storage.names)for the same reason. The shipped 0009 adds the ban columns to the defaultusertable andtaActorIdto the defaultsessiontable. Write the 0010 file fromcompatMigration0010Sql("sqlite", storage.names)for the same reason, or fromcompatMigration0010Sql("sqlite", storage.names, "before-1.7")for tables from before 1.7. The shipped 0010 addsactiveTeamIdto the defaultsessiontable andteamIdto the defaultinvitationtable. Write the 0012 file fromcompatMigration0012Sql("sqlite", storage.names)for the same reason. The shipped 0012 adds the plugin columns to the defaultusertable and the flags to the defaultpasskeytable. Write the 0013 file fromcompatMigration0013Sql("sqlite", storage.names)for the same reason. The shipped 0013 addstaProvedto the defaultsessiontable and reads the defaultusertable. - Tables that hold
session.activeTeamIdandinvitation.teamIdalready: Better Auth'steamsoption adds these two columns. SQLite has noADD COLUMN IF NOT EXISTS, so the shipped 0010 fails on these tables withduplicate column name: activeTeamId. Such an app writes its own 0010 file. It is the shipped file of its directory (d1ord1-before-1.7) without its twoALTER TABLE ... ADD COLUMNlines ofsessionandinvitation. The other lines must stay. They create theorganizationRole,team, andteamMembertables when they are absent. They addtaRank, thetacolumns, and the unique keys, and move the versions. It applies the files to 0009, its own 0010, and the shipped 0011 to 0015 withwrangler d1 migrations applybeforeauthtempo migrate --target d1 --tables compat. Then the compat version is 15, and the command copies nothing. - Tables that hold the columns of Better Auth's username, phone number, or anonymous plugin: the shipped 0012 adds these columns too, so on such tables it fails with
duplicate column name. Such an app writes its own 0012 file without theADD COLUMNline of each column that the table holds, and without the unique key that it holds.
wrangler d1 migrations apply rolls back a file that fails (wrangler
4.148.0, read 2026-10-10), so a refused file changes nothing. A runner that
does not roll back, such as wrangler d1 execute --file, can keep the empty
ta_date_check table of a refused date check. The next run uses that table
and drops it. The errors that a refused file gives:
no such column: issuer: the 1.7 file on tables from before 1.7. Use thed1-before-1.7file.duplicate column name: issuer: thed1-before-1.7file on 1.7 tables. Use thed1file.table ta_limit already exists: the compat migration ran already.duplicate column name: activeTeamId: the shipped 0010 on tables that hold the teams columns already. Use an own 0010 file: the shipped file without its twoADD COLUMNlines ofsessionandinvitation.duplicate column name: memberCount: thed1-before-1.70010 on the team tables of Better Auth 1.7. Use thed1file.UNIQUE constraint failed: organizationRole.organizationId, organizationRole.role(Postgres:could not create unique index "ux_organization_role__organization_id__role"): two role rows of one name in one organization. Better Auth checks the name before a create but has no unique key. Find them withSELECT "organizationId", role, count(*) FROM "organizationRole" GROUP BY "organizationId", role HAVING count(*) > 1. Delete or rename one row of each pair, and run the file again.UNIQUE constraint failed: teamMember.teamId, teamMember.userId(Postgres:could not create unique index "ux_team_member__team_id__user_id"): two team member rows of one pair. Better Auth 1.7 stops such rows with itsmembershipKey, but a row from before 1.7 has no key. Find them withSELECT "teamId", "userId", count(*) FROM "teamMember" GROUP BY "teamId", "userId" HAVING count(*) > 1. Delete one row of each pair, and run the file again.CHECK constraint failed: tempo_auth_compat_every_better_auth_date_must_be_text: a Better Auth date column holds a number (a Drizzleinteger({ mode: "timestamp" })schema) or text that is not a date. authtempo on D1 reads dates as ISO 8601 text only.
Dates are ISO 8601 text and booleans are 1 and 0, as Better Auth's Kysely
adapter writes them. The migration fills the added dates as ISO text with
milliseconds, also from SQLite's YYYY-MM-DD HH:MM:SS form. SQLite gives an
added column no computed default, so when another writer adds a row later,
the storage reads createdAt (updatedAt for a session) in place of the
added date. drizzleAdapter refuses a Drizzle SQLite schema with integer
timestamp columns. The storage also refuses every call with schema_mismatch
while account has no unique index on (issuer, accountId): the 1.7 file uses
Better Auth's own index and adds none.
A Better Auth date in SQLite's YYYY-MM-DD HH:MM:SS form has no time zone.
The storage reads it as UTC, as SQLite's date functions do, on Workers and
off them (plan 9b2). A where clause and a sort still compare the stored text,
so a row in that form sorts before an ISO row of the same second. A date text
that is not a date answers schema_mismatch. The storage does not match the
YYYY-MM-DD HH:MM form with no seconds. SQLite's CURRENT_TIMESTAMP never
writes it, but SQL written by hand can. JavaScript reads that text as local
time: on Workers, whose time zone is UTC, the read is correct; in a process
with another time zone it is wrong by the zone offset (probe with Node and
TZ=Pacific/Auckland, 2026-10-12). Write each date with its seconds.
A credential account row with a null password (Better Auth never writes
one) reads as no password row: the sign-in answers invalid_credentials
after the dummy verify, a reset writes a real hash, and the storage logs one
line, authtempo compat: a credential account row has no password; it reads
as no password row (account <id>).
On D1, do not delete a user or an organization inside a transaction of
your own while its child rows exist: the foreign keys delete them, and a
rollback does not bring them back (@authtempo/adapter-d1 README).
On SQLite, the storage turns the foreign keys on before its first call and
before its migrations, on every driver. So a user delete deletes the user's
child rows. bun:sqlite of Bun 1.4.3 opens with the keys off (read on
2026-11-03). The storage then reads the key back, and each call answers
config_mismatch while it reads 0. SQLite ignores the pragma inside an open
transaction, so do not hold a BEGIN on the handle at the first call. A
libSQL file client keeps a pool of connections. The storage turns the keys on
only for the connection of its first call. On each other connection, the
default of @libsql/client 0.18.0 keeps the keys on and the cascade with
them (read on 2026-11-03). So do not turn the keys off on that client.
These D1 facts come from the local Workers pool only and are not verified on a real D1 database: D1 refuses TEMP tables, D1 refuses a long compound SELECT, the PRAGMA column names, the rollback of a failed migration file, and the time of the one date scan statement on a large table (it can reach D1's per-query limit). A plan 9b input verifies them on a real D1 database.
What fails at start
betterAuth(options) checks every option against an allow list. One
BetterAuthCompatError lists every option, plugin, and provider that
authtempo cannot keep, so the app fails at start and never at run time. The
error's refusals holds the list. Options that change only speed, such as
session.cookieCache, are accepted and log one line.
Better Auth's defaults apply: a session lives 7 days and refreshes after 1 day, a reset link lives 1 hour, a magic link 5 minutes, an invitation 2 days.
Better Auth defaults that core does not keep:
| Better Auth default | authtempo |
| --- | --- |
| The client IP comes from x-forwarded-for | It comes from cf-connecting-ip. Set advanced.ipAddress.ipAddressHeaders off Workers: off Workers any caller sets cf-connecting-ip, so every per-IP limit can be rotated. toNodeHandler and toNextJsHandler throw BetterAuthCompatError at creation for an instance with neither a non-empty ipAddressHeaders nor disableIpTracking: true. toNodeHandler gives core the request body as a stream, so the cap of each route bounds the bytes that the route reads. A listed header value that is not an IPv4 or IPv6 literal counts as no client IP. For a header with a list of values, such as x-forwarded-for, the shim takes the leftmost value, as Better Auth does. A client can write that value, so list only a header that your proxy sets in full. A request with no client IP (a server call with no headers, or every request under disableIpTracking: true, which logs a note) skips the per-IP limit only for password sign-in, the magic link, the reset request, and the verify mail resend, which keep their per-email limits. Every other flow (sign-up, the reset form, invitation accept, the handoff, passkeys, social start) has only a per-IP limit, so it counts all such requests in one shared bucket. |
| An absolute callbackURL or redirectTo on any trusted origin | Only the origin of authtempo.appURL (default the origin of baseURL, or of the request's entry of a list) keeps its path, because core lands every sign-in there. Any other absolute value answers INVALID_CALLBACK_URL or INVALID_REDIRECT_URL, status 403. |
| A reset keeps the other sessions | A reset ends every session. |
| The verify link lives 1 hour beside a magic link of 5 minutes | Both live as long as the magic link. With the magic link plugin and no emailVerification.expiresIn, the verify link lives 300 s, not 3600 s, and a note says so at start. |
| trustedOrigins takes a function and wildcards such as https://*.example.com | Each entry is an exact origin (https://app.example.com, no path or trailing slash) or an app scheme (myapp://). Any other entry is refused at start. |
| baseURL takes { allowedHosts, fallback, protocol } with wildcard hosts, and protocol: "auto" reads x-forwarded-proto | Each host must be exact, and protocol must be https or http; a wildcard, auto, and no protocol are refused. The hosts map to core's baseURL list, and a fallback equal to one of them is the primary. Core picks the host from the request URL and reads no proxy header. The shim builds its own paths, SSO URLs, and mail links on that host. Each host is also a trusted origin, as in Better Auth, so a page on one host posts to another. A wildcard on a shared platform lets any customer of the platform own a host of the issuer. |
Call arguments that core cannot keep: on the server, api.signUpEmail with
callbackURL or image, and api.signInEmail with callbackURL or
rememberMe: false, throw APIError NOT_SUPPORTED with status 501. Core's
verify link lands on the app origin, and every session lives
session.expiresIn. rememberMe: true is Better Auth's default and is
accepted. The client answers the same NOT_SUPPORTED (501) for callbackURL
on signIn.email and signUp.email and for rememberMe: false, and sends no
request.
Two-factor (plan 9f): the error codes are Better Auth 1.7.2's (INVALID_CODE,
INVALID_BACKUP_CODE, TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE,
INVALID_TWO_FACTOR_COOKIE, TOTP_NOT_ENABLED, TWO_FACTOR_NOT_ENABLED,
INVALID_PASSWORD), with core's status: 400 for a wrong code, where Better
Auth answers 401. A missing or stale better-auth.two_factor cookie answers
INVALID_TWO_FACTOR_COOKIE with 401. A second enable answers
TOTP_ALREADY_ENABLED (409), where Better Auth replaces the secret: disable
first. A challenge lives 5 minutes, where Better Auth's cookie lives 10.
api.signInEmail answers { twoFactorRedirect: true, twoFactorMethods:
["totp"] }; its type says so only when the options name the plugin in a
literal list. The backup codes of a Better Auth user do not move: each user
sets the factor up again on authtempo. A new secret opens no sealed secret,
so every user with the factor on fails the code and the backup codes until the
factor is turned off for them. The setup takes the password at every path:
/two-factor/enable passes it into core's setup, and core's own POST
/totp/setup takes { password } or an email code, so a session alone sets up
no factor. twoFactor({ allowPasswordless: true }) of Better Auth lets a
session alone set up TOTP, so this package refuses it at start. A
wrong password answers INVALID_PASSWORD (400) and writes no row. The limits
that bind are per user, on every code check: 10 per 15 minutes and 30 per 24
hours. A person who has the password or a stolen session can use up that
budget, and the owner's verify, enable, and disable then answer
TOO_MANY_REQUESTS until the window ends, as with Better Auth's lockout.
api.signInEmail reads better-auth.trust_device from headers, so a
trusted device signs in with no challenge. A gated server sign-in keeps no
challenge, because a server caller has no cookie jar: the browser repeats the
sign-in through the handler. Since plan 12c a reset by code of a user with the
factor on answers { success: true } with no cookie, and the next sign-in asks
for the factor: Better Auth's own shape. On a trusted device the reset opens
the session, as the sign-in does. A reset link goes to core's page, which then
shows core's challenge page. The client's
resetPassword({ newPassword, token }) answers { status: true } for a gated
reset and leaves core's challenge live for 5 minutes; only the holder of the
reset link can reach it.
An invitation has two ids. The mail id (data.id in sendInvitationEmail)
accepts the invitation, and the row id (from api.createInvitation) cancels it.
api.sendVerificationEmail and authClient.sendVerificationEmail send a new
verify link through core's resend route (plan 8b). The earlier link of the
address stops working. A callbackURL answers NOT_SUPPORTED (501): core lands
the link on the app origin.
emailVerification.sendOnSignIn: false is refused at start: core sends a new
verify link at each unverified sign-in, at most 3 per 15 minutes. Absent and
true are accepted.
Secrets and sign-up
These rules come from plan 12b.
secrets: [{ version, value }]maps to core'ssecrets, one entry for one entry, the current version first. Givesecret,secrets, or both, as in Better Auth.secrets[i].version0 is refused: core reads a row from before plan 12b as version 1, so renumber from 1. Better Auth accepts version 0.- With
secretandsecrets, version 1 must be the value ofsecret. Another value is refused atsecrets[i].value. Core refuses every other bad entry, and the error names it asconfig: <reason>. - The shim does not read the
BETTER_AUTH_SECRETSenvironment variable: it maps options only. Pass the list assecrets. - Core refuses a weak secret at start, where Better Auth only warns. Each
value needs 32 characters or more. The current value (
secrets[0], orsecretwithoutsecrets) also needs an estimated 100 bits of entropy. Make a new one withopenssl rand -base64 32. An older version needs only the 32 characters, so an old secret of that length can stay as version 1 behind a new current value. emailAndPassword.autoSignIn: falsealone is refused: core opens a session at sign-up unlessrequireEmailVerificationis true. WithrequireEmailVerification: trueit is accepted, because Better Auth then acts as with that key alone: no session at sign-up, and an unverified sign-in is refused.- The sign-up answer is Better Auth's: a session for a new address unless
requireEmailVerificationis true, andUSER_ALREADY_EXISTSfor a taken one. The shim sets core'spassword.uniformSignUp: false, because core's uniform answer has no user for Better Auth's{ token, user }. So a caller can learn that an address has an account, as with Better Auth. Use core'screateAuthfor the uniform answer. - A sign-up of a new address writes rows and sends the verify mail. A taken address does neither, so the answer time can show that the address has an account, as in Better Auth.
- A confirm keeps the sign-up's password only with core's sign-up proof
(plan 12q). The handler sets it as the HttpOnly cookie
__Host-tempo_signupat the sign-up. Without it, the confirm deletes the password, and the person sets a first password with/password/change. So a link that opens in another browser costs the password. api.signUpEmailanswers the proof assignUpProof, a member that Better Auth does not have. A server call has no cookie jar, so the app sets the cookie from it. The answer for a taken address holds a proof of the same form.api.signInEmailandapi.sendVerificationEmailread the cookie fromheaders, so a new verify link keeps the proof.- A compat native app, such as an Expo app, loses the sign-up's password at
the confirm. The compat client keeps no proof, because its sign-up answer
is Better Auth's
{ token, user }. It has no code confirm either. The person then sets a first password with/password/change. disableSignUpis accepted onemailAndPassword,magicLink,emailOTP, and each social provider. Core has one sign-up rule for every method.trueon every configured method and provider that creates a user maps to core'ssignUp: false.trueon some and not on others is refused atdisableSignUp, and the reason names both groups: set it on every method or on none. A provider without the key counts as open.- A provider's
disableImplicitSignUpis refused: core has no sign-up that the caller asks for, so its onesignUprule covers every method. - With
signUp: false,api.signUpEmailthrowsEMAIL_PASSWORD_SIGN_UP_DISABLEDwith 400, Better Auth's code and status. The client'ssignUp.emailanswers the same code with core's status, 403. The other methods answer core'ssign_up_closedasSIGN_UP_CLOSED.
Errors: APIError on the server and error on the client carry Better Auth's
code (body.code, error.code) and core's HTTP status. The table is
BETTER_AUTH_CODES.
The session read
auth.api.getSession and GET /get-session answer { session, user }, or
null with no session (plan 12a). session.deferSessionRefresh: true maps
to core's session.deferRefresh.
- A GET request writes no session row.
GET /get-sessionandapi.getSessionanswerneedsRefreshbeside the session. POST /get-sessionslides the expiry and renews the cookie through core'sPOST /session/refresh.- With the option off,
POST /get-sessionanswersMETHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED(405), as Better Auth 1.7.2 does.
The handler forwards each request to core's own route, so core's rules
apply. The shim's client reads core's GET /session. When the answer holds
needsRefresh: true, the client posts core's POST /session/refresh and
keeps the GET answer if that post fails, as Better Auth's session atom does.
Account operations
Plan 12a serves Better Auth 1.7.2's account operations in Better Auth's
shapes. Each is a method of auth.api and a path of auth.handler.
| Better Auth call | Path | Answer |
| --- | --- | --- |
| listSessions | GET /list-sessions | The live sessions; token holds the session id |
| revokeSession({ token }) | POST /revoke-session | { status: true }, also for an unknown token |
| revokeSessions | POST /revoke-sessions | { status: true }; every session ends, the caller's too |
| revokeOtherSessions | POST /revoke-other-sessions | { status: true } |
| updateUser({ name, image }) | POST /update-user | { status: true } |
| changeEmail({ newEmail, callbackURL }) | POST /change-email | { status: true }, with user.changeEmail.enabled |
| deleteUser({ password }) | POST /delete-user | { success: true, message: "User deleted" }, with user.deleteUser.enabled. With sendDeleteAccountVerification: { success: true, message: "Verification email sent" } |
| deleteUser({ token }) | POST /delete-user | { success: true, message: "User deleted" }: the confirm of the mailed link |
| The mailed link (the handler only) | GET /delete-user/callback | Core's confirm page. It deletes nothing; its button posts the token |
| listUserAccounts | GET /list-accounts | The provider accounts and the credential account |
| linkSocial (the handler only) | POST /link-social | { url, redirect } |
| unlinkAccount({ accountId }) | POST /unlink-account | { status: true } |
The handler posts core's own route for each path, so core's Origin rule,
its fetch-metadata rule, CORS, and the cookie renewals apply. The handler
runs core's Origin and fetch-metadata rules on every POST first, also on the
paths that the shim answers itself. A refused POST answers 403
{ "code": "INVALID_ORIGIN", "message": "Invalid origin" }, as Better Auth's
origin check does. The check runs before the route, so a refused POST to a
path that no route serves answers 403, not 404. auth.api calls core in
process. Both run the same Better Auth checks. A refusal of
such a check changes no row. It carries no CORS header, as on the email
code and second-factor paths. The shim's own client
gains no account calls. A client app posts these paths, or calls
@authtempo/client.
| Difference | Why |
| --- | --- |
| listSessions answers the session id in token. revokeSession takes that id or a clear token | The shim stores the hash of a token, never the token |
| A revoke of the caller's own session through the handler clears the session cookie, as revokeSessions does | Core's rule for a request that ended its own session |
| A revoke, the change of address, the link, the unlink, and the delete need a fresh session. A stale session answers SESSION_NOT_FRESH (403) | ASVS 5.0.0 7.5.1 and 7.5.2. session.freshAge sets the window: default one day, rounded up to whole minutes |
| /two-factor/disable, /two-factor/get-totp-uri, and /two-factor/generate-backup-codes need a fresh session too, checked before the password. A stale session answers SESSION_NOT_FRESH (403) | A password and a stolen session must not turn the factor off. Better Auth asks for the password only |
| listSessions needs no fresh session, where Better Auth asks for one | A person can always view the sessions (ASVS 5.0.0 7.5.2) |
| A core route through the handler, such as POST /password/change, adds code: "SESSION_NOT_FRESH" to core's 403 answer | The caller reads Better Auth's code on every path |
| session.freshAge: 0 is refused | The fresh rule is a promise of core |
| deleteUser({ password }) re-authenticates first. A wrong password answers INVALID_EMAIL_OR_PASSWORD, not INVALID_PASSWORD | Better Auth's password path skips freshAge. Core's re-authentication proves the password, and the code too when the second factor is on |
| GET /delete-user/callback serves core's confirm page and deletes nothing. The page posts the token with the session cookie. url of sendDeleteAccountVerification opens that page on core's path, and request is undefined | A mail scanner fetches links, so a GET that deletes lets it delete the account |
| With sendDeleteAccountVerification, the request needs a fresh session, as the direct delete does. The organization rule runs at the request and again at the confirm | Core keeps every check of the delete. Better Auth mails the link with no check |
| deleteTokenExpiresIn is a whole number of minutes from 300 to 86400 seconds. Else the option is refused | Core keeps the life of the link in whole minutes, from 5 to 1440 |
| A spent, expired, unknown, or foreign token answers INVALID_TOKEN with 400, not 404. A confirm after a change of address answers it too | Core's status. The link went to the old mailbox |
| deleteUser with callbackURL answers NOT_SUPPORTED (501). The confirm page lands on the app | Core lands a form post on appURL |
| An organization where the user is the last owner and other members remain stops the delete: SOLE_OWNER (409) | Better Auth keeps such an organization with no owner |
| A delete answers DELETE_TOO_LARGE (409) before any write when the user alone holds more than 50 organizations. On D1 it also answers it when its least work cannot fit 50 queries | Core deletes the account in one transaction, and D1 Free allows 50 queries per invocation |
| updateUser takes name and image, for a verified address only. email answers EMAIL_CAN_NOT_BE_UPDATED, and any other field FIELD_NOT_ALLOWED | Core keeps no other user field. Better Auth drops an unknown field |
| The change of address mails the new address through emailVerification.sendVerificationEmail. A taken address gets no mail. The link opens core's confirm page | As Better Auth does. Core moves the address only after the proof. sendChangeEmailConfirmation is refused |
| changeEmail with the option off answers CHANGE_EMAIL_DISABLED (400). Core's own /user/change-email routes answer 404 | Better Auth 1.7.2's answer |
| A link needs the provider's verified address, equal to the account's. Else the callback answers email_mismatch. allowDifferentEmails: true and trustedProviders are refused | Better Auth also links an unverified address of a trusted provider, and a different address with allowDifferentEmails. A provider address must not take an account |
| unlinkAccount keeps the last way in: FAILED_TO_UNLINK_LAST_ACCOUNT with 409, where Better Auth answers 400. allowUnlinkingAll: true is refused | The last-credential guard |
| unlinkAccount of the credential account answers NOT_SUPPORTED (501) | Core has no password removal |
| linkSocial takes provider, callbackURL, and disableRedirect. Each other field answers NOT_SUPPORTED (501) | Core starts a redirect link with its own scopes and its own error page |
| Core's credential-change notices are off under the shim: account.notices: false. Use core's createAuth for the notice mails | Better Auth sends no mail after a password, passkey, or second-factor change, and has no callback for one |
| databaseHooks.user and databaseHooks.account map (see "Hooks"). A credential account fires no account hook, and the user delete fires none | Core's password row is not an identity |
| POST /reauth/email answers 404 | Better Auth has no re-authentication code |
The passkey rename of @better-auth/passkey 1.7.2 is a path of
auth.handler and a call of the shim's client: POST
/passkey/update-passkey and passkey.updatePasskey({ id, name }). Both
call core's POST /passkeys/rename and answer { passkey }. The server has
no auth.api.updatePasskey, as it has no other passkey call.
| Difference | Why |
| --- | --- |
| The id of another user's passkey answers PASSKEY_NOT_FOUND (404), as an unknown id does. Better Auth answers 401 YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY | The answer must tell nothing about the passkeys of another user |
| A name has 1 to 64 characters after the trim, with no control or format character except the zero-width joiners. Else VALIDATION_ERROR (400) | Core's passkey name rule. A bidi override must not make one passkey read as another |
| The answer's passkey has no publicKey, counter, transports, or aaguid | Core keeps them out of its answers |
| passkey.addPasskey sends a name that is empty after the trim as no name, so the passkey has the name null. Core also stores a name that breaks its rule as null | Better Auth keeps an empty name. Core never refuses a new credential for its name |
| 30 renames per user in 15 minutes, then TOO_MANY_REQUESTS (429) | Core's limit passkey-rename:user:<userId> |
Client
createAuthClient from better-auth/react or better-auth/client talks to
authtempo's routes under basePath. A hand-written fetch to a Better Auth
path does not work. consumer-i's invite dialog posts to
/organization/invite-member; call authClient.organization.inviteMember
instead.
These are every path that Better Auth 1.7.2 defines in better-auth
(dist/api/routes, the organization and magic link plugins) and in
@better-auth/passkey and @better-auth/expo (read 2026-10-10 from each
createAuthEndpoint call). The handler serves none of them under its Better
Auth request and answer shapes. It answers 404 for each, with two exceptions
that are core's own routes (core http/routes, read 2026-10-10): POST
/sign-out ends the session, as Better Auth's does, and /magic-link/verify is
core's magic link route. With the magicLink plugin, a Better Auth-era link
answers invalid_token. Without the plugin, it answers 404. Since plan 12i
Task 16, two more paths of the list answer. /callback/<provider> is core's
provider callback on an https baseURL, and it answers 404 on http.
/sign-in/social with idToken is core's ID-token sign-in, and it answers
404 without idToken. The handler
serves /get-session, the eleven account paths of plan 12a, and
/passkey/update-passkey in Better Auth's shapes, so they are not in this list. See "The session read" and "Account operations". The email code paths are not in
it either (see "Email codes"), nor the paths of the sign-in plugins (see "Sign-in plugins").
- Core:
/account-info,/callback/:id,/change-password,/error,/get-access-token,/ok,/refresh-token,/request-password-reset,/reset-password,/reset-password/:token,/send-verification-email,/sign-in/email,/sign-in/social,/sign-out,/sign-up/email,/update-session,/verify-email,/verify-password. - Organization:
/organization/accept-invitation,/add-team-member,/cancel-invitation,/check-slug,/create,/create-role,/create-team,/delete,/delete-role,/get-active-member,/get-active-member-role,/get-full-organization,/get-invitation,/get-organization,/get-role,/has-permission,/invite-member,/leave,/list,/list-invitations,/list-members,/list-roles,/list-team-members,/list-teams,/list-user-invitations,/list-user-teams,/reject-invitation,/remove-member,/remove-team,/remove-team-member,/set-active,/set-active-team,/update,/update-member-role,/update-role,/update-team(each under/organization). - Magic link:
/sign-in/magic-link,/magic-link/verify(see above). - Passkey:
/passkey/delete-passkey,/passkey/generate-authenticate-options,/passkey/generate-register-options,/passkey/list-user-passkeys,/passkey/verify-authentication,/passkey/verify-registration. - Expo:
/expo-authorization-proxy.
Results keep Better Auth's { data, error } shape. error.code is Better
Auth's code from BETTER_AUTH_CODES; error.status is authtempo's HTTP
status. A password that core's policy refuses answers PASSWORD_TOO_SHORT
below the server's minPasswordLength, PASSWORD_TOO_LONG over 128, and
INVALID_PASSWORD otherwise. The server's handler names the case, so the
client and api answer the same code.
Since plan 9e the client has Better Auth 1.7.2's email OTP calls, on
core's code routes: emailOtp.sendVerificationOtp({ email, type }) with
sign-in or forget-password (the other types answer NOT_SUPPORTED),
signIn.emailOtp({ email, otp }), forgetPassword.emailOtp({ email }),
emailOtp.requestPasswordReset({ email }), and
emailOtp.resetPassword({ email, otp, password }). emailOTPClient() is
accepted in plugins. On Expo signIn.emailOtp keeps the session token in
storage, as signIn.email does. The client answers { success: true }
for a malformed address, as core does; only the server's
/email-otp/send-verification-otp path answers INVALID_EMAIL. Through the
client, every policy refusal of emailOtp.resetPassword spends the code,
the length cases too.
An absolute callbackURL or redirectTo keeps its path only when its origin
is the page's origin, and the server's authtempo.appURL must be that
origin, because core lands every sign-in on appURL. Any other absolute value
answers INVALID_CALLBACK_URL or INVALID_REDIRECT_URL with status 403, as
Better Auth's origin check does. A trusted origin that is not appURL is
refused too. In React Native there is no page origin, so use a path.
On Expo, expoClient({ scheme, storagePrefix, storage }) keeps the session
token in storage and sends it as the bearer header. getCookie() answers
__Host-tempo_session=<token>, which the server reads as the session cookie.
The storage key keeps the name of plan 9, <storagePrefix>_tempo_session, so
an app update signs no Expo user out.
signIn.email and signUp.email run in the app. signIn.social and
signIn.magicLink run in the system browser through authtempo's handoff and
need webBrowser (the expo-web-browser module) and crypto (the
expo-crypto module) in expoClient; without them they answer NOT_SUPPORTED.
createAuthClient() with no baseURL does not throw when the module loads.
This matters for a Next server render of a client module. The client reads the
base at the first call: baseURL, else the page's location.origin. A call
with neither answers the error code BASE_URL_REQUIRED.
A baseURL that is not an absolute http or https URL (for example
/api/auth) throws one error when the client is made. A throw of the Expo
token store's setItem answers UNEXPECTED_RESPONSE with status 0. The call
does not reject. A useSession listener may call refetch on every notify.
The store starts no read for a call made while it notifies, so the reads end.
A listener that refetches later (for example in a timer or an effect) on every
notify still reads with no end. Refetch on a change of the data, not on every
notify.
The store is the session store of @authtempo/client (plan 11d); this package
maps its state to Better Auth's shape.
signIn.email with rememberMe: false answers NOT_SUPPORTED (501): core
keeps no short session. rememberMe: true works.
fetchOptions.onSuccess runs once per call, with the last successful
response. A failed sub-request of a call that sends several (for example the
invitation list for a member below admin) never reaches it. The session read
that inviteMember and getFullOrganization make for the active organization
does not call it.
| Client-only error | error.code | error.status |
| --- | --- | --- |
| No network answer | NETWORK_ERROR | 0 |
| The person cancels a passkey or sign-in prompt | AUTH_CANCELLED | 0 |
| The handoff redirect does not match | INVALID_REDIRECT_URL | 403 |
| An answer that the client cannot read, or a passkey prompt that fails in the browser | UNEXPECTED_RESPONSE | the HTTP status, or 0 for the browser failure |
| A call with no baseURL and no page location | BASE_URL_REQUIRED | 0 |
Status 0 means that no HTTP response exists. Do not test status >= 400 alone
for these. The handoff mismatch also has no HTTP response, but it answers 403:
INVALID_REDIRECT_URL has one status everywhere, the one in the table below
(plan 9b).
The shim's own codes name the cases that no core code names. The server api
throws them as APIError with this status, and the client answers them as
error.code with this status. COMPAT_CODES holds this table, and a test
checks each row here.
| Code | Status | Case |
| --- | --- | --- |
| INVALID_CALLBACK_URL | 403 | A callbackURL on an origin that is not appURL |
| INVALID_REDIRECT_URL | 403 | A redirectTo on an origin that is not appURL |
| NO_ACTIVE_ORGANIZATION | 400 | An invitation with no organizationId and no active organization |
| INVITATION_NOT_FOUND | 404 | api.cancelInvitation with an unknown row id |
| NOT_SUPPORTED | 501 | An argument or call that core does not serve |
| BASE_URL_REQUIRED | 0 | A client call with no baseURL and no page location; no request goes out |
| EMAIL_CAN_NOT_BE_UPDATED | 400 | updateUser with email (plan 12a) |
| FIELD_NOT_ALLOWED | 400 | updateUser with a field other than name and image (plan 12a) |
| ACCOUNT_NOT_FOUND | 400 | unlinkAccount with an id that is not the caller's account (plan 12a) |
| CHANGE_EMAIL_DISABLED | 400 | changeEmail without user.changeEmail.enabled (plan 12a) |
| METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED | 405 | POST /get-session without session.deferSessionRefresh (plan 12a) |
| PASSKEY_NOT_FOUND | 404 | POST /passkey/update-passkey or passkey.updatePasskey with an id that is not a passkey of the caller (plan 12a) |
On Expo, pass expo-secure-store as storage. The client accepts any object
with getItem and setItem, as Better Auth does. With a plain store, such as
localStorage, the session token lies readable at rest, and any script on the
page can read it.
twoFactorClient({ twoFactorPage?, onTwoFactorRedirect? }) (plan 9f):
signIn.email answers { twoFactorRedirect: true, twoFactorMethods: ["totp"]
} for a user with the factor on and calls onTwoFactorRedirect, or sends the
browser to twoFactorPage. The client keeps the challenge in memory, so
twoFactor.verifyTotp({ code }) and twoFactor.verifyBackupCode({ code })
work on Expo with no cookie; on the web, after a reload, they send the
better-auth.two_factor cookie. On Expo, trustDevice: true stores the trust
token under <storagePrefix>_trust_device, and the next signIn.email sends
it. On Expo, a sign-in that answers a challenge also drops the stored session
token: the token of an earlier sign-in is not the new one. twoFactor.enable,
disable, getTotpUri, and generateBackupCodes take the password.
sendOtp, verifyOtp, and disableSession: true answer NOT_SUPPORTED. The
answer type holds twoFactorRedirect only when the client options name
twoFactorClient() in a literal list.
Plugins
| Plugin | What it does on authtempo |
| --- | --- |
| organization | Core's organizations, mailed invitations, and Better Auth's roles: ac, roles, and dynamicAccessControl map onto core's statements, roles, and dynamic roles (see "Access control and roles"). teams maps onto core's teams (see "Teams"). With no roles, the roles are Better Auth's member < admin < owner. sendInvitationEmail is required. Its data.id and data.invitation.id hold the invitation token, not the row id: build the accept link from it, and acceptInvitation({ invitationId }) sends it back. api.createInvitation and api.cancelInvitation use the row id. |
| passkey | Core's passkeys. rpID, rpName, and origin are required; each origin must be baseURL or in trustedOrigins. registration.requireSession: true maps. requireSession: false, resolveUser, and afterVerification are refused: core makes every user. Core's passkey.signUp is the sign-up by passkey, and the shim does not map it (deviation 6 of plan 12i). |
| magicLink | Core's magic link with its confirm page. sendMagicLink is required. Without the plugin the magic link paths answer 404. |
| emailOTP | Core's email codes (plan 9e): the sign-in code and the reset code. sendVerificationOTP is required. It gets type: "sign-in" or type: "forget-password", never another type, and a reset code goes only to an address with a user, as in Better Auth. Without the plugin core's code routes answer 404. See "Email codes". |
| bearer | Core reads Authorization: Bearer on every route already. The plugin adds set-auth-token to every response that sets the session cookie. |
| expo | Core's handoff for the system browser. trustedOrigins must hold the app scheme, for example reception://. expo-origin becomes origin when a request has none. On Expo, signIn.social and signIn.magicLink open core's sign-in page, which lists every method this server serves: the magic link form only with the magicLink plugin, the password form with emailAndPassword, a social button per provider, and the passkey button with the passkey plugin. The provider is not chosen in advance. A config with expo and none of these methods is refused at start. |
| apiKey | Core's API tokens (plan 12k Task 12): references: "user" gives user tokens (tk_), and "organization" gives organization tokens (to_). See "API keys". |
| twoFactor | Core's TOTP second factor (plan 9f) on the password sign-in. Needs emailAndPassword.enabled. /two-factor/enable (the password) answers { method: "totp", totpURI, backupCodes }; /two-factor/verify-totp with the session turns the factor on and ends the other sessions; at the next sign-in core answers a challenge and sets better-auth.two_factor, and verify-totp or verify-backup-code with that cookie opens the session. trustDevice: true sets better-auth.trust_device for trustDeviceMaxAge (whole days, default 30). disable, get-totp-uri, and generate-backup-codes take the password. send-otp, verify-otp, and method: "otp" answer NOT_SUPPORTED (501). Pass accountLockout: { enabled: false }: core has no account lockout. user.twoFactorEnabled comes from core's ta_second_factor row; the Better Auth twoFactor table is not read. Backup codes are 23 characters (backupCodeOptions.length 23 to 32). Core's gate on the magic link, the email code, social, and the phone code stays off, as in Better Auth. A reset by code of a user with the factor on opens no session on a device that is not trusted (plan 12c). |
| admin | Core's operator tools (plan 12f). Needs organization and authtempo.platformOrganization. See "The admin plugin". |
| sso | Core's OIDC and SAML connections and its domain proof (plan 12d). Needs organization and authtempo.ssoDns. See "SSO and SCIM". |
| scim | Core's SCIM server (plan 12d). Needs organization. Each static credential acts on one organization. See "SSO and SCIM". |
| anonymous | Core's anonymous sign-in (plan 12i Task 16). See "Sign-in plugins". |
| username | Core's username and the password sign-in by username. Needs emailAndPassword.enabled. See "Sign-in plugins". |
| phoneNumber | Core's phone code. sendOTP delivers each code that core makes. Needs authtempo.phone.regions. See "Sign-in plugins". |
| oneTap | Core's ID-token route for Google, with no nonce. Needs socialProviders.google. See "Sign-in plugins". |
| multiSession | Core's multi-session: maximumSessions (2 to 10, default 5) is core's multiSession.max. See "Sign-in plugins". |
| lastLoginMethod | Core's last method cookie under Better Auth's cookie name. See "Sign-in plugins". |
Give each plugin once. A second entry with the same id is refused at start, because the server reads only the first.
The captcha and have-i-been-pwned plugins are refused at start, and the refusal names core's option. Core has both checks (plan 12b): the captcha option with @authtempo/captcha-turnstile, and password.breachCheck with @authtempo/breach-check. This package does not pass these options to core.
Only auth.handler keeps the plugin behavior in this table: the magic link 404, set-auth-token, and the expo-origin rule. auth.tempo.handle serves core's routes directly, without them.
The admin plugin
Better Auth's admin plugin runs on core's operator tools (plan 12f, spec
section 26). Core has no role on a user. A platform operator is a member of
the platform organization with the platform role. Core checks that member at
each call: the platform role, a verified address, a second factor, and a
fresh session. A Better Auth admin with no second factor has no power.
import { admin, organization } from "better-auth/plugins";
betterAuth({
// ...
authtempo: { platformOrganization: "platform" },
plugins: [organization({ sendInvitationEmail }), admin({ adminRoles: ["admin"] })],
});The options:
| Option | On authtempo |
| --- | --- |
| authtempo.platformOrganization | Required with admin, refused without it. The slug of the platform organization. The app's auth.tempo.api.operator.createAdmin creates it with the first operator (see "Admins from Better Auth"). |
| adminRoles | One role of the organization plugin, default admin: a key of its roles, or member, admin, or owner with no roles (plan 12k). It is the platform role. A list with two roles, or a name that is no such role, is refused. |
| impersonationSessionDuration | Seconds, a whole number of minutes from 5 to 240; default 3600. It is core's operator.impersonation.ttlMinutes. Core mails the user a notice at each start. |
| defaultRole | "user" only, Better Auth's default. |
| allowImpersonatingAdmins | false only: core never lets an operator impersonate a platform operator. |
| defaultBanReason, defaultBanExpiresIn, bannedUserMessage, adminUserIds, schema, ac, roles | Refused. Each refusal names spec section 26. |
Four calls that core does not serve answer NOT_SUPPORTED (501) with a
line that names spec section 26. They are /admin/set-user-password,
/admin/list-user-sessions, /admin/revoke-user-session, and
/admin/has-permission. No operator sets a
password (plan 12f2): a password that an operator knows signs in outside an
impersonation. The person resets the password through the reset link. The
refusal comes before any read, so its answer is the same for every user id.
/admin/update-user takes data.name and data.image only, as core's
operator update does (plan 12f2). An empty name clears the name, as null
does. Each other key of data is refused before any read, and nothing is
written. After the password, the shim checks the keys in Better Auth's
order: the role, the ban keys, then the address. It never drops a key in
silence:
| Key of data | Answer |
| --- | --- |
| None | 400 NO_DATA_TO_UPDATE, Better Auth's code. |
| password | 400 PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER, Better Auth's code. The line names spec section 26 and the reset link. |
| role | 403 YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE, Better Auth's code. Use /admin/set-role. |
| banned, banReason, banExpires | 403 YOU_ARE_NOT_ALLOWED_TO_BAN_USERS, Better Auth's code. Use /admin/ban-user and /admin/unban-user. |
| email, emailVerified | 403 YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL, Better Auth's code. The person changes the address and proves it (spec section 8.15 item 5). |
| Any other key | 400 FIELD_NOT_ALLOWED, with a line that names the key and spec section 26. |
/admin/create-user takes email, name, data.emailVerified, and
data.image, as core's operator create does (plan 12f2). An empty name is
no name. The shim sends core's firstSignIn: "none", because Better Auth
mails nothing at create: core writes no invitation and mails no link. The
person signs in by a path of the app, such as the reset link or a magic
link. data.emailVerified: true makes core take the address as proved, and
the audit row records the flag. No later proof of the address resets the
account, so a wrong address gives the account to the owner of that
address. Set it only after your own check of the address. Each other key
is refused before any read, and nothing is written.
The shim never drops a key in silence:
| Key | Answer |
| --- | --- |
| role of a form other than a string or a list of strings, such as null | 400 VALIDATION_ERROR, before any other check, as Better Auth's body schema answers. |
| role or data.role with a value that is no string | 400 INVALID_ROLE_TYPE, Better Auth's code. |
| password | 403 YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD, the code of Better Auth's password set. No operator sets a password; the line names the reset link and spec section 26. |
| role or data.role other than user | 403 YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE, Better Auth's code. Grant the platform role through /admin/set-role. user and ["user"] add nothing. |
| data.banned, data.banReason, data.banExpires | 403 YOU_ARE_NOT_ALLOWED_TO_BAN_USERS, Better Auth's code. Use /admin/ban-user. |
| Any other key of data (name, email, phoneNumber, an added field) | 400 FIELD_NOT_ALLOWED, with a line that names the key and spec section 26. |
A taken address answers 400 USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL and a
malformed address 400 INVALID_EMAIL, as Better Auth answers. An address in
a placeholder form answers 403 HOOK_REFUSED before any write: it reads
back as no address, so it is never proved.
/admin/list-users takes one search. searchValue needs searchField
email (the default) and searchOperator starts_with: core searches the
start of an address, never a part inside it or the name. filterField
email or id with filterOperator eq (the default) is an exact search.
Core lists by id ascending, 1 to 100 users per page, with a cursor and no
total. So sortBy, sortDirection: "desc", and an offset other than 0 are
refused.
/admin/set-role takes the platform role, which grants it, or user, which
revokes it. Any other role is refused.
Each mapped write that takes a body needs content-type: application/json,
as core's operator routes do. A write with another type or with no type
answers 400 VALIDATION_ERROR and changes nothing. The stop of an
impersonation takes no body, so it takes any type.
Each mapped call posts core's operator route with the caller's cookie, so core's guard decides (plan 12f Task 10):
| Call | Core's route | Answer |
| --- | --- | --- |
| GET /admin/list-users
