Skip to content

fix(auth): keep a failing auth hook from failing login, signup and email verification - #436

Merged
omegascorp merged 6 commits into
modelence:mainfrom
Mohil-Ahuja:fix/auth-hooks-cannot-fail-auth
Nov 16, 2026
Merged

omegascorp merged 6 commits into
modelence:mainfrom
Mohil-Ahuja:fix/auth-hooks-cannot-fail-auth

Conversation

@Mohil-Ahuja

@Mohil-Ahuja Mohil-Ahuja commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

magicLink.ts runs its auth hooks through fireAuthHook, so a hook that throws or rejects is logged and never changes the auth result. The other paths call the hooks directly inside their try blocks:

  • login.ts and loginWithOAuth.ts: onAfterLogin, onLoginError, login.onSuccess, login.onError
  • signup.ts: onAfterSignup, onSignupError, signup.onSuccess, signup.onError
  • verification.ts (handleVerifyEmail and handleVerifyEmailMutation): onAfterEmailVerification, onEmailVerificationError
  • providers/oauthCommon.ts (the Google and GitHub callbacks): onAfterLogin and login.onSuccess for existing-user and auto-link logins, onAfterSignup and signup.onSuccess for new users, onLoginError/login.onError, and onSignupError/signup.onError in reportSignupError

A hook that throws turns a completed operation into an error:

  • In handleLoginWithPassword the new session is already started and its cookie set when onAfterLogin runs, yet the client gets a 500 with the hook's message and onLoginError fires. The browser is signed in while the client sees a failed login.
  • In handleSignupWithPassword the account is already inserted and the verification email sent, so the client is told signup failed and a retry hits "already exists".
  • In handleVerifyEmail the address is verified but the user is redirected with status=error.
  • In the OAuth callbacks the session is started and the redirect sent before the hooks run. A throwing hook fires the error hooks for a login or signup that succeeded, and the provider's catch then calls sendOAuthError after the response was already sent.
  • A throwing error hook (onSignupError, onEmailVerificationError, ...) replaces the real error.

An async hook that rejects is not awaited or caught. startServer's unhandledRejection handler keeps the process running, but the log is a generic Unhandled Promise Rejection that doesn't name the hook. safelyCallHook in oauthCommon.ts only caught synchronous throws, so the async onAfterOAuthLink and onOAuthLinkError had the same gap.

Change

fireAuthHook moves from magicLink.ts to auth/utils.ts, and every hook call above goes through it, including the deprecated login/signup callbacks. safelyCallHook is removed and its call sites use fireAuthHook too. Hook failures, sync or async, are logged as Error in <hook> hook:. The hooks still run at the same points with the same arguments. onBeforeSignup is still awaited and not wrapped, since it's a veto.

The notify-only hook types are widened from (...) => void to (...) => void | Promise<void>, which documents that async hooks are supported. fireAuthHook's invoke parameter is no longer optional. The AuthConfig JSDoc states the contract: notify-only hooks aren't awaited, their failures are logged without changing the response, and onBeforeSignup is the exception.

In loginWithOAuth.ts, the error path copies provider to a const so its narrowing holds inside the callback.

Tests

  • login.test.ts: a throwing onAfterLogin and a rejecting login.onSuccess leave the login successful, without firing the error hooks
  • signup.test.ts: a throwing onAfterSignup and a rejecting signup.onSuccess still return the new user id, without firing the error hooks
  • verification.test.ts: a rejecting onAfterEmailVerification still redirects with status=verified; in handleVerifyEmailMutation, a rejecting onAfterEmailVerification still resolves, and a throwing onEmailVerificationError doesn't replace the real error
  • oauthCommon.test.ts: failing login and signup hooks, including the auto-link login, still redirect without an error response; failing login error hooks don't replace the real error in either OAuth login path; throwing/rejecting signup error hooks don't replace the real error; a rejecting onAfterOAuthLink is logged and the link still completes

The throwing and rejecting mocks use mockImplementationOnce / mockRejectedValueOnce, so they don't leak into later tests. All 12 new tests fail against main's source. The test files that mock ./utils or ../utils now pass the real fireAuthHook through.

