Harden the admin module after a fresh-context review
Six defects found by an independent review of 7aac07a.
Environment handling now fails safe. NODE_ENV=production was gating the
signing key, the cookie domain, the CORS origin list and invitation-token
logging all at once, and it was documented nowhere - an unset value, which is
what a fresh Plesk vhost gives you, silently degraded all four. Only
'development' and 'test' relax anything now; everything else, unset included,
is strict. The hardcoded fallback secret is gone (dev gets a random
per-process one, so no committed value can ever sign a production cookie),
and invitation-link logging is an explicit ADMIN_LOG_INVITE_LINKS opt-in that
is refused in strict mode.
Rate limiting no longer collapses into a single global bucket. Without
trustedProxies, better-auth rejects a multi-value x-forwarded-for, resolves no
client IP, and keys every request to "no-trusted-ip" - where /sign-in/*
allows 3 requests per 10 seconds, so one noisy client could lock the whole
organisation out. CLIENT_IP_HEADERS and TRUSTED_PROXY_IPS make this explicit,
the unspecified x-forwarded-for fallback is gone, and strict mode warns at
boot when no trusted proxy is configured.
Invite acceptance is transactional. The user and its credential account go in
one runWithTransaction, as better-auth's own sign-up route does. A transaction
cannot span the permission and invitation writes - those use this module's own
pool - so a failure there is compensated: the user row is deleted and the
invitation un-marked, so the link works again instead of leaving the invitee
with a burnt token and an account no route can repair.
The last-admin guards were check-then-act. Two admins each removing the
other's admin permission could both pass the check and both commit, leaving
nobody able to administer anything. The count now runs inside the write
transaction under SELECT ... FOR UPDATE.
Also: lastSignInAt filtered expired sessions in the detail endpoint but not
the list, so the two disagreed; and the integration suite never reset
rateLimit, leaving it one added sign-in away from 429s that look like auth
bugs.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,7 @@ import * as z from 'zod';
|
||||
import {APIError, createAuthEndpoint} from 'better-auth/api';
|
||||
import {setSessionCookie} from 'better-auth/cookies';
|
||||
import {createLocalAccountIssuer} from 'better-auth/db';
|
||||
import {runWithTransaction} from '@better-auth/core/context';
|
||||
import type {BetterAuthPlugin} from 'better-auth';
|
||||
import * as InvitationsService from './invitations.service.js';
|
||||
import * as UsersService from '../users/users.admin.service.js';
|
||||
@@ -105,29 +106,45 @@ export const invitationsPlugin = () => {
|
||||
throw invalidToken();
|
||||
}
|
||||
|
||||
// The user and its credential account go in one better-auth
|
||||
// transaction, the way better-auth's own sign-up route does
|
||||
// it: a half-created account with no password is not
|
||||
// recoverable through any route this API exposes.
|
||||
//
|
||||
// It cannot cover everything, though. `user_app_permissions`
|
||||
// and `invitations` are written through this module's own
|
||||
// Kysely pool, which is a different connection, so no single
|
||||
// transaction spans both. What follows is therefore
|
||||
// compensated by hand rather than rolled back.
|
||||
let user: Awaited<ReturnType<typeof ctx.context.internalAdapter.createUser>> | null = null;
|
||||
try {
|
||||
const user = await ctx.context.internalAdapter.createUser(
|
||||
{
|
||||
email: invitation.email,
|
||||
name: invitation.name,
|
||||
// Accepting a link sent to that mailbox *is* the
|
||||
// proof of address ownership, so there is no
|
||||
// separate verification mail (plan decision 15).
|
||||
emailVerified: true,
|
||||
disabled: false
|
||||
},
|
||||
{method: 'email-password'}
|
||||
);
|
||||
user = await runWithTransaction(ctx.context.adapter, async () => {
|
||||
const created = await ctx.context.internalAdapter.createUser(
|
||||
{
|
||||
email: invitation.email,
|
||||
name: invitation.name,
|
||||
// Accepting a link sent to that mailbox *is*
|
||||
// the proof of address ownership, so there is
|
||||
// no separate verification mail (plan
|
||||
// decision 15).
|
||||
emailVerified: true,
|
||||
disabled: false
|
||||
},
|
||||
{method: 'email-password'}
|
||||
);
|
||||
|
||||
// Same call better-auth's own sign-up route makes, down to
|
||||
// the synthetic issuer - a credential account written any
|
||||
// other way would not be found on sign-in.
|
||||
await ctx.context.internalAdapter.linkAccount({
|
||||
userId: user.id,
|
||||
providerId: 'credential',
|
||||
issuer: createLocalAccountIssuer('credential'),
|
||||
accountId: user.id,
|
||||
password: await ctx.context.password.hash(ctx.body.password)
|
||||
// Same call better-auth's own sign-up route makes,
|
||||
// down to the synthetic issuer - a credential account
|
||||
// written any other way is not found on sign-in.
|
||||
await ctx.context.internalAdapter.linkAccount({
|
||||
userId: created.id,
|
||||
providerId: 'credential',
|
||||
issuer: createLocalAccountIssuer('credential'),
|
||||
accountId: created.id,
|
||||
password: await ctx.context.password.hash(ctx.body.password)
|
||||
});
|
||||
|
||||
return created;
|
||||
});
|
||||
|
||||
await UsersService.setPermissions(user.id, invitation.apps, null);
|
||||
@@ -139,12 +156,34 @@ export const invitationsPlugin = () => {
|
||||
user: {id: user.id, email: user.email, name: user.name}
|
||||
});
|
||||
} catch (e: any) {
|
||||
// The invitation is already marked accepted at this
|
||||
// point. Leaving it that way is deliberate: a token that
|
||||
// has been through a half-completed account creation
|
||||
// should not stay usable. The admin can send a new
|
||||
// invitation, and this log says why one is needed.
|
||||
logger.error('Admin: invitation accepted but account creation failed', {
|
||||
// Undo what committed, so the invitee can use their link
|
||||
// again instead of being stranded with a burnt token, an
|
||||
// account they cannot sign into, and an admin who cannot
|
||||
// re-invite them (the create route 409s on an existing
|
||||
// user, and there is no delete route by design).
|
||||
//
|
||||
// Deleting the user is safe here: it was created moments
|
||||
// ago in this request, and acceptance already established
|
||||
// that no account for this address existed before.
|
||||
try {
|
||||
if (user) {
|
||||
await ctx.context.internalAdapter.deleteUser(user.id);
|
||||
}
|
||||
await InvitationsService.unmarkAccepted(invitation.id);
|
||||
} catch (compensationError: any) {
|
||||
// Now the state really is inconsistent, and only a
|
||||
// human can sort it out. Say so loudly and precisely.
|
||||
logger.error('Admin: invitation acceptance failed AND its rollback failed', {
|
||||
invitationId: invitation.id,
|
||||
email: invitation.email,
|
||||
userId: user?.id,
|
||||
detail: e?.message,
|
||||
compensationDetail: compensationError?.message
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
|
||||
logger.error('Admin: invitation acceptance failed and was rolled back', {
|
||||
invitationId: invitation.id,
|
||||
detail: e?.message
|
||||
});
|
||||
|
||||
@@ -3,10 +3,9 @@ import * as InvitationsService from './invitations.service.js';
|
||||
import * as UsersService from '../users/users.admin.service.js';
|
||||
import {isAppName, AppName} from '../admin.schema.js';
|
||||
import {sendInvitationMail} from '../admin.mail.js';
|
||||
import {ADMIN_APP_URL} from '../admin.config.js';
|
||||
import {ADMIN_APP_URL, LOG_INVITE_LINKS} from '../admin.config.js';
|
||||
import {sendServerError} from '../admin.errors.js';
|
||||
import logger from '../../../middleware/logger.js';
|
||||
import {isProd} from '../admin.config.js';
|
||||
|
||||
export const invitationsRouter = express.Router();
|
||||
|
||||
@@ -21,14 +20,16 @@ export const invitationsRouter = express.Router();
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
/**
|
||||
* Outside production the Salesforce relay is normally off, so the invitation
|
||||
* mail never arrives and only the token's hash is stored - there would be no
|
||||
* way to walk through the accept flow locally. Logging the link closes that,
|
||||
* and mirrors what the bootstrap already does. Never in production: the log
|
||||
* would then hold a live credential.
|
||||
* With the mail relay off (the normal local setup) the invitation mail never
|
||||
* arrives, and only the token's hash is stored, so there would be no way to
|
||||
* walk through the accept flow. Logging the link closes that.
|
||||
*
|
||||
* Gated on an explicit opt-in rather than on NODE_ENV: the link is a live
|
||||
* account-creation credential, and "not production" is too weak a condition to
|
||||
* hang that on. See LOG_INVITE_LINKS in admin.config.ts.
|
||||
*/
|
||||
const logInviteLinkInDev = (token: string): void => {
|
||||
if (!isProd) {
|
||||
if (LOG_INVITE_LINKS) {
|
||||
logger.info(`Admin: invitation link ${ADMIN_APP_URL}/accept-invite?token=${encodeURIComponent(token)}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -133,6 +133,19 @@ export const markAccepted = async (invitationId: number): Promise<boolean> => {
|
||||
return Number(result.numUpdatedRows) > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverses markAccepted. Used only to compensate a failed acceptance: the user
|
||||
* could not be created, so the link must become usable again rather than
|
||||
* stranding the invitee with a burnt token and no account.
|
||||
*/
|
||||
export const unmarkAccepted = async (invitationId: number): Promise<void> => {
|
||||
await db
|
||||
.updateTable('invitations')
|
||||
.set({accepted_at: null})
|
||||
.where('id', '=', invitationId)
|
||||
.execute();
|
||||
};
|
||||
|
||||
export const listOpenInvitations = async (): Promise<OpenInvitation[]> => {
|
||||
const rows = await db
|
||||
.selectFrom('invitations')
|
||||
|
||||
Reference in New Issue
Block a user