Repository navigation
Expand file tree
/
Copy pathauth-manager-after-hook.ts
More file actions
487 lines (461 loc) · 25.8 KB
/
Copy pathauth-manager-after-hook.ts
File metadata and controls
487 lines (461 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#25224 cut 12] The global after-hook of the better-auth instance
* `AuthManager` builds — the one `hooks.after` middleware `createAuthInstance`
* hands better-auth, which every endpoint's response passes through — moved
* out of `auth-manager.ts` whole.
*
* A MOVE, not a redesign. The function below is the body of the arrow
* `createAuthInstance` passes to `createAuthMiddleware` for `hooks.after`, as
* it stood, re-indented four levels and otherwise unedited: the same bearer
* rotation on impersonation, the same echo of the installed session token,
* the same session envelope completion, the same two-factor re-enrolment
* reset, the same sign-in outcome count, refusal audit, concurrent-session cap
* and login stamp, the same password-change stamp and history commit, the
* same old-address notice on an e-mail change, the same directory doors
* narrowed for an external caller, the same invite-role refusal code, and the
* same sign-up stamp and `disableSignUp` restore — in the same order.
*
* ## How the moved body reaches the class
*
* The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts`
* header carries the full reasoning), which the eleven `auth-manager-*.ts`
* modules split out before this one follow, applied to a closure instead of a
* method. `createAuthInstance` keeps its place, its docblock and its
* signature, and `hooks.after` keeps its place in the config literal: the
* arrow there is now one literal of exactly the {@link AfterHookHost} members
* the body reads, plus a `.call`. The `async` moved from that arrow to the
* function below, and the arrow returns the function's own promise, so the
* middleware awaits the same promise the body settles, with no extra wrapper.
*
* The body's `this` was the manager, the arrow's lexical receiver; it is now
* that host. Every member it reads is a method, and each goes as a closure
* that calls it on the manager at call time, so a test double or spy set on
* the manager is still the one the body reaches. The arrow builds the host
* each time better-auth runs the hook, as every method stub in this series
* does, so nothing the body reads is captured early. The arrow read no local
* of `createAuthInstance`, so the function takes the same one parameter.
*
* Nothing re-exports this module, so the published surface does not move.
*/
import { codeSelfServiceRefusal } from './account-self-service-refusal-code.js';
import { BANNED_USER_CODE, causeBannedUserRefusal } from './banned-user-refusal-cause.js';
import type { AuthManager } from './auth-manager.js';
import { refusalCodeOf } from './auth-session-audit.js';
import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js';
import { narrowDirectoryForExternalCaller } from './external-directory-door.js';
import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js';
import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js';
import { carryRefusalReasonOnCallback } from './oauth-callback-refusal-reason.js';
import { rotateCallerBearerOnImpersonation } from './impersonation-bearer-rotation.js';
import { stampInvitationDeliveryOutcome } from './invitation-delivery-outcome.js';
import { retireExpiredInvitationsOnReissue } from './invitation-expired-supersede.js';
import { codeInviteRoleNotFound } from './invite-role-not-found-code.js';
import { explainUntrustedDiscoveryRefusal } from './sso-discovery-companion-origins.js';
import { readRequestClientAddress } from './request-client-address.js';
import { stampRoleChangeGrantedSet } from './role-change-granted-set.js';
import { attachSessionToCredentialResponse } from './session-envelope-completion.js';
import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js';
import { resetVerifiedOnTwoFactorReenrollment } from './two-factor-reenrollment-verified-reset.js';
import { echoInstalledSessionToken } from './two-factor-rotated-token-echo.js';
/**
* The `AuthManager` members the function below reads — every one of them, and
* no other. Each is typed AS the class member (an indexed access on the
* class), so a change to a member's signature on the class is a change here
* too, and naming a member the class does not have is a compile error.
*/
export interface AfterHookHost {
auditRefusedSignIn: AuthManager['auditRefusedSignIn'];
enforceConcurrentCap: AuthManager['enforceConcurrentCap'];
externalDirectoryDoorDeps: AuthManager['externalDirectoryDoorDeps'];
isEmailDeliveryLive: AuthManager['isEmailDeliveryLive'];
logDurabilityDegradation: AuthManager['logDurabilityDegradation'];
recordPasswordHistory: AuthManager['recordPasswordHistory'];
roleChangeGrantDeps: AuthManager['roleChangeGrantDeps'];
sendChangeEmailNotice: AuthManager['sendChangeEmailNotice'];
settleSignInAttempt: AuthManager['settleSignInAttempt'];
settleSsoProviderDelete: AuthManager['settleSsoProviderDelete'];
settleSsoSignOutOfIdp: AuthManager['settleSsoSignOutOfIdp'];
stampLastLogin: AuthManager['stampLastLogin'];
stampPasswordChangedAt: AuthManager['stampPasswordChangedAt'];
}
/**
* #8019 — who the change-email notice goes to: the user of the session the
* endpoint acted on. `undefined` when that user carries no address, and then
* no notice is sent.
*/
function changeEmailFrom(user: unknown): { email: string; name?: string; id?: string } | undefined {
const u = (user ?? {}) as { email?: unknown; name?: unknown; id?: unknown };
if (typeof u.email !== 'string' || !u.email) return undefined;
return {
email: u.email,
...(typeof u.name === 'string' && u.name ? { name: u.name } : {}),
...(typeof u.id === 'string' && u.id ? { id: u.id } : {}),
};
}
/**
* The user of the session the endpoint acted on, as better-auth's session
* middleware recorded it on `ctx.context.session` before the handler ran.
*/
function actingUserIdOf(ctx: any): string | undefined {
const id: unknown = ctx?.context?.session?.user?.id;
return typeof id === 'string' && id !== '' ? id : undefined;
}
/**
* ADR-0069 D1 — the account a successful password change's after-effects
* (the `password_changed_at` stamp, the forced-change flag it clears, the
* history entry) land on, or `undefined` when they land on none.
*
* `/change-password`: the account the endpoint acted on
* ({@link actingUserIdOf}), and only when the before-hook's password checks
* ran for that same account (`__osPwChangeUserId`, stashed beside them). A
* clear of the forced-change flag is the verdict those checks gate, so an
* account they did not judge is given none of it, and no account but the one
* changed is ever stamped.
*
* `/reset-password`: no session is involved; the account is the reset
* token's, which the before-hook resolved, as before.
*/
function passwordChangeAfterEffectsAccount(ctx: any): string | undefined {
const checkedFor: unknown = ctx?.context?.__osPwChangeUserId;
const checked = typeof checkedFor === 'string' && checkedFor !== '' ? checkedFor : undefined;
if (ctx?.path !== '/change-password') return checked;
const acting = actingUserIdOf(ctx);
return acting !== undefined && acting === checked ? acting : undefined;
}
/**
* ADR-0069 D2 — the `/sign-in/email` refusals that come AFTER the password
* passed, which the lockout counter neither counts nor clears: only a refused
* credential counts toward a lock. better-auth's `signInEmail` throws
* `INVALID_EMAIL_OR_PASSWORD` for a wrong password before it reaches either
* place these are raised, so a wrong password never carries one of them to
* the counter:
*
* - `EMAIL_NOT_VERIFIED` (`BASE_ERROR_CODES`), thrown by `signInEmail` itself
* right after the password verified, when the deployment requires a
* verified address;
* - the organization's own allowed IP ranges (`SESSION_SCOPING_REFUSAL`),
* judged where the new session is scoped to it (`refuseUnadmittedScoping`,
* at session creation);
* - a ban ({@link BANNED_USER_CODE}, better-auth's admin plugin, from its
* `session.create.before` hook), judged at session creation too.
*
* A function, read when a sign-in is judged, rather than a set built when this
* module loads: `organization-access-policy.ts` imports `auth-manager.ts`,
* which reaches this module, so on that import order its constant is not yet
* initialised while this module evaluates; and better-auth is loaded lazily,
* as everywhere in this package.
*/
async function refusedAfterTheCredential(returned: unknown): Promise<boolean> {
const code = refusalCodeOf(returned);
if (code === undefined) return false;
const { BASE_ERROR_CODES } = await import('@better-auth/core/error');
const after: readonly string[] = [
BASE_ERROR_CODES.EMAIL_NOT_VERIFIED.code,
SESSION_SCOPING_REFUSAL.code,
BANNED_USER_CODE,
];
return after.includes(code);
}
/** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */
export async function globalAfterHook(this: AfterHookHost, ctx: any) {
// ── #8243: impersonation must actually take effect for a bearer ──
// FIRST among the after-hooks that touch the response, because the
// bearer plugin's own after-hook runs behind this one and must see
// what we stage: it re-reads `Access-Control-Expose-Headers` to add
// `set-auth-token`, so the recovery header we expose here survives
// only by being merged before it. See
// `impersonation-bearer-rotation.ts` for the mechanism — the short
// version is that `bearer()` converts the caller's token back into
// the ADMIN's session cookie on every later request, so without
// rotating that token, `/admin/impersonate-user` is a 200 no-op.
await rotateCallerBearerOnImpersonation(ctx);
// ── #10701: a 2FA verification must echo the session it INSTALLED ─
// On the enrolment lane `/two-factor/verify-totp` rotates the
// caller's session and then echoes the PRE-rotation token — the row
// it just deleted. A client that stores it (the console's
// `auth-session-token` pattern) is holding a revoked credential, and
// because `bearer()` overwrites the request cookie with whatever the
// Authorization header carries, presenting it destroys the valid
// rotated cookie too. See `two-factor-rotated-token-echo.ts`. This
// corrects the echoed VALUE only; resolver precedence is untouched.
await echoInstalledSessionToken(ctx);
// ── #17234: complete the SessionResponse envelope with the session
// the route just committed ────────────────────────────────────────
// `/sign-in/email` and `/sign-up/email` answer `{ token, user }`
// (plus `redirect` on sign-in) with no `session` member anywhere in
// the body or the headers, so `SessionResponseSchema` never parsed
// either method's return value. The session is not absent — it is
// the row `internalAdapter.createSession` already committed before
// the endpoint returned — so this reads it back by the response's
// own token, the same seam `/get-session` uses, and attaches it.
// See `session-envelope-completion.ts` for the full measurement and
// why this can never fabricate an id or an expiry.
await attachSessionToCredentialResponse(ctx);
// ── #10700: `verified` must describe the secret stored beside it ──
// A second `/two-factor/enable` on an already-confirmed account
// rewrites the TOTP secret on the one `sys_two_factor` row the
// account has and INHERITS `verified` from the enrollment before it,
// so a secret nobody confirmed is honoured at the sign-in challenge.
// better-auth already gates that challenge on the flag — a first
// enrollment is inert until the session-lane verify flips it — so
// restoring the flag restores the gate rather than adding a second
// one. See `two-factor-reenrollment-verified-reset.ts`, whose header
// also states what this deliberately does NOT do.
await resetVerifiedOnTwoFactorReenrollment(ctx);
// ── A banned user's token introspects as inactive while the ban holds ──
// `/oauth2/introspect` only: an active answer whose subject is a user
// whose ban holds becomes `{ active: false }`, the answer a token that is
// not valid gets. See `oauth-token-read-ban-refusal.ts`.
await refuseIntrospectionForBannedSubject(ctx);
// ── [#32085] A deleted SSO provider takes its dependents with it ──────
// `/sso/delete-provider` only, and only once the vendor answered
// `success`: remove the provider's IdP group mappings and the grants
// whose reason is its projection marker, then name in the answer the
// users the delete unlinked, those with no other sign-in method linked,
// and what was removed (counted by the before-hook ahead of the
// vendor's writes).
// See `sso-provider-lifecycle.ts`.
if (ctx?.path === SSO_PROVIDER_DELETE_PATH) await this.settleSsoProviderDelete(ctx);
// A refused platform sign-in: the environment's callback hands the host's
// reason on to the sign-in page (`oauth-callback-refusal-reason.ts`).
carryRefusalReasonOnCallback(ctx);
// Ruling record 6866334319: an OIDC provider saved with "sign out of the
// company sign-in too" on keeps the end_session_endpoint its before-hook
// read (`sso-sign-out-of-idp.ts`).
if (ctx?.path === '/sso/register' || ctx?.path === '/sso/update-provider') await this.settleSsoSignOutOfIdp(ctx);
// ── ADR-0069 D2: account lockout (counter) ──────────────────
// On every password door (`/sign-in/email`, `/sign-in/phone-number`).
// better-auth catches an INVALID_EMAIL_OR_PASSWORD APIError and runs
// the after-hook with it on `ctx.context.returned`; a success leaves
// the session payload there. The gate stamped this attempt as a
// failure before the check; settle that stamp now: a success clears
// the counter, a failure keeps it. A refusal `refusedAfterTheCredential`
// names is neither: the password passed and a policy then refused the
// sign-in, so the stamp is handed back and the counter is left as it
// stood. Its `login_failed` row is still written below.
const passwordDoor = passwordSignInDoorOf(ctx);
if (passwordDoor) {
const { door, identifier: email } = passwordDoor;
if (email) {
let succeeded = true;
try {
const { isAPIError } = await import('better-auth/api');
succeeded = !isAPIError(ctx?.context?.returned);
} catch {
succeeded = !(ctx?.context?.returned instanceof Error);
}
const settlement = await this.settleSignInAttempt(
email,
succeeded
? 'succeeded'
: await refusedAfterTheCredential(ctx?.context?.returned)
? 'refused-after-credential'
: 'refused',
door,
);
// A refused sign-in writes `login_failed`, and the one that
// stamped the lockout also writes `account_locked`. A successful
// one is recorded as `login` by the session hook, unchanged. A
// sign-in refused because the account is locked had its row
// written by the gate, with the lock as its reason.
if (!succeeded && !settlement.refusedByLock) await this.auditRefusedSignIn(ctx, email, settlement, door);
// The session controls and the last-login stamp below are the email
// door's, as before.
if (succeeded && door === 'email') {
const uid = ctx?.context?.returned?.user?.id;
// [ADR-0069 TL;DR 6] The cap of the organization the new session
// was scoped to at creation (ADR-0093 D9), never above the
// deployment's.
const scopedOrg = ctx?.context?.newSession?.session?.activeOrganizationId;
if (typeof uid === 'string') {
const newSessionId = ctx?.context?.newSession?.session?.id;
await this.enforceConcurrentCap(
uid,
typeof scopedOrg === 'string' && scopedOrg ? scopedOrg : undefined,
typeof newSessionId === 'string' ? newSessionId : undefined,
);
}
// ADR-0069 D7 — login audit: stamp last_login_at/ip on success.
// Independent of lockout config (settleSignInAttempt no-ops when
// lockout is off). The IP is the address `handleRequest`
// established for this request by the client-address trust rule,
// the same address the D5 allow-list judged; none when it was
// undetermined. ⛔ Never re-read from a header here.
if (typeof uid === 'string') {
await this.stampLastLogin(uid, await readRequestClientAddress());
}
}
}
// ── A ban the identity provider placed says so ──────────────
// A `403 BANNED_USER` whose ban is the SCIM deactivation's gains
// `details.cause: 'scim_deactivated'`; an administrator's ban is
// answered as before. See `banned-user-refusal-cause.ts`. It throws
// on a match, so it stays after the settlement and the refusal's
// `login_failed` row above. The phone door goes on to the hooks below,
// as before.
if (door === 'email') {
await causeBannedUserRefusal(ctx);
return;
}
}
// ── ADR-0069 D1: on a successful change/reset — stamp
// password_changed_at (expiry) and commit password history.
//
// Every after-effect lands on ONE account, read by
// `passwordChangeAfterEffectsAccount`: on `/change-password` the account
// the endpoint itself acted on — the session better-auth's
// `sensitiveSessionMiddleware` recorded on `ctx.context.session` before
// the handler ran, the reading the change-email notice below takes — and
// only when the before-hook's reuse and forced-change checks ran for that
// same account. The history entry is the old hash those checks read, so it
// is appended only to the account it was read from.
if (ctx?.path === '/change-password' || ctx?.path === '/reset-password') {
let succeeded: boolean;
try {
const { isAPIError } = await import('better-auth/api');
succeeded = !isAPIError(ctx?.context?.returned);
} catch {
succeeded = !(ctx?.context?.returned instanceof Error);
}
if (succeeded) {
const stampId = passwordChangeAfterEffectsAccount(ctx);
if (stampId) {
await this.stampPasswordChangedAt(stampId);
const stash = ctx?.context?.__osPwHistory;
if (stash?.userId === stampId) await this.recordPasswordHistory(stash.userId, stash.oldHash);
} else if (ctx?.path === '/change-password' && actingUserIdOf(ctx)) {
// The password changed, but the checks that gate these writes never
// judged the account it changed on: nothing is stamped, so a forced
// change stays outstanding and the user is asked again (the safe
// direction), and the operator is told, here.
this.logDurabilityDegradation(
'AuthManager: a password change succeeded, but its password_changed_at stamp, the '
+ 'must_change_password clear and the history entry were NOT written: the password '
+ 'checks before it (reuse, forced change) did not run for the account it changed. '
+ 'The new password works; any forced change stays outstanding, so the user is asked '
+ 'to change it again at the next sign-in, and the password-age clock keeps its old '
+ 'start. Remedy: none needed per request; the next change whose checks run re-stamps.',
new Error('password checks did not run for the acting account'),
{ object: 'sys_user', fields: ['password_changed_at', 'must_change_password'] },
);
}
}
delete ctx.context.__osPwChangeUserId;
delete ctx.context.__osPwHistory;
return;
}
// ── #8019: tell the OLD address, without gating on it ──────────────
// Maintainer ruling 2026-08-12 — 「notify the OLD address — do not
// gate on it」. See the `changeEmail` config site for why this cannot
// be `sendChangeEmailConfirmation` (that option IS the gate).
//
// Why HERE is the whole design:
// • after-hook ⇒ better-auth has already produced its response, so
// nothing this code does can change the endpoint's outcome. The
// "does not gate" property is structural, not a promise;
// • gated on success ⇒ a refused request sends nothing;
// • `sendChangeEmailNotice` swallows its own failures ⇒ a dead
// mailbox, an unseeded template or a missing transport cannot
// turn the notification into a block. That inversion — a security
// notice that takes the flow down with it — is precisely the
// failure mode the ruling exists to avoid.
//
// Sent at REQUEST time, which is also the strongest moment available:
// the owner learns while the attacker still has to prove control of
// the new mailbox, so the warning arrives inside the window where it
// can still be acted on. It is also the only moment that exists
// exactly once per attempt — the apply step (`GET /verify-email`)
// does not carry the old address, and better-auth mints a fresh
// session there when the link is opened without one, so an
// apply-time notice would silently miss that path.
//
// The address the notice goes to is the one the account holds as the
// request arrives, read from the session the endpoint itself acted on:
// better-auth's `sensitiveSessionMiddleware` resolves the caller before
// the handler runs and records that session on `ctx.context.session`,
// whatever credential carried it, and the handler never writes that object.
// So it names the account the request changes, with the address as it
// stood. No before-hook can read it: the endpoint resolves its caller only
// after every before-hook has run.
if (ctx?.path === '/change-email') {
const from = changeEmailFrom(ctx?.context?.session?.user);
let succeeded: boolean;
try {
const { isAPIError } = await import('better-auth/api');
succeeded = !isAPIError(ctx?.context?.returned);
} catch {
succeeded = !(ctx?.context?.returned instanceof Error);
}
const newEmail = typeof ctx?.body?.newEmail === 'string' ? ctx.body.newEmail : '';
if (succeeded && from?.email && newEmail) {
// #14319 — the notice goes to the account owner, who IS the
// caller here, so the request rung applies.
await this.sendChangeEmailNotice(from, newEmail, ctx);
}
// #29163 — the vendor's uncoded refusals here carry a ledgered code
// (see `account-self-service-refusal-code.ts`). It throws on a match,
// so it stays last in this section.
await codeSelfServiceRefusal(ctx);
return;
}
// ── Ruling 6355206139 E2: the directory doors, narrowed for an external ──
// list-members, get-full-organization, list-teams and list-invitations
// check membership only, so an `external` caller would read every
// fellow member, team and pending invitation there. See
// `external-directory-door.ts`.
await narrowDirectoryForExternalCaller(ctx, this.externalDirectoryDoorDeps());
// ── #27843: invite-member says whether its mail was delivered ──
// A success answers `outcome: 'sent' | 'link_only'` beside the
// invitation row, by the one deliverability rule sign-up uses (see
// `invitation-delivery-outcome.ts`). A refusal passes untouched.
await stampInvitationDeliveryOutcome(ctx, () => this.isEmailDeliveryLive());
// ── #28540: a new invitation retires the person's expired pending one ──
// The vendor skips an expired row when it looks for one to renew, so a
// resend (or an invite) on it issues a new invitation; the expired row is
// moved to `expired` here, so the Pending list holds one row per person
// (see `invitation-expired-supersede.ts`). A refusal retires nothing.
await retireExpiredInvitationsOnReissue(ctx);
// ── #27862: a role change names the permission set it granted ──
// The before hook read the member's org-admin grants; a success that
// left a new one held answers `outcome: 'permission_set_granted'` and
// `grantedPermissionSet: { name, label }` beside the member row (see
// `role-change-granted-set.ts`). A refusal passes untouched.
const roleChangeDeps = this.roleChangeGrantDeps();
if (roleChangeDeps) await stampRoleChangeGrantedSet(ctx, roleChangeDeps);
// ── #24750: invite-member's unknown-role refusal carries its code ──
// better-auth throws it with only a message; the spec promises
// `ROLE_NOT_FOUND` (see `invite-role-not-found-code.ts`). It throws
// on a match, so it stays after every section above.
await codeInviteRoleNotFound(ctx);
// ── An untrusted discovery endpoint: say how to name it explicitly ──
// `/sso/register` only; the same status and code, the remedy appended to
// the vendor's message (`sso-discovery-companion-origins.ts`).
await explainUntrustedDiscoveryRefusal(ctx);
// ── #29163: update-user's uncoded refusal carries its code ──
// Same seam as the change-email section above; throws on a match.
await codeSelfServiceRefusal(ctx);
if (ctx?.path !== '/sign-up/email') return;
// ADR-0069 D1 — stamp password_changed_at for a newly-created local
// user (expiry clock starts at sign-up). Best-effort.
{
const newUserId = ctx?.context?.returned?.user?.id;
let signupOk: boolean;
try {
const { isAPIError } = await import('better-auth/api');
signupOk = !isAPIError(ctx?.context?.returned);
} catch {
signupOk = !(ctx?.context?.returned instanceof Error);
}
// [#25060] Not for an existing address answered as a success: that
// answer's user id belongs to no row, and nothing was created.
if (signupOk && typeof newUserId === 'string' && ctx?.context?.__osExistingAddressSignUp !== true) {
await this.stampPasswordChangedAt(newUserId);
}
}
const ep = ctx?.context?.options?.emailAndPassword;
if (ep && ctx.context.__osDisableSignUpOrig !== undefined) {
ep.disableSignUp = ctx.context.__osDisableSignUpOrig;
delete ctx.context.__osDisableSignUpOrig;
}
}