tsc --noEmit, eslint, prettier, npm run build and npm run test (122 files, 1573 tests) pass.


Note

Medium Risk
Touches core authentication flows and hook contracts; behavior change is intentionally safer for clients but apps that relied on hook failures to block auth will see different outcomes.

Overview
Auth notify hooks no longer flip successful logins, signups, and verifications into failures when analytics or other side-effect code throws or rejects.

A shared fireAuthHook helper is centralized in auth/utils.ts (replacing the magic-link–local copy and OAuth’s safelyCallHook) and wraps login, signup, email verification, OAuth, and magic link paths. Hook errors are logged and reported to telemetry without changing the HTTP response or masking the underlying auth error. onBeforeSignup stays awaited as the veto hook.

Types and docs now allow void | Promise<void> on notify-only callbacks and document that these hooks are fire-and-forget. Tests cover hook failures across password login, signup, verification, and OAuth flows.

Reviewed by Cursor Bugbot for commit 6f53fbe. Bugbot is set up for automated code reviews on this repo. Configure here.

…ail verification

The password login, OAuth login, password signup and email verification
paths called the onAfter*/on*Error hooks (and the deprecated login/signup
callbacks) directly inside their try blocks. A hook that threw made a
completed login or signup report an error to the client (after the session
cookie was set, or after the account was created), and an async hook that
rejected was an unhandled rejection that can take the process down.

Move magicLink's fireAuthHook into auth/utils and route every hook call
through it, so hook failures are logged and never change the auth result.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the approach is right. Every changed call site now goes through fireAuthHook with the same timing and arguments. onBeforeSignup is still awaited and is not wrapped, which is correct because it's a veto. The failedProvider const is fine, and claimed.provider is equivalent to the old provider because it's assigned just before. Before this can merge, it needs a rebase and has some gaps.

Blocking

1. Conflicts with main in verification.ts. This branch is based on b7a462b. Since then #446 removed session creation from handleVerifyEmail and added the alreadyVerified short-circuit, and #423 added handleVerifyEmailMutation. After rebasing:

  • Please wrap both hooks in handleVerifyEmailMutation too. They are still called directly on main, so it's the same bug in a newer path.
  • The new verification test mocks createSession, which handleVerifyEmail no longer calls. Please drop that mock.

I rebased locally and kept main's verification.ts. The other tests in login, signup, magicLink, loginWithOAuth and verification (129) pass. Only the new verification test fails, which is expected until the conflict is resolved.

2. The OAuth callback hooks in providers/oauthCommon.ts are still called directly. This is the main web path for Google and GitHub sign-in, and it has exactly the bug this PR describes:

  • Existing-user login (onAfterLogin / login.onSuccess, ~L320): authenticateUser has already started the session and redirected when the hook runs. If the hook throws, onLoginError and login.onError fire for a login that succeeded. Then the provider's catch in google.ts / github.ts calls sendOAuthError(res, 500, ...) after the response has already been sent.
  • Existing-email auto-link login (~L432): same pattern.
  • New-user signup (onAfterSignup / signup.onSuccess, ~L582): the user is inserted and the session started first. A throwing hook means reportSignupError fires and the user sees an error.
  • reportSignupError (~L474): calls onSignupError and signup.onError directly, so a throwing error hook replaces the real error.

The reasoning in this PR applies to all of these, so they seem in scope. If you'd rather do a follow-up PR, please say in the description that OAuth-callback hooks are not covered here.

Should fix

3. Two hook helpers. oauthCommon.ts already has safelyCallHook (~L676). It only catches synchronous throws, so an async onAfterOAuthLink or onOAuthLinkError that rejects is still an unhandled rejection. Now that fireAuthHook is in auth/utils, please replace safelyCallHook with it. That also gives these hooks the same Error in <hook> hook: log format.

Nits

  • Async hooks are now handled on purpose, so widening the hook types from (...) => void to void | Promise<void> would document that.
  • The | undefined on fireAuthHook's invoke parameter is no longer needed, because every caller passes a closure.
  • The signup test only covers a synchronous throw. A rejecting signup.onSuccess case, like the one in the login test, would cover the async branch.

@omegascorp

Copy link
Copy Markdown
Collaborator

Two more things after checking this against main. The change is worth doing: I ran the new login and signup tests against main's unchanged code, and both fail with the hook's own error. On main, a throwing onAfterLogin returns a 500 with the hook's message in the body, while the response still sets the new authToken cookie. The client sees a failed login while the browser is actually signed in.

1. Please correct the crash claim in the description. startServer installs a process-level unhandledRejection handler that only logs (app/server.ts, ~L236). So in an app started the normal way, a rejecting async hook doesn't exit the process. Today it produces a generic Unhandled Promise Rejection log that doesn't name the hook. With this PR, it's logged as Error in <hook> hook: instead. That's still a good reason to wrap async hooks, but it's a logging improvement, not a crash fix. Please reword the description so the release notes don't overstate it.

2. The new tests leak throwing mocks into later tests. beforeEach calls vi.clearAllMocks(), which clears call history but not the implementations set with mockImplementation or mockRejectedValue. So the throwing onAfterSignup (signup test) and the throwing onAfterLogin plus rejecting login.onSuccess (login test) stay set for every test that runs after them. I ran the new signup.test.ts against unchanged main, and 8 unrelated signup tests also fail with analytics down. They pass on this branch only because the fix tolerates the leaked failure. If this path regresses, the failure would show up in nine tests instead of one. Please use mockImplementationOnce / mockRejectedValueOnce, or reset these mocks in the test's finally.

…ot-fail-auth

# Conflicts:
#	packages/modelence/src/auth/verification.ts
Wrap the onAfterLogin, login.onSuccess/onError, onLoginError, onAfterSignup,
signup.onSuccess and onSignupError/signup.onError calls in oauthCommon, and
replace safelyCallHook with fireAuthHook so async link hooks that reject are
caught and every hook failure is logged with the hook's name.

Type the notify-only hooks as returning void | Promise<void>, and make the
throwing and rejecting mocks in the new tests one-shot so they don't leak
into later tests.
@Mohil-Ahuja

Copy link
Copy Markdown
Contributor Author

@omegascorp thanks for the thorough review. All addressed in 5d07b3e:

  1. Merged main into the branch (7607f5e) rather than rebasing, to avoid force-pushing over the review. verification.ts keeps main's version, with both hooks in handleVerifyEmailMutation and handleVerifyEmail wrapped. The createSession mock is gone from the new test, and there are two new handleVerifyEmailMutation tests.
  2. Covered the OAuth callback hooks in oauthCommon.ts here: both login paths, new-user signup and reportSignupError. Each has a test.
  3. Replaced safelyCallHook with fireAuthHook, so a rejecting onAfterOAuthLink / onOAuthLinkError is caught, with a test for the link case.

Also fixed the crash claim in the description (it's now described as a logging improvement), made the throwing and rejecting mocks one-shot, widened the hook types to void | Promise<void>, dropped | undefined from invoke, and added a rejecting signup.onSuccess case.

The 9 new tests fail against main's source. lint, prettier, tsc --noEmit, build and the full suite (1570 tests) pass.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround. Everything from the first round is addressed, and I think this is ready to merge. The two nits below don't block it.

Checked

  • Coverage: Every notify-only hook call in src/ now goes through fireAuthHook. That's 39 call sites in login, loginWithOAuth, signup, verification (both handlers), magicLink and oauthCommon (both login paths, new-user signup, reportSignupError and all six link-hook calls). None are left that call a hook directly, and safelyCallHook is gone.
  • Behavior: Each hook still runs synchronously at the same point with the same arguments, so the sync part of a hook still runs before the function returns. onBeforeSignup is still awaited and not wrapped.
  • Merge: The merge from main kept main's verification.ts, including the alreadyVerified short-circuit. The branch merges cleanly into the current main.
  • Tests: I swapped in main's versions of the changed source files, with a pass-through fireAuthHook. Exactly the 9 new tests fail, and every other auth test passes, so the one-shot mocks no longer leak into later tests. On this branch, vitest run src/auth passes (605 tests), and eslint and prettier are clean.

Nits

  • The auto-link login path and the OAuth login error paths have no failing-hook test (inline comment below).
  • The hook JSDoc could state the contract that is now enforced (inline comment below).

connectionInfo,
});
authConfig.login?.onSuccess?.(updatedUser);
fireAuthHook('onAfterLogin', () =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, not blocking: this auto-link login path has no failing-hook test. Neither do the two OAuth login catch blocks (login.onError / onLoginError at L332 and L450). The change here is mechanical, so I'm fine merging without them. If you want parity with the existing-provider test, one case with oauthAccountLinking: 'auto' and a throwing onAfterLogin would cover this path.

* Use for analytics, audit logging, or post-login side effects.
*/
onAfterLogin?: (props: AuthSuccessProps) => void;
onAfterLogin?: (props: AuthSuccessProps) => void | Promise<void>;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: now that this behavior is enforced, the JSDoc could say it. These hooks are not awaited, and a throw or rejection is logged as Error in <hook> hook: and doesn't affect the response. One sentence on AuthConfig, or on each notify-only hook, would tell app authors not to rely on a hook finishing before the client gets its response. It would also make it clear that onBeforeSignup is the exception.

Add failing-hook tests for the auto-link login path and for both OAuth login
catch blocks, and document on AuthConfig that the notify-only hooks are not
awaited and that their failures are logged without changing the response.
@Mohil-Ahuja

Copy link
Copy Markdown
Contributor Author

@omegascorp thanks, both nits done in b25c128:

  • Tests for the auto-link login path (a throwing onAfterLogin and a rejecting login.onSuccess) and for both OAuth login catch blocks (a throwing login.onError and a rejecting onLoginError don't replace the real error).
  • The AuthConfig JSDoc now states the contract: the notify-only hooks may be async but aren't awaited, a throw or rejection is logged as Error in <hook> hook: and doesn't change the response, and onBeforeSignup is the exception.

The 12 hook tests fail against main's source. lint, prettier, tsc --noEmit, build and the full suite (1573 tests) pass.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, both nits are addressed in b25c128. The new auto-link and login-error tests look right, and the JSDoc states the contract clearly.

One blocker: #454 landed on main and conflicts with this branch in magicLink.ts, providers/oauthCommon.ts and verification.ts. #454 changed hook-failure logging to logError(msg, { error }) plus captureError(error), so failures reach telemetry. When you merge main:

  • Port that into fireAuthHook in auth/utils.ts, as on main:
    const reportHookError = (error: unknown) => {
      logError(`Error in ${name} hook:`, { error });
      captureError(error);
    };
    try {
      Promise.resolve(invoke()).catch(reportHookError);
    } catch (hookError) {
      reportHookError(hookError);
    }
  • In oauthCommon.ts, keep the @/telemetry import, because sendOAuthError uses it, and still remove safelyCallHook.
  • In verification.ts, keep the fireAuthHook wrap and drop the console.error('Error verifying email:') line, because main now logs after the if.
  • Update the new tests to match. verification.test.ts and oauthCommon.test.ts already mock @/telemetry on main, so assert on mockLogError with { error: expect.any(Error) }, and ideally check mockCaptureError too. For login.test.ts and signup.test.ts, mock @/telemetry the same way, or assert { error: expect.any(Error) } on the console spy.

I tried this resolution locally. With it, only the 12 new tests fail, all on their log assertions, and the rest of the auth suite passes.

@Mohil-Ahuja

Copy link
Copy Markdown
Contributor Author

@omegascorp thanks for working out the resolution. Merged main in 02afc33, done the way you described:

  • fireAuthHook in auth/utils.ts reports through logError(msg, { error }) and captureError(error), and the copy main added to magicLink.ts is gone, so there is one helper.
  • oauthCommon.ts keeps the @/telemetry import for sendOAuthError and drops safelyCallHook.
  • verification.ts keeps the fireAuthHook wrap without the console.error line.
  • The hook tests assert on mockLogError with { error: expect.any(Error) } and on mockCaptureError. login.test.ts and signup.test.ts now mock @/telemetry like the others.

The full suite passes (1650 tests), along with tsc, eslint and prettier.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @Mohil-Ahuja looks good

@omegascorp
omegascorp merged commit 91d9565 into modelence:main Nov 16, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants